Top 30 Java Interview Questions and Answers for 2024.
Basic Java Interview Questions:
1. What is Java?
2. What are the main features of Java?
3. What is the difference between JDK, JRE, and JVM?
4. What is the difference between == and .equals() method in Java?
5. What is the difference between abstract class and interface in Java?
6. Explain the concept of inheritance in Java.
7. What is method overloading and method overriding?
8. What is the difference between checked and unchecked exceptions in Java?
9. What is a constructor in Java?
10. What is the difference between static and non-static methods?
Intermediate Java Interview Questions:
11. What is the purpose of the ‘final’ keyword in Java?
12. Explain the concept of multithreading in Java.
13. What are the synchronization techniques in Java?
14. What is the purpose of the ‘volatile’ keyword in Java?
15. What is the difference between ArrayList and LinkedList?
16. What is the difference between HashMap and HashTable?
17. What is the difference between String, StringBuilder, and StringBuffer?
18. Explain the concept of exception handling in Java.
19. What is the purpose of the ‘super’ keyword in Java?
20. What is the difference between static and dynamic binding?
Advanced Java Interview Questions:
21. Explain the concept of Generics in Java.
22. What are the different types of inner classes in Java?
23. What is the purpose of the ‘transient’ keyword in Java?
24. What is the difference between serialization and deserialization in Java?
25. Explain the concept of reflection in Java.
26. What are the design patterns in Java?
27. Explain the concept of garbage collection in Java.
28. What are the different ways to create a thread in Java?
29. Explain the concept of lambda expressions in Java.
30. What is the purpose of the ‘this’ keyword in Java?
Basic Java Interview Questions:
1. What is Java?
– Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle Corporation). It was designed to be platform-independent, meaning that Java programs can run on any device or operating system that has a Java Virtual Machine (JVM) installed.
2. Main Features of Java:
– Simple: Java was designed to be easy to learn and use.
– Object-Oriented: Java follows an object-oriented programming paradigm, allowing developers to create reusable and modular code.
– Platform-Independent: Java programs can run on any device or operating system with a Java Virtual Machine (JVM), making them highly portable.
– Secure: Java provides a secure runtime environment with features like bytecode verification and a security manager.
– Robust: Java incorporates features like exception handling and garbage collection, which help ensure robust and reliable programs.
– Multithreaded: Java supports multithreading, allowing concurrent execution of multiple tasks within a single program.
– High Performance: With features like Just-In-Time (JIT) compilation, Java offers high performance for both desktop and server applications.
3. Difference between JDK, JRE, and JVM:
– JVM (Java Virtual Machine): JVM is an abstract computing machine that provides the runtime environment for executing Java bytecode. It converts Java bytecode into machine code and executes it. JVM implementations exist for various platforms.
– JRE (Java Runtime Environment): JRE is a software package that contains JVM, libraries, and other components required to run Java applications. It does not contain development tools like compilers and debuggers.
– JDK (Java Development Kit):** JDK is a software development kit that includes JRE along with development tools like Java compiler (javac), debugger, and other utilities. JDK is used for developing Java applications. ( Java Interview Questions )
4. Difference between == and .equals() method in Java:
– == Operator: In Java, the == operator is used to compare the references (memory addresses) of two objects. When applied to objects, it checks if the two object references point to the same memory location.
– .equals() Method: The .equals() method is used to compare the contents or values of two objects. It is a method that is overridden from the Object class in Java. By default, it performs the same comparison as the == operator, but it can be overridden in user-defined classes to provide custom comparison logic.
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2); // Output: false (different memory locations)
System.out.println(str1.equals(str2)); // Output: true (same content)
5. Difference between abstract class and interface in Java:
– Abstract Class:
– An abstract class is a class that cannot be instantiated on its own and may contain abstract methods (methods without a body).
– Abstract classes can contain both abstract and concrete methods.
– An abstract class can have instance variables.
– A class can extend only one abstract class.
abstract class Shape {
abstract void draw(); // Abstract method
}
– Interface:
– An interface in Java is a blueprint of a class and only contains abstract methods by default (methods without a body).
– Interfaces cannot have instance variables. They can only have constants (static final variables).
– A class can implement multiple interfaces.
interface Drawable {
void draw(); // Abstract method
}
6. Inheritance in Java
Inheritance is a fundamental concept in object-oriented programming (OOP) where a new class (subclass or child class) is created by inheriting the features and behaviors of an existing class (superclass or parent class). This allows the subclass to reuse the fields and methods of the superclass, and also enables polymorphism. ( Java Interview Questions )
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks
}
}
7. Method Overloading and Method Overriding
– Method Overloading: In Java, method overloading refers to the ability to define multiple methods in the same class with the same name but with different parameters. The methods must have different method signatures. Method overloading is resolved at compile-time based on the method signature.
– Method Overriding: Method overriding occurs when a subclass provides a specific implementation of a method that is already provided by its superclass. The method signature, including the name, return type, and parameters, must be the same in both the superclass and subclass. Method overriding is resolved at runtime.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
class ScientificCalculator extends Calculator {
@Override
int add(int a, int b) {
return a * b; // Override the add method in the superclass
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(2, 3)); // Output: 5
ScientificCalculator scientificCalculator = new ScientificCalculator();
System.out.println(scientificCalculator.add(2, 3)); // Output: 6
}
}
8. Checked vs Unchecked Exceptions
– Checked Exceptions: Checked exceptions are the exceptions that are checked at compile-time. These exceptions are typically beyond the control of the programmer, such as file not found or network connection issues. They must be handled using try-catch blocks or declared in the method signature using the `throws` keyword.
– Unchecked Exceptions: Unchecked exceptions are the exceptions that are not checked at compile-time. These exceptions occur due to programming errors such as accessing an array index out of bounds or dividing by zero. They are subclasses of `RuntimeException` and are not required to be caught or declared.
9. Constructor in Java
A constructor in Java is a special type of method that is invoked when an object of a class is created. It is used to initialize the newly created object. Constructors have the same name as the class and do not have a return type, not even `void`.
Example:
class Car {
String brand;
// Constructor
Car(String b) {
brand = b;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota");
System.out.println(myCar.brand); // Output: Toyota
}
}
Also Read : Top 30 JavaScript Interview Questions And Answers For 2024 ( Java Interview Questions )
10. Static vs Non-static Methods
– Static Methods: Static methods belong to the class rather than any instance of the class. They can be called directly using the class name without creating an instance of the class. Static methods cannot access instance variables directly and can only access static variables.
– Non-static Methods: Non-static methods belong to the instance of the class. They can access both static and non-static variables. Non-static methods are called using an instance of the class.
Example:
class MyClass {
static int staticVar = 5;
int instanceVar = 10;
static void staticMethod() {
System.out.println("Static method");
}
void instanceMethod() {
System.out.println("Instance method");
}
}
public class Main {
public static void main(String[] args) {
MyClass.staticMethod(); // Output: Static method
MyClass myObj = new MyClass();
myObj.instanceMethod(); // Output: Instance method
}
}
Intermediate Java Interview Questions:
11. Purpose of the ‘final’ keyword in Java:
In Java, the `final` keyword is used to apply restrictions on class, method, and variable declarations. When applied:
– For variables: It indicates that the variable’s value cannot be changed once assigned.
– For methods: It indicates that the method cannot be overridden by subclasses.
– For classes: It indicates that the class cannot be subclassed.
public class FinalExample {
final int x = 10; // Final variable
final void display() { // Final method
System.out.println("This is a final method.");
}
}
class SubClass extends FinalExample {
// Attempting to override final method will result in a compile-time error
// void display() { } // This line will cause a compilation error
}
12. Concept of multithreading in Java:
Multithreading in Java allows concurrent execution of multiple threads within a single process. Each thread represents a separate path of execution, allowing programs to perform multiple tasks simultaneously.
class MyThread extends Thread {
public void run() {
// Code to be executed concurrently
}
}
public class MultithreadingExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // Start the first thread
thread2.start(); // Start the second thread
}
}
13. Synchronization techniques in Java:
In Java, synchronization is used to control the access of multiple threads to shared resources. Some synchronization techniques include:
– Synchronized methods: Using the `synchronized` keyword to make methods thread-safe.
– Synchronized blocks: Using synchronized blocks to protect critical sections of code.
– Locks: Using explicit lock objects from the `java.util.concurrent.locks` package.
class Counter {
private int count = 0;
// Synchronized method
public synchronized void increment() {
count++;
}
// Synchronized block
public void decrement() {
synchronized (this) {
count--;
}
}
}
14. Purpose of the ‘volatile’ keyword in Java:
The `volatile` keyword in Java is used to indicate that a variable’s value will be modified by different threads. It ensures visibility of changes to that variable across all threads.
public class VolatileExample {
private volatile boolean flag = false;
public void setFlag(boolean value) {
flag = value;
}
public boolean getFlag() {
return flag;
}
}
15. Difference between ArrayList and LinkedList:
– ArrayList: Implements a dynamic array, allowing fast random access and fast iteration. However, insertion and deletion operations can be slower as elements need to be shifted.
– LinkedList: Implements a doubly linked list, allowing fast insertion and deletion operations as elements are simply reconnected. However, accessing elements by index is slower compared to ArrayList.
import java.util.ArrayList;
import java.util.LinkedList;
public class ListExample {
public static void main(String[] args) {
// ArrayList example
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
// LinkedList example
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
}
}
Also Read : Top 30 JavaScript Interview Questions And Answers For 2024 ( Java Interview Questions )
16. Difference between HashMap and HashTable
HashMap:
– Introduced in Java 1.2.
– Not synchronized, meaning it’s not thread-safe.
– Allows null values and one null key.
– Iterators in HashMap are fail-fast.
– HashMap performance is better than HashTable.
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
System.out.println(map);
}
}
HashTable:
– Introduced in Java 1.0.
– Synchronized, making it thread-safe.
– Does not allow null values or keys.
– Iterators in HashTable are fail-safe.
– HashTable performance is slower than HashMap.
import java.util.Hashtable;
public class HashTableExample {
public static void main(String[] args) {
Hashtable<Integer, String> table = new Hashtable<>();
table.put(1, "One");
table.put(2, "Two");
table.put(3, "Three");
System.out.println(table);
}
}
17. Difference between String, StringBuilder, and StringBuffer
String:
– Immutable in Java.
– Concatenation creates a new String object.
– Thread-safe due to its immutability.
StringBuilder:
– Introduced in Java 5.
– Mutable sequence of characters.
– Not thread-safe.
– Efficient for single-threaded operations where modifications are frequent.
StringBuffer:
– Introduced in Java 1.0.
– Mutable sequence of characters.
– Thread-safe as methods are synchronized.
– Efficient for multi-threaded operations.
public class StringBuildersExample {
public static void main(String[] args) {
String str = "Hello";
StringBuilder stringBuilder = new StringBuilder(str);
StringBuffer stringBuffer = new StringBuffer(str);
stringBuilder.append(" World");
stringBuffer.append(" World");
System.out.println("StringBuilder: " + stringBuilder);
System.out.println("StringBuffer: " + stringBuffer);
}
}
18. Exception Handling in Java
Exception handling in Java is a mechanism to handle runtime errors and exceptional conditions. It includes:
– Try: Contains the code that might throw an exception.
– Catch: Handles the exception thrown by the try block.
– Finally: Contains code that will always execute, whether an exception is handled or not.
– Throw: Explicitly throws an exception.
– Throws: Indicates that the method may throw an exception.
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block always executes.");
}
}
}
19. Purpose of the ‘super’ Keyword in Java
The `super` keyword in Java is used to refer to the superclass (parent class) of the current object. It is primarily used to access superclass methods, constructors, and variables. It is also used to differentiate between superclass and subclass members with the same name.
class Animal {
String sound = "Animal Sound";
}
class Dog extends Animal {
String sound = "Woof";
void printSound() {
System.out.println(super.sound); // Accessing superclass variable
}
}
public class SuperKeywordExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.printSound(); // Output: Animal Sound
}
}
20. Difference between Static and Dynamic Binding
Static Binding:
– Occurs at compile time.
– Also known as early binding.
– Method overloading is an example of static binding.
Dynamic Binding:
– Occurs at runtime.
– Also known as late binding.
– Method overriding is an example of dynamic binding.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class BindingExample {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound(); // Output: Dog barks
}
}
Advanced Java Interview Questions:
21. Generics in Java:
Generics in Java enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. This allows you to create classes, interfaces, and methods that operate on objects of various types while providing compile-time type safety.
// Example of a generic class
public class Box<T> {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
22. Types of Inner Classes in Java:
There are four types of inner classes in Java: ( Java Interview Questions )
1. **Member Inner Class**: Defined at the member level of a class. Can access the members of the outer class including private members.
2. **Static Nested Class**: A static class nested within another class. It doesn’t have access to the instance variables of the outer class.
3. **Local Inner Class**: Defined inside a block or method. Can access the members of the enclosing class and local variables must be final or effectively final.
4. **Anonymous Inner Class**: A class defined without a name. Used for instantiating objects with overridden methods or interfaces.
// Example of a member inner class
class Outer {
private int outerField;
class Inner {
void display() {
System.out.println("Outer Field: " + outerField);
}
}
}
// Example of a static nested class
class Outer {
static class Nested {
void display() {
System.out.println("Static Nested Class");
}
}
}
// Example of a local inner class
class Outer {
void outerMethod() {
class LocalInner {
void display() {
System.out.println("Local Inner Class");
}
}
LocalInner inner = new LocalInner();
inner.display();
}
}
// Example of an anonymous inner class
interface Greeting {
void greet();
}
class Outer {
void displayGreeting() {
Greeting greeting = new Greeting() {
@Override
public void greet() {
System.out.println("Hello, Anonymous Inner Class!");
}
};
greeting.greet();
}
}
23. Purpose of ‘transient’ keyword in Java:
The `transient` keyword is used in Java to indicate that a field should not be serialized when the class instance containing that field is serialized. It is mainly used to exclude sensitive or unnecessary fields from being persisted.
import java.io.Serializable;
class MyClass implements Serializable {
private transient int sensitiveData; // This field won't be serialized
private int normalData;
// Constructor and methods
}
24. Serialization vs. Deserialization in Java:
Serialization is the process of converting an object into a byte stream so that it can be persisted (e.g., stored in a file or sent over the network). In Java, this is typically achieved by implementing the `Serializable` interface.
Deserialization is the reverse process of serialization, where the byte stream is converted back into an object. Deserialization allows you to reconstruct the object from the serialized form. ( Java Interview Questions )
// Serialization example
try {
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(employee);
out.close();
fileOut.close();
} catch (IOException i) {
i.printStackTrace();
}
// Deserialization example
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee employee = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
25. Reflection in Java:
Reflection in Java allows you to inspect and manipulate classes, interfaces, fields, methods, and constructors at runtime, without knowing their names at compile time. It enables you to obtain information about classes and objects and to dynamically invoke methods and access fields.
import java.lang.reflect.*;
class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public void display() {
System.out.println("Name: " + name);
}
}
public class Main {
public static void main(String[] args) throws Exception {
Class<?> clazz = MyClass.class;
Constructor<?> constructor = clazz.getConstructor(String.class);
MyClass myObj = (MyClass) constructor.newInstance("John");
Method method = clazz.getDeclaredMethod("display");
method.invoke(myObj); // Prints: Name: John
}
}
26. Design Patterns in Java:
Design patterns are reusable solutions to common problems encountered in software design. In Java, some popular design patterns include Singleton, Factory, Observer, Strategy, Decorator, and more. Each pattern addresses a specific concern within a software application. Here’s a brief example of the Singleton pattern:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
27. Garbage Collection in Java:
Garbage collection is the process by which Java automatically manages memory allocation and deallocation. Java’s garbage collector periodically identifies and removes objects from memory that are no longer reachable or in use by the program. Developers don’t need to explicitly free memory as in languages like C or C++. Here’s a simple explanation:
MyClass obj = new MyClass(); // Memory allocated for obj
obj = null; // Object is no longer reachable
// Garbage collector frees the memory occupied by the object
28. Ways to Create a Thread in Java:
There are two main ways to create a thread in Java: by extending the Thread class or by implementing the Runnable interface. Here are examples of both:
Extending Thread class:
class MyThread extends Thread {
public void run() {
// Thread code here
}
}
MyThread thread = new MyThread();
thread.start();
Implementing Runnable interface:
class MyRunnable implements Runnable {
public void run() {
// Thread code here
}
}
Thread thread = new Thread(new MyRunnable());
thread.start();
29. Lambda Expressions in Java:
Lambda expressions introduce functional programming features to Java, allowing you to treat functionality as a method argument or create anonymous functions. They’re particularly useful for writing concise code, especially when working with collections or functional interfaces. Here’s an example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach(number -> System.out.println(number));
30. Purpose of the ‘this’ Keyword in Java:
In Java, the ‘this’ keyword refers to the current instance of the class. It can be used to access instance variables and methods, differentiate between instance variables and parameters with the same name, and pass the current object as a parameter. Here’s a simple usage:
class MyClass {
private int value;
public MyClass(int value) {
this.value = value; // 'this' distinguishes instance variable from parameter
}
public void printValue() {
System.out.println(this.value); // Accessing instance variable using 'this'
}
}
These explanations should give you a good understanding of these concepts along with some code samples to illustrate them. Let me know if you need further clarification on any of them!