Java is a platform and programming language. It tops the list of all programming languages and offers a variety of job options. The purpose of understanding Java interview questions for freshers is to familiarise you with the types of questions you might be asked during your Java-related interviews. Java Training in Chennai is the ideal setting for exploring your profession if youโre curious about learning the language.
Core Java Concepts
1. What various access specifiers are there for Java classes?
The terms used before a class name in Java that correspond to the access scope are considered access classifiers.
Public available from anywhere; a field, method, or class. When a field or method is protected, it can only be accessed within the class to which it belongs, from subclasses, and within the same package class.
By default, only code from the same packageโnot code from outside the native packageโcan access a classโs field or method. The method is accessible from the same class to which it belongs via the private field.
2. What is the difference between a Subclass and an Inner class?
Inner class
A class defined inside another class is known as an inner class. It has access rights to the class that contains it, which means it can access all the outer classes. There are variables and methods declared.
Subclass
A subclass, a derived class, inherits from a superclass. It has access to every superclassโs protected and open fields and methods.
Sample code demonstrating an inner class and subclass relationship:
publicclassOuterClass{
private int outerVariable;
publicvoidouterMethod(){
System.out.println("This is the outer method");
}
publicclassInnerClass{
publicvoidinnerMethod(){
outerVariable =10;// Accessing the outer variable
outerMethod();// Accessing the outer method
System.out.println("This is the inner method");
}
}
}
publicclassSubClassextendsSuperClass{
publicvoidsubClassMethod(){
protectedField =20;// Accessing the protected field of the superclass
publicMethod();// Accessing the public method of the superclass
System.out.println("This is the subclass method");
}
}
// Usage of the inner class and subclass
OuterClass outerObject =newOuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.innerMethod();
SubClass subObject =newSubClass();
subObject.subClassMethod();
3. What is data encapsulation?
This is frequently asked in most Core Javainterview questions for freshers.
Data encapsulation is a fundamental principle in object-oriented programming that involves bundling data (attributes) and the methods (operations) that interact with that data into a single unit, known as an object. This encapsulation ensures data security and modularity.
Encapsulating data within an object allows you to control access to it through well-defined methods. This prevents unauthorised access or modification, protecting the integrity of your data. This is often referred to as data hiding.
Sample code demonstrating data encapsulation:
publicclassPerson{
private String name;
private int age;
publicvoidsetName(String newName){
name = newName;
}
public String getName(){
return name;
}
publicvoidsetAge(int newAge){
age = newAge;
}
public int getAge(){
return age;
}
}
publicclassMain{
publicstaticvoidmain(String[] args){
Person person =newPerson();
person.setName("John");
person.setAge(25);
System.out.println("Name: "+ person.getName());
System.out.println("Age: "+ person.getAge());
}
}
4. What do static methods and variables accomplish?
In your Java developer interview preparation, it’s important to understand static variables and static methods. They share a variable or a method instead of making unique copies for every item. They divide one object of a class across several others.
By declaring a method or variable as static, it becomes shared and can be accessed directly through the class itself rather than through an instance of the class. This allows for efficient memory utilisation and enables convenient access to common resources or operations that are not specific to individual object instances.
5. What do Java loops do? Which three types of loops are there?
This is one of the must-know Java interview questions for experienced developers. Loops in Java are used to execute a statement or a block of statements repeatedly. There are 3 types of loops in Java:
For Loops:
For loops execute statements a specified number of times. They are commonly used when the number of iterations is known in advance.
While Loops:
When it is necessary to execute statements repeatedly While loops are used until a specific condition is fulfilled. This type of condition is evaluated before the execution of the statements.
Do-While Loops:
Do-while loops are similar to while loops but with one difference: the condition is evaluated after the execution of the statement block. By doing this, even if the condition is initially false, it is ensured that the assertions are carried out at least once.
6. What is a Singleton Class? Can you provide an example?
The Java Interview Questions And Answers for freshers list is complete with this question. In Java, a singleton class can have only one instance, which owns all of its variables and methods. The singleton class pattern is used when the number of objects created for a class needs to be restricted.
An example of using a singleton is when there is a requirement to have a single connection to a database only because of driver or licencing restrictions.
publicclassDatabaseConnection{
privatestatic DatabaseConnection instance;
privateDatabaseConnection(){
// Private constructor to prevent direct instantiation
}
publicstatic DatabaseConnection getInstance(){
if(instance ==null){
instance =newDatabaseConnection();
}
return instance;
}
publicvoidconnect(){
System.out.println("Connected to the database");
}
}
publicclassMain{
publicstaticvoidmain(String[] args){
DatabaseConnection connection = DatabaseConnection.getInstance();
connection.connect();
}
}
7. Describe the distinctions between the โbreakโ and โcontinueโ statements
The โbreakโ and โcontinueโ statements are key concepts used in loops. Providing examples during Java interviews for freshers can help illustrate these concepts.
When a loop is discovered, the โbreakโ command is used to end it instantly. It completely exits the loop, regardless of the loop condition. For example:
for(int counter =0; counter <10; counter++){
System.out.println(counter);
if(counter ==4){
break;
}
}
The โcontinueโ statement, on the other hand, is utilised to skip the current iteration of a loop and move on to the subsequent iteration. It allows the loop to continue its execution. For example:
for(int counter =0; counter <10; counter++){
System.out.println(counter);
if(counter ==4){
continue;
}
System.out.println("This will not be printed when counter is 4");
}
Using these statements provides control over loop execution, allowing specific conditions to be met to terminate or skip iterations. Memorise these statements as a part of your Java developer interview preparation.
8. What is an infinite loop? How is an infinite loop declared?
An infinite loop is a loop which runs indefinitely without any condition to terminate it. To break out of an infinite loop, a breaking logic or condition must be included within the loopโs statement block.
An infinite loop can be declared as follows:
for(;;){
// Statements to execute
// Add any loop-breaking logic
}
9. What is the โfinalโ keyword in Java used for? Can you provide an example?
Constant declaration in Java requires the usage of the โfinalโ keyword. A final variableโs value cannot be altered once it has been assigned.
Hereโs an example of declaring a constant named const_val:
private final int const_val =100;
Additionally, the โfinalโ keyword has other uses in Java. When a method is marked as final, subclasses cannot override it. Final methods are resolved at compile time, making them faster than other methods.
This is an important topic which is asked in Java interview questions for freshers.
10. What are the Java float and double variables differences?
In Java, the float and double variables differ in their precision and memory size.
The float variable represents a single-precision floating-point decimal number and typically occupies 4 bytes of memory. It offers less precision compared to double.
On the other hand, the double variable represents a double-precision decimal number and usually occupies 8 bytes of memory. Compared to float, it provides higher precision and a wider range of values.
11. How can you generate random numbers in Java?
In Java, there are several methods for producing random numbers. One approach is by using the Math.random() method, which generates random double values between 0.0 (inclusive) and 1.0 (exclusive). To obtain random numbers within a specific range, you can multiply the result of Math.random() by the desired range and add an offset value.
double randomValue = Math.random();// Generates random value between 0.0 and 1.0
double scaledValue = randomValue *(max – min)+ min;// Generates random value within a specific range
You can brush up on your knowledge and succeed in your interview with the help of these Java interview questions for freshers.
12. What is a ternary operator? Can you provide an example?
The conditional operator, commonly called the ternary operator, is used to make decisions and assign a value to a variable based on the evaluation of a Boolean expression.
publicclassConditionTest{
publicstaticvoidmain(String[] args){
String status;
int rank =3;
status =(rank ==1)?"Done":"Pending";
System.out.println(status);
}
}
The ternary operator is a concise way to make decisions and assign values based on conditions in Java.
13. What is the Java basic class that all other classes are descended from?
The Java foundation class, from which all other classes are descended, is java.lang.Object.
14. What is a default case in a switch statement? Can you provide an example?
The default case is used in a switch statement when none of the other switch conditions match. It acts as an optional case that is executed when no other cases are satisfied.
The default case should be placed after all the other cases have been coded within the switch statement.
publicclassSwitchExample{
publicstaticvoidmain(String[] args){
int score =4;
switch(score){
case1:
System.out.println("Score is 1");
break;
case2:
System.out.println("Score is 2");
break;
default:
System.out.println("Default Case");
}
}
}
The default case provides a fallback option when none of the other cases matches in a switch statement.
15. What are Java packages? What is the significance of packages?
This seems like one of the basic Java interview questions and answers for freshers.
Packages are a way to organise code in Java and group related classes, interfaces, and other code elements together. They allow developers to modularise their code, making it easier to manage and reuse.
Packages contain a logically related collection of classes and interfaces. By organising code into packages, developers can improve code organisation and maintainability.
One significant benefit of using packages is the ability to control access to classes and encapsulate code within a specific namespace. This helps prevent naming conflicts and provides a clear boundary for accessing code from other packages.
Packages also facilitate code reuse by allowing the importation of classes and resources from other packages. Once code is packaged in a particular package, it can be easily imported into other classes and used without duplicating the code.
16. Does the main() method in Java return any data?
The main() method in Java does not return any data. As a result, a void return type is always stated when it is used. You can brush up on your knowledge and succeed in your interview with the help of this kind of Java interview questions for freshers.
17. Explain the difference between an Interface and an Abstract Class in Java.
The following is the main difference in Java, between an abstract class and an interface:
Interface
An interface can only declare public static method signatures without providing their concrete implementation. It serves as a contract for classes that implement it, ensuring they define the specified methods. Interfaces can also declare constants and can be implemented by multiple classes.
Abstract Class
An abstract class can have members with various access specifiers (private, public, etc.) and can include abstract and concrete methods. It can provide a partial implementation of methods. Abstract classes are designed to be extended by subclasses, which are responsible for implementing abstract methods defined by the abstract class. This is one of the important Java interview questions for experienced.
18. Is it possible to declare a class as an Abstract class without having any abstract methods?
Yes, it is possible to use the abstract keyword before the class name to create an abstract class, even if it doesnโt contain any abstract methods. However, if a class contains at least one abstract method, it must be declared as an abstract class, otherwise it will result in an error.
19. Does importing a package also import its sub-packages in Java?
No, when a package is imported in Java, its sub-packages are not automatically imported. If the developer wants to use classes from the sub-packages, they need to import them separately.
For example, if a developer imports the package university.*, it will load all the classes from the university package, but it will not load classes from its sub-packages. To access classes from a sub-package, the developer needs to import them like this explicitly:
import university.department.*;
This is one of the basic Java interview questions and answers to know before attending an interview.
20. What are the performance implications of interfaces compared to abstract classes?
Interfaces are generally considered to have slightly slower performance than abstract classes due to the additional indirections required for interfaces. Another important consideration for developers is that a class can only extend a single abstract class while it can implement multiple interfaces.
Using interfaces also imposes an additional responsibility on developers. When a class implements an interface, the developer is obligated to implement all the methods defined in that interface.
Object Oriented Programming (OOP) Concepts
This section will fundamentally delve into OOP concepts that often come up in the Java interview questions and answers for freshers.
21. Constant declaration in Java requires the usage of the โfinalโ keyword. A final variableโs value cannot be altered once it has been assigned.
In Java, passing arguments to a function by reference is impossible. Java only supports passing arguments by value, where a copy of the value is passed to the function. This means the original variable outside of the function is unaffected by changes made to the parameter inside the function.
In contrast to other programming languages, such as C++, Java does not provide direct support for passing arguments by reference.
22. Is it possible to declare the main method of a class as private?
No, the main method should be declared public static to run applications correctly in Java. If the main method is declared as private, it will compile without any errors. However, it will not be executed and will result in a runtime error.
23. When should we use serialisation?
Serialisation is commonly used when data needs to be transmitted over a network. By using serialisation, an object’s state can be converted and saved into a byte stream. This byte stream can then be transferred through the network, and the object can be reconstructed at the destination. Serialisation is particularly useful when working with distributed systems, client-server communication, or persistent object storage.
This is one of the typical Java interview questions and answers.
24. How does Java serialise an object?
In Java, an object can be serialised by implementing the Serializable interface. By implementing this interface, the class can convert its objects into a byte stream through serialization. When a class implements the Serialisable interface, most of its objects can be serialised, and their state can be stored in the byte stream. This allows the object to be easily transmitted or stored persistently.
You can advance in your chosen career with the aid of these Java questions and answers.
25. Is there a way to skip the final block even if an exception occurs within the catch block?
In Java, the finally block is always carried out regardless of whether an exception occurs or not. It is not possible to directly skip the finally block based on an exception in the catch block.
However, if you want to terminate the program forcefully and avoid executing any statements in the final block, you can use the System.exit(0) code line at the end of the try block. This will abruptly terminate the program and prevent the execution of subsequent code, including the final block. Itโs important to note that using System.exit(0) should be done cautiously, as it terminates the entire Java program abruptly.
26. Does Javaโs Try block have to be followed by a Catch block in order to handle exceptions?
One of the most common Java interview questions for freshers is whether a Try block must always be followed by a Catch block. In Java, a Try block must be followed by either a Catch block, a Finally block, or both. Whenever an exception is raised inside the Try block, it must be caught and handled in the Catch block. Alternatively, specific tasks that need to be executed before the termination of the code can be placed in the Finally block.
The Catch block allows for catching and handling specific exceptions, allowing one to handle exceptions gracefully or perform error logging. Code that must always be run is specified regardless of whether an exception happens or not, in the Finally block. It is typically used for tasks such as closing resources or releasing acquired locks.
27. Can a class have multiple constructors?
Yes, a class may have several constructors with various inputs. The constructor used for object creation depends on the arguments passed during the object’s instantiation. This allows flexibility in creating objects with different initialisations based on the constructor used.
With the aid of these Java interview questions for freshers, you may increase your knowledge and succeed in your interview.
28. When is the class constructor invoked?
The class constructor is invoked every time an object is created using the new keyword.
For example, in the following class, the constructor is invoked twice when two objects are created using the new keyword:
publicclassConstExample{
ConstExample(){}
publicstaticvoidmain(String args[]){
ConstExample c1 =newConstExample();
ConstExample c2 =newConstExample();
}
}
29. In the following example, what can be the output?
publicclassSuperclass{
publicvoiddisplayResult(){
System.out.println("Printing from superclass");
}
}
publicclassSubclassextendsSuperclass{
publicvoiddisplayResult(){
System.out.println("Displaying from subclass");
super.displayResult();
}
publicstaticvoidmain(String args[]){
Subclass obj =newSubclass();
obj.displayResult();
}
}
Output:
Displaying from subclass
Printing from superclass
Explanation:
The main method is invoked, creating an object of the Subclass class. The displayResult method is then called on this object. The output will first display โDisplaying from subclassโ as it is defined in the Subclass class. After that, the super.displayResult() line calls the displayResult method of the superclass Superclass, resulting in the output โPrinting from superclassโ being displayed.
It is regarded as one of the Java basic interview questionsthat candidates must be familiar with before attending an interview.
30. Is it possible to override static methods of a class?
No, static methods cannot be overridden. Static methods belong to the class rather than individual objects and are resolved at compile time. We will not encounter a compilation error when we try to replace a static method. However, the overriding will not have any effect when executing the code.
To enhance your programming skills, Java Training in Pondicherry offers specialized courses and expert instruction tailored to your career objectives.
Java String and Memory Management
31. how many string objects can be produced in the following example?
String s1 =”I am Java Expert”;
String s2 =”I am C Expert”;
String s3 =”I am Java Expert”;
Answer: Two objects of the java.lang.String class have been created in the above example. Both s1 and s3 reference the same object, which contains the text โI am Java Expertโ.
32. Is a string considered a data type in Java?
No, a string is not classified as a primitive data type in Java. When a string is created, it is actually an object of the java.lang.String class that is created. Once a string object is created, various built-in methods of the String class can be used on the string object.
One of the Java questions and answers that is regularly asked is this one.
33. What distinguishes a vector from an array?
An array collects information of a static, same primitive type, but vectors are believed to be dynamic in nature and hold the data of multiple data types.
import java.util.Vector;
publicclassVectorExample{
publicstaticvoidmain(String[] args){
// Creating a vector
Vector names =newVector<>();
// Adding elements to the vector
names.add("John");
names.add("Alice");
names.add("Bob");
// Accessing elements from the vector
System.out.println("First name: "+ names.get(0));
System.out.println("Second name: "+ names.get(1));
System.out.println("Third name: "+ names.get(2));
// Changing an element in the vector
names.set(1,"Eve");
// Removing an element from the vector
names.remove(0);
// Printing all elements in the vector
System.out.println("Elements in the vector: "+ names);
}
}
34. Why are strings known as immutable in Java?
Strings are immutable objects in Java, which means that once a value is assigned to a string, it cannot be changed. If any modifications are made to a string, a new string object is created with the updated value, while the original string object remains unchanged.The integrity and security of Javaโs string objects are guaranteed by their immutability.
Java Multithreading
35. What is Multi-Threading?
Multi-threading is a fundamental programming concept that involves executingconcurrently running many tasks in a same programme. The same process stack is shared by all running threads, enabling improved performance of a program. Multi-threading is an important topic frequently asked in Java interviews. You can better prepare for the interview with the aid of these Java interview questions for experienced.
36. Why does Java employ the Runnable interface?
The Runnable interface is used in Java to facilitate the execution of multi-threaded applications. The java.lang.Runnable interface is created by a class to facilitate the functionality of multi-threading.
37. Which one should be used first when several changes to the data are required? String or StringBuffer?
Unlike Strings, which are immutable, string buffers are dynamic in nature and allow us to change the values of StringBuffer objects. Therefore, it is always a good choice to use StringBuffer when data needs to be changed frequently. When doing so, use a String., Each data modification will result in the creation of a fresh String object, resulting in additional overhead.
38. What are the two ways that Java implements multi-threading?
Java offers two different ways to construct multi-threaded applications:
Implementing the java.lang.Runnable interface: Classes can implement this interface to enable multi-threading. The interface includes a run() method that is executed when the thread starts.
classMyRunnableimplementsRunnable{
publicvoidrun(){
System.out.println("Thread is running using Runnable interface.");
publicclassRunnableExample{
publicstaticvoidmain(String[] args){
MyRunnable myRunnable =newMyRunnable();
Thread thread =newThread(myRunnable);
thread.start();
}
}
Extending the java.lang.Thread class: Multi-threading can be achieved by creating a class that extends the Thread class. The class can override the run() method to specify the programme that will run when the thread begins.
classMyThreadextendsThread{
publicvoidrun(){
System.out.println("Thread is running by extending Thread class.");
}
}
publicclassThreadExample{
publicstaticvoidmain(String[] args){
MyThread myThread =newMyThread();
myThread.start();
}
}
It is one of the crucial Java questions and answersoften asked during an interview.
39. How is garbage collection performed in Java?
In Java, garbage collection occurs automatically when an object is no longer referenced. The object is then automatically removed from memory. Java triggers garbage collection through the Runtime.gc() method or the System.gc() method.
Java Control Flow Statements
40. Why is the โbreakโ statement used each time a switch statement is used?
To make sure that the code exits the switch block following the execution of the valid case, the โbreakโ statement is used after each case in a switch statement (except from the final case). Without the break statement, the code would continue executing the subsequent cases, resulting in incorrect outcomes.The execution flow is controlled and limited to the desired scenario by utilising the break statement.
It is one of the important Java Interview Questions and answers that come up repeatedly during the interview.
41. How do we run Java code before the main method?
To execute statements before object creation and the main method, In the class, we can use a static piece of code. The static block is executed once during the class loading process, even before the main method is invoked. Any statements within this static block are executed before the main method and object creation.
Java Inheritance
42. Can a class function simultaneously as a superclass and a subclass? Give an instance.
When using inheritance hierarchy, a class can serve as a superclass for one class and as a subclass for another class simultaneously.
In the example below, the โcontinentโ class is a subclass of the โworldโ class and, at the same time, a superclass for the โcountryโ class.
publicclassworld{
// ...
}
publicclasscontinentextendsworld{
// ...
}
publicclasscountryextendscontinent{
// ...
}
43. If a class doesnโt have a constructor, how are objects of that class created?
Include this question in your Java developer interview preparation, as it’s one of the most frequently asked: Even if no explicit constructor is defined in a Java class, objects are successfully created because Java automatically provides a default constructor. This default constructor is used when no other constructor is explicitly defined.
Java Synchronization
Java interview questions and answers for experienced often delve into the intricacies of Java synchronization.
44. How do we make sure that in multi-threading, only one thread is using a resource at a time?
Access to shared resources among the multiple threads can be controlled using synchronization in multi-threading. By using the synchronized keyword, We can make sure that only one thread at a time is using the shared resource, while other threads will gain once the resource has been becomes free from the thread currently using it.
Java Object Creation and Access
45. Can an object call a classโ constructor more than once?
No, the constructor of a class can only be called once for an object. It is automatically invoked during the creation of the object using the `new` keyword, and after an object has been constructed, we are unable to directly call its constructor again.
To succeed in the interview, thoroughly prepare for these Java interview questions and answers.
46. There are two distinct classes, Class A and Class B. Both classes are in the same package. Can an object of Class B access a private member of Class A?
A classโs private members cannot be accessed from outside of that class, and this includes other classes in the same package. Therefore, an object of Class B cannot access the private members of Class A.
47. Can two methods with the same name exist in the same class?
Yes, Two methods with the same name but distinct parameters might exist in the same class. The called procedure is determined by the parameters passed when calling the method.
For example, in the following class, there are two print methods with the same name but different parameters. The appropriate method will be called depending on the parameters passed:
publicclassMethodExample{
publicvoidprint(){
System.out.println("Print method without parameters.");
}
publicvoidprint(String name){
System.out.println("Print method with parameter.");
}
publicstaticvoidmain(String[] args){
MethodExample obj1 =newMethodExample();
obj1.print();
obj1.print("xx");
}
}
48. How can we duplicate a Java object?
The idea of cloning can be used to duplicate an object. By implementing the Cloneable interface and using the clone() method, we can create copies of objects with their current state.
You can thoroughly understand the topic before the interview by reading these Java interview questions for freshers.
49. What benefit does employing inheritance provide?
The main upper hand of using inheritance is code reusability, as it allows subclasses to inherit and use the code again from their superclass. Additionally, inheritance enables polymorphism, allowing new functionality to be introduced without impacting existing derived classes.
Hereโs a sample program demonstrating inheritance:
// Superclass
classVehicle{
publicvoidstart(){
System.out.println("Vehicle started.");
}
}
// Subclass inheriting from Vehicle
classCarextendsVehicle{
publicvoidaccelerate(){
System.out.println("Car accelerating.");
}
}
publicclassMain{
publicstaticvoidmain(String[] args){
// Create an object of the Car class
Car myCar =newCar();
// Access methods from both Vehicle and Car classes
myCar.start();// Inherited from Vehicle class
myCar.accelerate();// Specific to Car class
}
}
50. What access specifier does a classโs by default for its variables and methods?
the classโs standard access specifier for variables and methods is โpackage-protectedโ or โdefaultโ. This means that the variables and methods are accessible within the same package, but not outside of it.
51. Give a Java class example where pointers are used.
In Java, the concept of pointers is not directly available as in some other programming languages such as C or C++. Java utilizes references instead of pointers to handle objects. References in Java provide a safe and simplified way to access objects without the need for explicit memory management.
The most common concept in core Java developer interview preparation is pointers in Java
52. How may a classโ inheritance be limited so that no other classes can inherit from it?
If we want to prevent a class from being further extended by any other class, Prior to the class name, we can use the final keyword.
In the following example, the Stone class is declared as final, which means it cannot be subclassed:
public final classStone{
// Class methods and variables
}
By making a class final, we ensure that any other class cannot extend or inherit it. This provides control over the classโs implementation and behaviour, preventing any modifications or extensions.
To stay competitive in the tech industry, Java Training in Coimbatore offers high-quality training and expert guidance, ensuring you remain up-to-date with the latest Java features and best practices.
53. What is the Protected access specifierโs access range?
Prior to the class name, we can use the final keyword.A variable or method becomes available within the same class, any other class of the same package, and also within subclasses when it is specified with the Protected access specifier.
The Protected access modifier allows access to the member variables and methods from within the class itself, from other classes within the same package, and from subclasses of the class, regardless of the package they are in. This provides a level of access that is more restrictive than the default (package-private) access but less restrictive than public access.
Modifier | CLASS | PACKAGE | SUBCLASS | WORLD |
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modifier | Y | Y | N | N |
private | Y | N | N | N |
Before going to any interviews, you must be familiar with these Java interview questions and answers.
54. What distinctions exist between queues and stacks?
A Queue and a Stack are both data structures used for storing and retrieving elements. The main difference between them lies in their ordering principle. The Last In First Out (LIFO) principle is used in a stack. whereas a queue adheres to the First In First Out (FIFO) rule.
Hereโs a sample program to illustrate the distinction between a Java Queue and Stack
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
publicclassQueueVsStackExample{
publicstaticvoidmain(String[] args){
// Creating a Queue
Queue queue =newLinkedList<>();
// Adding elements to the Queue
queue.add("Element 1");
queue.add("Element 2");
queue.add("Element 3");
// Removing and printing elements from the Queue (FIFO)
while(!queue.isEmpty()){
System.out.println(queue.poll());
}
System.out.println();
// Creating a Stack
Stack stack =newStack<>();
// Adding elements to the Stack
stack.push("Element 1");
stack.push("Element 2");
stack.push("Element 3");
// Removing and printing elements from the Stack (LIFO)
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
}
Output
Element 1
Element 2
Element 3
Element 3
Element 2
Element 1
55. How may variable serialisation be forbidden?
One of the frequently asked Java interview questions and answers is how to prevent certain variables from being serialized. To achieve this, we can use the transient keyword when declaring these variables. For example, the variable trans_var below is tagged as temporary and not serialised:
publicclassTransientExample{
private transient int trans_var;
// rest of the code
}
By declaring a variable as transient, it indicates to the Java serialization mechanism that the variable should be excluded from the serialization process. When an object is serialised, the transient variables are not written to the output stream. When the object is deserialized, these variables will have their default values, as they were not saved during serialization.
56. How do you use primitive data types as objects?
By using their respective wrapper classes, primitive data types like int can be treated as objects. For example, The wrapper class for the primitive data type int is an integer. By using wrapper classes, primitive data types can be treated as objects, and various methods can be applied to them, similar to any other object.
Hereโs an example that demonstrates the usage of the Integer wrapper class:
publicclassWrapperExample{
publicstaticvoidmain(String[] args){
int number =10;// primitive data type
Integer wrapperNumber = Integer.valueOf(number);// using wrapper class
// Applying methods to the wrapper class
int result = wrapperNumber.compareTo(5);
System.out.println("Comparison result: "+ result);
String binaryString = wrapperNumber.toBinaryString();
System.out.println("Binary representation: "+ binaryString);
}
}
57. Which exception types are examined at compile time?
Checked exceptions are caught by the compiler at compile time. To ensure successful compilation, checked exceptions must be handled using try-catch blocks or declared using the throws keyword. This is a significant subject that appears in the Java Interview Questions For Experienced.
58. Describe the various states of a thread.
A thread in Java could be in any of the following states:
New: When a thread is created but not started yet, it is in the new state.
Runnable: A thread that is ready to run or is currently running is in the runnable state.
Waiting: A thread that is stand by for another thread to release a lock or for a specific condition to be satisfied is in the waiting state.
Timed Waiting: A thread that is waiting for a certain period of time is in the timed waiting state.
Blocked: A blocked thread that is awaiting a monitor lock to be released is in the blocked state.
Terminated: A thread that has completed its execution or has been terminated abruptly is in the terminated state.
59. Even if an explicit constructor is defined, may the default constructor of a class be used?
In Java, if no explicit constructor is defined in a class, the compiler automatically provides a default no-argument constructor. However, once an explicit constructor is defined in the class, the default constructor is not automatically invoked. The developer can only use the constructors that are explicitly defined in the class.
It is one of the core Java interview questions and answers that is regularly asked.
60. Can a method have a different return type but the same method name and arguments?
In Java, method overriding requires that the method name, arguments, and return type of the overriding method must be exactly the same as the one of the substituted approach. Therefore, if the return type of a method is different, it cannot be considered as overriding the method.
61. What does the code snippet that is listed below produce?
publicclassOperatorExample{
publicstaticvoidmain(String args[]){
int x =4;
System.out.println(x++);
}
}
The code uses the postfix++ operator,This initially returns the value before increasing it. Therefore, the output will be 4.
62. Is it feasible to claim that a Java class was properly compiled without even having a main method?
Itโs one of the basic Java questions and answers they frequently ask candidates in an interview. The main method is considered to be an entry point of a Java class and is required for executing the program. However,If a Java class lacks a main method, it can nevertheless be successfully compiled. Note that the class cannot be executed without a main method.
With the help of Java Online Training, gain the information you need to become a Java developer.
63. Can a static method invoke a non-static method from within it?
No, a non-static method cannot be called directly from inside a static method. Non-static methods belong to an instance of a class and require an object to be invoked. In a static method, there is no instance context, so calling a non-static method directly is not possible. To call a non-static methods from a static method, you must first construct an object of the class and then use that object to call the non-static method.
Hereโs an example:
publicclassExample{
publicvoidnonStaticMethod(){
System.out.println("Non-static method");
}
publicstaticvoidstaticMethod(){
Example obj =newExample();// Create an object of the class
obj.nonStaticMethod();// Call the non-static method using the object
}
publicstaticvoidmain(String[] args){
staticMethod();
}
}
With the aid of these Java interview questions for freshers, you may brush up on your knowledge and succeed in your interview.
64. What are the two environment variables that must be established before any Java programme may be run?
To successfully run Java programs on a machine, Two environment variables need to be properly configured, and they are as follows:
PATH variable
- The PATH variable should include the directory path where the Java Development Kit (JDK) binaries are located. This allows the system to locate and execute the Java compiler (javac) and Java Virtual Machine (java) commands.
CLASSPATH variable
- The CLASSPATH variable is used by the Java runtime environment to locate the compiled Java classes and libraries required by the program during runtime. It should include the directories or JAR files containing the compiled classes or libraries.
65. Can a constructor have a different name than the class name in Java?
In Java, a constructor must have the same name as the class it belongs to. If the constructor has a different name, it will not be recognized as a constructor by the compiler and will be treated as a regular method.
66. What will Round(3.7) and Ceil(3.7) produce?
The output of Round(3.7) is 4, and the output of Ceil(3.7) is 4. View these Java interview questions and answers for freshers to see how well they may help you review your knowledge.
67. Can a Java class inherit from multiple classes?
Java does not support multiple inheritance. A class can only derive from one other.
68. Can you use Javaโs go to command to jump to a specific line?
In Java, the โgotoโ keyword does not exist, and the language does not support the capability of jumping to a specific labelled line.
69. Can we revive a dead thread?
A dead thread is a thread that has finished executing its run() method. While it’s not directly possible to “revive” a thread once it’s terminated, you can create a new thread with the same or similar functionality. A dead thread is a common topic covered in Java Interview Questions for experienced.
70. Is the class declaration that follows accurate?
The provided class declaration needs to be corrected. In Java, a class cannot be declared as both abstract and final at the same time. The keywords โabstractโ and โfinalโ have conflicting meanings in Java. An abstract class is intended to be subclassed, while a final class cannot be subclassed. Therefore, it is not possible to declare a class as both abstract and final.
If you’re eager to deepen your understanding of Java, enrolling in Java Training in Tirupur offers a well-rounded curriculum and hands-on learning experiences.
71. Is JDK required for Java programs to execute on every computer?
The JDK (Java Development Kit) is primarily used for development purposes It is not necessary for a machine to run a Java program. Instead, only the JRE (Java Runtime Environment) is necessary for running Java programs.
To help you improve your knowledge, we provide you with these Java questions and answers.
72. What makes a comparison using the equals method and the == operator different?
When two string objects are compared, and their contents are found to be identical, the equals() function returns true. On the other hand, the == operator compares the references of the two string objects in Java.
In the below example, the equals() given that the two string objects it returns include the same values. However, the == operator returns false as the two string objects are referencing different objects:
publicclassEqualsTest{
publicstaticvoidmain(String args[]){
String str1 ="Hello World";
String str2 ="Hello World";
if(str1.equals(str2)){
System.out.println("str1 and str2 are similar in terms of values");
}
if(str1 == str2){
System.out.println("Both strings are referencing the same object");
}
else{
System.out.println("Both strings are referencing different objects");
}
}
}
With the help of these Java interview questions for freshers, you may more effectively prepare for the interview.
73. What is == and === in Java?
There is no === operator in Java. The == operator is used to compare the references of two objects. If the references are equal, it means both variables point to the same object in memory. However, if the references are not equal, it means the variables point to different objects, even if their contents are the same.
74. What is equals () method?
The equals() method is used to compare the actual content or values of two objects. It is often overridden in classes to provide a meaningful comparison based on the object’s properties. If two objects have the same content or values, the equals() method will return true, even if they are different objects in memory.”
75. What is the difference between == and string equals?
This is one of the basicJava questions and answers to be familiar as a part of their java developer interview preparation.
In Java, the== operator compares object references. If two string objects have the same reference, it means they are the same object in memory.
Theequals() method compares the content or values of two objects. If two string objects have the same content, even if they are different objects in memory, the equals() method will return true.
76. Can static methods be present in an interface?
In Java, interfaces can contain static methods. Static methods in interfaces can have a defined implementation and can be invoked directly on the interface itself, without the need for an implementing class.
77. How are destructors defined in Java?
Destructors are not defined in Java, as there is no need to explicitly define them. Java has a built-in garbage collection mechanism that automatically allocates memory for discarded items referenced, eliminating the need for explicit destructors.
78. In a class that implements an interface, is it possible to modify the value of any variable defined in the interface?
No, we cannot change the value of any variable defined in an interface in a class implementing that interface. All variables in an interface are, by default, static, public, and final. Final variables are constants and their values cannot be changed once assigned. Therefore, the variable values defined in an interface cannot be modified in the implementing class.
79. Is it true that Javaโs garbage collection function prevents programmes from ever running out of memory?
This is one of the tricky Java interview questions for freshers to check their application ability. The absence of memory issues with Java programmes is not a given. Although Java provides automatic garbage collection, there is still a possibility of running out of memory if objects are created at a faster rate than garbage collection can free up memory resources.
80. Can we use a different return type for void in the main method?
No, for the programme to run successfully, the main method of a Java class can only have a void return type.
However, if you need to return a value upon the completion of the main method, you can use System.exit(int status).
81. Once an item has been garbage collected, I need to use it again. What makes it possible?
An object that has been trash-collected from the heap is permanently deleted and cannot be accessed or referenced again. After it has been garbage collected, there is no way to get the item back or use it.
82. What do you mean by a interface in Java?
An interface in Java serves as a blueprint for a class containing a set of static constants and abstract methods. Each public and abstract method is in an interface and it does not have a constructor. Thus, an interface represents a group of related methods with empty bodies.
Example:
publicinterfaceAnimal{
publicvoideat();
publicvoidsleep();
publicvoidrun();
}
ย 83. What is an association?
Association is a relationship where each object has its own lifecycle, and there is no ownership.Think about the relationship between a teacher and a student, for instance. A single teacher can have many pupils in their class, while a single student might have many teachers in their class. However, the objects have no ownership, and each object has an independent lifecycle. These associations can be one-to-one, one-to-many, many-to-one, and many-to-many.
84. What is composition in Java?
Composition is a specialized form of aggregation, representing a โdeathโ relationship. It is a strong type of aggregation where child objects do not have their own lifecycle. All child objects are also removed if the parent object is erased. For example, consider the relationship between a House and its rooms. A house can contain multiple rooms, but each room cannot belong to multiple houses. If the house is deleted, all rooms associated with it are also deleted.
85. What is a marker interface?
This is quite an important question to be included in your Java developer interview preparation. A marker interface is an interface that does not contain any data members or member functions. It is simply an empty interface. Serializable and Cloneable are two examples of marker interfaces in Java. A marker interface can be declared as follows:
publicinterfaceSerializable{}
86. What is constructor overloading in Java?
In Java, the practice of adding many constructors, each with a unique parameter list, to a class is known as constructor overloading. The compiler uses the number and types of parameters to differentiate between the overloaded constructors.
Example:
classDemo{
int i;
publicDemo(int a){
i = a;
}
publicDemo(int a, int b){
// body
}
}
87. What is a servlet?
Using a server-side technology called a Java servlet which extends the functionality of web servers by enabling dynamic response generation and data persistence. Interfaces and classes for writing servlets are given by the javax.servlet and javax.servlet.http packages.The javax.servlet must be implemented by every servlet.Servlet lifecycle methods are defined by the Servlet interface. The HttpServlet class, an extension of GenericServlet, provides methods like doGet() and doPost() for handling HTTP-specific services.
88. What is a Request Dispatcher?
The RequestDispatcher interface is used to forward a request to another resource, which can be an HTML, JSP, or another servlet within the same application. It can also be used to include the content of another resource in the response.
The RequestDispatcher interface defines two methods:
void forward()
void include()
89. How do cookies work in Servlets?
This is one of the Java interview questions for experienced. Cookies are files that the server sends to the client and stores locally on the clientโs device. Through the javax.servlet.http.Cookie class, which implements the Serializable and Cloneable interfaces, the Servlet API offers cookie functionality. The HttpServletRequest getCookies() method retrieves an array of cookies from the request. However, there are no methods to add or set cookies in the request. Similarly, the HttpServletResponse addCookie(Cookie c) method attaches a cookie in the response header.
90. What are the different method of session management in servlets?
Session management in servlets involves maintaining a conversational state between the client and server. Some common methods of session management include:
- User Authentication
- HTML Hidden Field
- Cookies
- URL Rewriting
- Session Management API
By reading through these Java Programming Interview Questions before the interview, you can have a complete understanding of the subject.
By choosing Java Training in Madurai, youโll gain essential insights and skills that prepare you for the challenges of application development and large-scale software solutions.
91. What is a JDBC Driver?
Java is made possible through a software component called a JDBC Driver. applications to interact with databases. Altogether there are mainly four main types of JDBC drivers:
- JDBC-ODBC bridge driver
- Native-API driver (partially Java driver)
- Network Protocol driver (fully Java driver)
- Thin driver (fully Java driver)
Do not miss to include this question in your Java developer interview preparation.
92. What is a JIT compiler in Java?
The JIT (Just-In-Time) compiler in Java is a program that converts Direct instructions provided to the CPU from Java bytecode. By default, When a Java method is called, In Java, the JIT compiler is activated and launched. It โjust in timeโ converts the bytecode for the method into machine language. following compilation of the procedure, the JVM directly summons the compiled code for execution, rather than interpreting it. The JIT compiler plays a crucial role in optimizing the performance of Java applications at runtime.
93. Define a Java Class.
A Java class is a blueprint that defines the structure and behaviour of objects. It contains fields (variables) and methods to describe the characteristics and actions of an object. The following is the syntax for declaring a class:
classClassName{
// member variables
// class body with methods
}
One of the Java Interview Questions For Freshers that is frequently asked is this particular one.
94. What is Object-Oriented Programming?
The programming paradigm known as โObject-Oriented Programmingโ (OOP) revolves around objects rather than logic and functions. It focuses on organizing programs around objects that need to be manipulated, making it suitable for large and complex codebases that require frequent updates and maintenance.
95. What are the concepts of OOPs in Java?
The main concepts of Object-Oriented Programming (OOPs) in Java are:
- Inheritance: A process where one class acquires the properties and behaviours of another class.
- Encapsulation: A mechanism for wrapping data and code together as a single unit.
- Abstraction: It offers a streamlined interface while concealing the implementation specifics.
- Polymorphism: The capacity of an object to assume different shapes.
96. What is an infinite loop in Java? Explain with an example.
An infinite loop in Java is a sequence of instructions that repeatedly executes without a functional exit condition. This can be the result of a coding error or intentional design based on application behavior. An infinite loop will only terminate when the application is forcibly terminated or interrupted.
Example:
publicclassInfiniteForLoopDemo{
publicstaticvoidmain(String[] args){
for(;;){
System.out.println("Welcome to Edureka!");
// Ctrl + C in the console will end this programme.
}
}
}
97. What is Java String Pool?
The Java String Pool refers to a collection of String objects stored in the heap memory. When a new String object is created, the string pool checks if an identical object already exists. If it does, the reference to the existing object is returned. If not, a fresh object is made in the string pool, and its reference is returned.
98. What is a classloader in Java?
This is an important Java questions and answers. The Java ClassLoader is responsible for loading class files during the execution of a Java program. When a Java program is executed, it is first loaded by the classloader. Java provides three built-in classloaders: the Bootstrap ClassLoader, the Extension ClassLoader, and the System/Application ClassLoader.
99. What is Polymorphism?
โPolymorphismโ refers to an object, function, or variableโs ability to take on a variety of shapes. It allows entities in a program, such as variables and functions, to have more than one implementation. Polymorphism can be achieved through method overloading (compile-time polymorphism) and method overriding (runtime polymorphism).
Spring and Hibernate
This is a concept that often shows up in Java interview questions for experienced.
100. What is Spring?
For the Java platform, Spring is an application framework and inversion of control container. It provides core features that can be used by any Java application, with extensions available for the Java EE platform for developing web applications. Spring is a lightweight and integrated framework used for developing enterprise applications in Java.
101. How to integrate Spring and Hibernate Frameworks?
To integrate Spring and Hibernate frameworks, the Spring ORM module can be used. If Hibernate 3+ is used, where SessionFactory provides the current session, it is recommended to avoid using HibernateTemplate or HibernateDaoSupport classes. Instead, the DAO pattern with dependency injection should be utilized.
Additionally, Spring ORM provides support for declarative transaction management, which is preferred over writing boilerplate code for transaction management in Hibernate.
102. How can exceptions be handled in the Spring MVC Framework?
This is something you only could answer if you have experience, so you can expect this in Java interview questions for experienced.
The Spring MVC Framework offers several approaches for robust exception handling:
Controller-Based: We can define exception handler methods within our controller classes and annotate them with the @ExceptionHandler annotation.
Global Exception Handler: The @ControllerAdvice annotation from Spring can be used with any class to provide a global exception handler. Exception handling is a cross-cutting topic.
Handler Exception Resolver Implementation: In cases where we need to serve static pages for generic exceptions, we can implement the HandlerExceptionResolver interface provided by the Spring Framework. This allows us to create a global exception handler. The advantage of this approach is that Spring Framework offers default implementation classes that can be configured in the Spring bean configuration file to leverage the benefits of Springโs exception-handling capabilities.
J2Ee Interview Questions
103. What are J2EE concepts?
J2EE (Java 2 Platform, Enterprise Edition) is a set of technologies and APIs that provide a framework for developing and deploying enterprise-level Java applications. Key J2EE concepts include:
- Component-based architecture: Applications are built from reusable components like servlets, JSPs, EJBs, and JavaBeans.
- Distributed computing: Applications can be distributed across multiple servers and clients.
- Transaction management: Ensures data consistency and integrity in distributed transactions.
- Security: Provides mechanisms for authenticating users, authorizing access, and protecting sensitive data.
- Web services: Enables interoperability between applications by exposing services over HTTP.
- Enterprise JavaBeans (EJBs): Provides a high-level API for developing server-side business logic.
- JavaServer Pages (JSPs): Dynamic web pages that combine HTML, XML, and Java code.
- Servlets: Java programs that handle HTTP requests and generate responses.
- Java Message Service (JMS): Provides APIs for asynchronous communication between applications.
104. Are Java and J2EE the same?
This is an important question asked J2Ee Interview Questions as it is quite a basic difference every Java developer must know.
No, Java and J2EE are not the same. Java is a general-purpose programming language, while J2EE is a platform specifically designed for developing enterprise applications. J2EE uses Java as its programming language, but it also includes additional APIs and technologies for building distributed, scalable applications.
105. What are the three types of J2EE?
J2EE is no longer divided into three types. In the past, it was divided into Standard, Enterprise, and Personal editions. However, these distinctions have been phased out, and the term “J2EE” is now used to refer to the entire platform.
106. What is the framework in J2EE?
J2EE itself is a framework providing a set of APIs and technologies for building enterprise applications. Within J2EE, there are also specific frameworks like Spring and Hibernate that can be used to simplify development and improve application architecture.
107. Is J2EE front end or backend?
J2EE is primarily a backend technology focusing on server-side components and business logic. However, it can also be used to develop front-end components like JSPs and servlets that interact with the client.
108. What is J2EE called?
This is a pretty basic Java interview questions and answers.
ย J2EE is now called Java EE. The “2” was removed in a later version.
109. What are J2EE components?
J2EE components are reusable building blocks that can be combined to create enterprise applications. Common components include:
- EJBs: Enterprise JavaBeans
- JSPs: JavaServer Pages
- Servlets: Java programs that handle HTTP requests
- JavaBeans: Reusable Java classes
- Web services: Services exposed over HTTP
- Message-driven beans: EJBs that handle asynchronous messages
110. What are J2EE patterns?
J2EE patterns are design patterns specifically tailored for enterprise Java applications. They provide proven solutions to common design problems, helping developers create more robust, scalable, and maintainable applications.
111. Is Servlet a J2EE?
Yes, a servlet is a fundamental component of J2EE. It is a Java program that handles HTTP requests and generates responses.
112. What is the full form of JVM in J2EE?
JVM stands for Java Virtual Machine. It is the runtime environment that executes Java bytecode. It is important J2EE interview question to include in Java developer interview preparation.
113. What is a 2-tier architecture in J2EE?ย
A 2-tier architecture in J2EE refers to a system with two main tiers:
Presentation tier: Handles user interaction and displays data (e.g., JSPs, servlets).
Business tier: Contains the application’s business logic (e.g., EJBs).
114. What is the full form of DD in J2EE?
DD stands for Deployment Descriptor. It is an XML file that contains configuration information for a J2EE application.
115. What is the full form of URL in J2EE?
URL stands for Uniform Resource Locator. It is a unique identifier for a resource on the internet.
In conclusion, mastering Java is essential for any aspiring software developer. These 115 important Java interview questions and answers covering fundamental and advanced topics along with J2Ee interview questions, helping freshers build a strong foundation in Java programming and boost their confidence for job interviews. Youโll be well-prepared to tackle real-world coding challenges by thoroughly understanding these concepts. To learn more about Java Programming, visit FITA Academy for the best Java Training in Bangalore.