Prepare for your next Java interview with this comprehensive list of 30 Java interview questions covering basic, intermediate, and advanced topics. These questions are designed for freshers, candidates with 1-3 years of experience, and professionals with 3-6 years, helping you build a strong foundation in core Java concepts, OOP principles, collections, multithreading, and more.
Basic Java Interview Questions (1-10)
1. What is the difference between JDK, JRE, and JVM?
Answer: JDK (Java Development Kit) is for development and includes compiler and tools. JRE (Java Runtime Environment) is for running Java programs. JVM (Java Virtual Machine) executes bytecode and provides platform independence.
2. Why is String class immutable in Java?
Answer: String is immutable for security reasons (like in passwords), thread-safety, and to enable string pooling for better memory efficiency. Once created, its value cannot be changed.
3. What is the difference between == and .equals() in Java?
Answer: == compares object references (memory addresses). .equals() compares object content or values. For strings, == checks if they point to the same object, while .equals() checks character sequence.
4. Explain the four pillars of OOP in Java.
Answer: Encapsulation: Bundling data and methods (using private fields, public getters/setters). Inheritance: Reusing code via extends. Polymorphism: Method overriding and overloading. Abstraction: Hiding implementation using abstract classes/interfaces.
5. What is the difference between method overloading and overriding?
Answer: Overloading: Same method name, different parameters in same class (compile-time). Overriding: Subclass provides specific implementation of superclass method (runtime).
6. What are the differences between ArrayList and LinkedList?
Answer: ArrayList uses dynamic array (fast random access, O(1) get). LinkedList uses doubly-linked list (fast insert/delete at ends, O(1) add/remove).
7. What is autoboxing and unboxing in Java?
Answer: Autoboxing: Primitive to wrapper (int to Integer). Unboxing: Wrapper to primitive (Integer to int). Introduced in Java 5 for easier collections usage.
8. Explain try-catch-finally block.
Answer: try: Code that may throw exception. catch: Handles specific exceptions. finally: Always executes (cleanup like closing resources), even if no exception.
try {
// risky code
} catch (Exception e) {
// handle
} finally {
// cleanup
}
9. What is the difference between this() and super()?
Answer: this(): Calls another constructor in same class. super(): Calls parent class constructor. Both must be first statement in constructor.
10. What is a final variable in Java?
Answer: Final variable is constant (cannot be reassigned after initialization). Used for immutable values like public static final int MAX = 100;
Intermediate Java Interview Questions (11-20)
11. What is the difference between HashMap and Hashtable?
Answer: HashMap: Not synchronized, allows null key/value, faster. Hashtable: Synchronized (thread-safe), no nulls, slower due to locking.
12. Explain Comparable vs Comparator.
Answer: Comparable: Natural ordering (implements compareTo() in class). Comparator: Custom ordering (separate class implementing compare()). Use Comparator for flexibility.
13. What are Java 8 Lambda expressions?
Answer: Lambdas enable functional programming: (parameters) -> expression. Used with functional interfaces like Runnable or Predicate.
List<String> list = Arrays.asList("a", "b");
list.forEach(s -> System.out.println(s));
14. What is the Stream API in Java 8?
Answer: Streams process collections functionally: filter, map, reduce. Lazy evaluation, parallel processing support.
list.stream().filter(s -> s.startsWith("a")).collect(Collectors.toList());
15. How does Garbage Collection work in Java?
Answer: JVM automatically frees memory of unreachable objects. Generations: Young (Eden, Survivor), Old. Algorithms like G1 collect efficiently.
16. What is the difference between checked and unchecked exceptions?
Answer: Checked: Must be handled (IOException). Unchecked: Runtime (NullPointerException), optional to handle.
17. Explain synchronized keyword.
Answer: Ensures thread safety by acquiring monitor lock on object/method. Prevents concurrent access to critical sections.
public synchronized void method() {
// thread-safe code
}
18. What is the volatile keyword?
Answer: Volatile ensures variable visibility across threads (no caching in thread-local memory). Does not provide atomicity.
19. How do you reverse a string in Java?
Answer: Use StringBuilder reverse() or loop with StringBuilder append.
String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
20. What is an Enum in Java? (Scenario: At Zoho, how would you use Enum for order status?)
Answer: Enum defines fixed constants. Thread-safe, type-safe.
enum OrderStatus { PENDING, SHIPPED, DELIVERED }
OrderStatus status = OrderStatus.SHIPPED;
Advanced Java Interview Questions (21-30)
21. Implement a thread-safe Singleton pattern.
Answer: Use enum or double-checked locking with volatile.
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}
22. What is a memory leak in Java? How to prevent it?
Answer: Unreachable objects not garbage collected (e.g., static collections holding references). Prevent: Use weak references, clear collections, avoid static misuse.
23. Explain Producer-Consumer using wait() and notify().
Answer: Producer adds to queue (notify consumers), consumers remove (wait if empty). Uses synchronized block.
24. What is ExecutorService? (Scenario: At Atlassian, managing concurrent tasks)
Answer: Thread pool framework. submit(), shutdown(). Better than manual Thread creation.
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Task"));
25. Difference between fail-fast and fail-safe iterators.
Answer: Fail-fast (ArrayList): Throws ConcurrentModificationException on structural change. Fail-safe (CopyOnWriteArrayList): Works on copy, no exception.
26. What is reflection in Java?
Answer: Runtime inspection/modification of classes (Class.forName(), getMethod()). Used in frameworks like Spring.
27. Explain deadlock and how to avoid it.
Answer: Threads waiting circularly for locks. Avoid: Consistent lock order, timeout locks, avoid nested locks.
28. What are Atomic variables? (Scenario: At Paytm, for counter in high-traffic)
Answer: Thread-safe without locks (AtomicInteger.incrementAndGet()). CAS (Compare-And-Swap) based.
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
29. What is CompletableFuture for async programming?
Answer: Asynchronous computation (supplyAsync(), thenApply()). Handles callbacks, chaining without blocking.
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
30. How does ConcurrentHashMap ensure thread safety? (Scenario: At Adobe, caching user data)
Answer: Segment-level locking (Java 7) or CAS + synchronized (Java 8+). Allows concurrent reads/writes without full lock.
## Related Posts