tough java interview questions and answers
Here’s a list of tough Java interview questions along with detailed explanations/answers.
1. What is the difference between == and equals() in Java?
Answer:
==checks reference equality (whether two references point to the same object).equals()checks content equality, and can be overridden in classes likeString,Integer, or user-defined classes.
Example:
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2); // false (different objects or different memory location)
System.out.println(s1.equals(s2)); // true (same content)
2. Explain the Java memory model. How does garbage collection work?
Answer:
- Java divides memory into Heap, Stack, Method Area, PC Registers, Native Method Stack.
- Heap: Objects are stored here; GC collects unreachable objects.
- Stack: Stores primitive local variables and references; LIFO order.
- Garbage Collection: JVM automatically removes objects that are no longer referenced. Types of GC: Serial, Parallel, CMS, G1.
3. What is the difference between HashMap, TreeMap, and LinkedHashMap?
| Feature | HashMap | TreeMap | LinkedHashMap |
|---|---|---|---|
| Order | No order | Sorted by key | Insertion order |
| Null Key | 1 | No | 1 |
| Performance | O(1) | O(log n) | O(1) |
| Implementation | Hash table | Red-Black Tree | Hash table + linked list |
4. Explain volatile keyword. When is it used?
Answer:
volatileensures visibility of changes to variables across threads.- It prevents CPU caching issues, but does not provide atomicity.
- Used in multithreading when multiple threads read/write a variable without locking.
volatile boolean flag = true;
5. What is the difference between synchronized and ReentrantLock?
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Syntax | Keyword | Class |
| Flexibility | Less flexible | More (tryLock, lockInterruptibly) |
| Fairness | No | Can be fair |
| Unlock | Automatic | Must call unlock() explicitly |
6. What is the difference between final, finally, and finalize()?
final: Modifier for classes, methods, variables. Prevents modification.finally: Block in try-catch to execute code always (used for cleanup).finalize(): Method called before GC destroys an object (deprecated in Java 9+).
7. How does Java handle Integer caching?
- JVM caches
Integerobjects from -128 to 127. - Using
Integer.valueOf(100)returns cached object;new Integer(100)creates new object.
Integer a = 100; // cached
Integer b = 100;
System.out.println(a == b); // true
Integer c = 200;
Integer d = 200;
System.out.println(c == d); // false
8. Explain Java ClassLoader hierarchy.
- Bootstrap ClassLoader: Loads core JDK classes (
rt.jar). - Extension ClassLoader: Loads classes from
jre/lib/ext. - System/Application ClassLoader: Loads classes from classpath.
- Custom ClassLoader: Can load classes dynamically at runtime.
9. Difference between HashMap and ConcurrentHashMap
| Feature | HashMap | ConcurrentHashMap |
|---|---|---|
| Thread Safe | No | Yes |
| Null Key/Value | Yes | No null keys/values |
| Locking | None | Segment-level locking (Java 8 uses CAS and bin-level locking) |
10. Explain Deadlock and how to prevent it.
Answer:
-
Deadlock occurs when two or more threads wait indefinitely for each other’s locks.
-
Prevention:
- Lock ordering
- Use
tryLock()with timeout - Avoid nested locks
11. Difference between ==, equals(), and hashCode()
==: Reference comparisonequals(): Logical equalityhashCode(): Returns int for hash-based collections. Contract: Ifa.equals(b)→a.hashCode() == b.hashCode()
12. What is the difference between Checked and Unchecked Exceptions?
- Checked: Must be handled (
IOException,SQLException) - Unchecked: Runtime exceptions (
NullPointerException,ArithmeticException)
13. How does Java pass-by-value work?
- Java is always pass-by-value.
- For objects, the reference is passed by value, so modifying the object is possible, but reassigning the reference is not.
void modify(List<String> list) {
list.add("Hi"); // works
list = new ArrayList<>(); // no effect outside
}
**14. Explain Java 8 Stream API and Collector.collect()
- Stream allows functional-style operations on collections.
Collectors.collect()gathers elements into List, Set, Map, or custom container.
List<String> names = Arrays.asList("John","Jane","Jack");
List<String> filtered = names.stream()
.filter(n -> n.startsWith("J"))
.collect(Collectors.toList());
15. What are Soft, Weak, and Phantom References in Java?
| Type | GC Behavior | Usage |
|---|---|---|
| SrongReference | Not Collected unless null | Default ref |
| SoftReference | Collected only if memory low | Cache |
| WeakReference | Collected eagerly | WeakHashMap |
| PhantomReference | Only for post-mortem cleanup | ReferenceQueue |
16. How do HashMap collisions get resolved in Java 8+?
- Bucket uses LinkedList or Red-Black Tree (if >8 elements).
- Hash function distributes keys; collisions form chains or tree for O(log n) lookup.
**17. Explain Volatile + Double-checked Locking Singleton
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;
}
}
volatileprevents instruction reordering.synchronizedensures thread safety.- Double-check avoids locking after instance is created.
18. Explain CAS (Compare-And-Swap)
CAS → atomic operation to update value without locking. Used in ConcurrentHashMap, AtomicInteger, and other lock-free structures.
19. Explain transient and static in Serialization
- transient → field not serialized
- static → belongs to class, not serialized
20. How does the JVM manage memory?
Memory areas:
- Heap → Objects and arrays
- Stack → Method calls and local vars
- Metaspace (Java 8+) → Class metadata
- PC Register → Instruction pointer
- Native Stack → Native code (JNI)
- Garbage Collection (GC) reclaims heap memory automatically.
21. What happens inside the JVM when you execute a Java program?
- ClassLoader loads the .class file.
- Bytecode verifier checks for illegal bytecode.
- JIT Compiler (Just-In-Time) compiles hot methods to native code.
- Execution Engine runs the code.
- GC monitors and frees unused memory.
Published on: Oct 05, 2025, 10:55 AM