Interview Prep — Java Track
Java Interview Questions
15 Java questions — == vs .equals(), the String pool, checked exceptions, the Integer cache, HashMap internals, and generics type erasure. The concepts backend and enterprise interviewers ask every time. Tagged for FAANG and startups.
CoreOOPAdvanced
15Total
6Core
4OOP
5Advanced
Core Java
01What is the difference between
== and .equals()?Java▾== compares references (do two variables point to the same object). .equals() compares logical equality (do two objects have the same content, as defined by the class).
java
String a = new String("hi"); String b = new String("hi"); a == b; // false — different objects a.equals(b); // true — same content
Rule: always use
.equals() for objects (especially Strings). If you override equals(), you must also override hashCode() to keep the contract for hash-based collections.02Why are Strings immutable, and what is the String pool?Java▾
String is immutable — once created, its contents never change; every "modification" produces a new object. Benefits: thread safety, safe use as HashMap keys, and security (paths, connection strings can't be mutated after validation).
The String pool is a special heap region where string literals are interned and reused. Two identical literals point to the same pooled object.
java
String a = "hi"; // pooled String b = "hi"; // same pooled object a == b; // true String c = new String("hi"); // forced new heap object a == c; // false
Tip: use
StringBuilder for heavy concatenation in loops — building with + creates a new String each iteration (O(n²)).03Checked vs unchecked exceptions?Java▾
| Checked | Unchecked (RuntimeException) | |
|---|---|---|
| Compiler enforces | Yes — declare or handle | No |
| Represents | Recoverable external problems | Programming bugs |
| Examples | IOException, SQLException | NullPointerException, ArrayIndexOutOfBounds |
throws, which some praise for robustness and others find noisy.
04What is autoboxing, and what is the Integer cache trap?Java▾
Autoboxing is the automatic conversion between a primitive (
int) and its wrapper (Integer). Java caches Integer objects for values −128 to 127, so == on boxed values in that range can accidentally look correct.
java
Integer a = 127, b = 127; a == b; // true — cached, same object Integer c = 200, d = 200; c == d; // false — outside cache, different objects c.equals(d); // true — always use equals for wrappers
05Difference between
final, finally, and finalize?Java▾final— a modifier: afinalvariable can't be reassigned, afinalmethod can't be overridden, afinalclass can't be extended.finally— a block aftertry/catchthat always runs, used for cleanup.finalize()— a deprecatedObjectmethod the GC once called before reclaiming an object. Do not rely on it; use try-with-resources instead.
06Difference between
ArrayList and LinkedList?Java▾| ArrayList | LinkedList | |
|---|---|---|
| Backing | Resizable array | Doubly-linked nodes |
| Random access | O(1) | O(n) |
| Insert/remove at ends | O(1) amortized (end) | O(1) |
| Insert in middle | O(n) shift | O(1) once located |
| Memory | Compact | Higher (node pointers) |
In practice:
ArrayList is the right default almost always — cache-friendly and fast random access. LinkedList rarely wins outside niche queue/deque cases. OOP in Java
07Interface vs abstract class — when do you use each?Java▾
| Interface | Abstract Class | |
|---|---|---|
| Multiple inheritance | Yes (implement many) | No (extend one) |
| State (fields) | Only constants | Instance fields allowed |
| Constructors | No | Yes |
| Method bodies | default/static only | Concrete + abstract |
Comparable, Runnable). Use an abstract class as a partial base for closely related types that share state and code.
08Method overloading vs overriding?Java▾
- Overloading — same method name, different parameter lists, in the same class. Resolved at compile time (static polymorphism).
- Overriding — a subclass provides a new implementation of a parent method with the same signature. Resolved at runtime (dynamic dispatch).
Note: overloads can't differ by return type alone. Always use
@Override when overriding — the compiler then catches signature typos.09What are records, and how do they differ from a class?Java▾
A record (Java 16+) is an immutable data carrier. One line generates the constructor, accessors,
Records are implicitly
equals(), hashCode(), and toString().
java
record Point(int x, int y) {} Point p = new Point(3, 4); p.x(); // 3 — accessor p.equals(new Point(3, 4)); // true — value equality, free
final, their fields are final, and they can't extend a class (they already extend Record).
10Explain the four access modifiers.Java▾
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
private | ✓ | ✗ | ✗ | ✗ |
| (default) | ✓ | ✓ | ✗ | ✗ |
protected | ✓ | ✓ | ✓ | ✗ |
public | ✓ | ✓ | ✓ | ✓ |
Advanced Java
11How does a
HashMap work internally?Java▾
A
HashMap is an array of buckets. A key's hashCode() (further spread by an internal hash) selects a bucket index. Collisions in a bucket form a linked list, which converts to a balanced tree (Java 8+) once it exceeds 8 entries, improving worst-case lookup from O(n) to O(log n).
- Load factor default 0.75 — at 75% full it resizes (doubles) and rehashes.
- Average get/put: O(1); worst case with tree bins: O(log n).
Contract: keys must implement
hashCode() and equals() consistently. Mutating a key after insertion corrupts lookups.12
Comparable vs Comparator?Java▾Comparable<T>— the class's natural ordering, viacompareTo(). One ordering per class.Comparator<T>— an external, swappable ordering, viacompare(). Many per class.
java
people.sort(Comparator.comparing(Person::getAge) .thenComparing(Person::getName)); // multi-key sort
13What is generics type erasure?Java▾
Java generics exist only at compile time. The compiler checks types, then erases them —
Consequences:
List<String> and List<Integer> are both just List at runtime. This preserved backward compatibility with pre-generics code.
Consequences:
- You can't do
new T()ornew T[]. instanceof List<String>is illegal.- Overloads that differ only by generic parameter clash (same erased signature).
Contrast: C++ templates and C# generics are reified (types survive to runtime). Java's erasure is a common interview "gotcha".
14How does Java garbage collection work?Java▾
The JVM automatically reclaims objects no longer reachable from GC roots (stack references, statics). The heap is generational:
- Young generation (Eden + survivor spaces) — new objects; frequent, fast minor GCs.
- Old generation — long-lived objects; less frequent, costlier major GCs.
System.gc() is only a hint.
15What is a fail-fast iterator?Java▾
A fail-fast iterator throws
Concurrent collections like
ConcurrentModificationException if the collection is structurally modified during iteration (except through the iterator's own remove()). It detects modification via an internal modCount.
java
for (String s : list) { if (s.isEmpty()) list.remove(s); // throws CME } // Fix: use iterator.remove() or removeIf(String::isEmpty)
CopyOnWriteArrayList are fail-safe — they iterate over a snapshot and never throw.
No questions match your search.