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
Progress saved locally. Check off questions — saves to your browser. No account needed.
0
/ 15 Done
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
CheckedUnchecked (RuntimeException)
Compiler enforcesYes — declare or handleNo
RepresentsRecoverable external problemsProgramming bugs
ExamplesIOException, SQLExceptionNullPointerException, ArrayIndexOutOfBounds
Checked exceptions are unique to Java. The compiler forces you to handle or declare them with 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: a final variable can't be reassigned, a final method can't be overridden, a final class can't be extended.
  • finally — a block after try/catch that always runs, used for cleanup.
  • finalize() — a deprecated Object method the GC once called before reclaiming an object. Do not rely on it; use try-with-resources instead.
06Difference between ArrayList and LinkedList?Java
ArrayListLinkedList
BackingResizable arrayDoubly-linked nodes
Random accessO(1)O(n)
Insert/remove at endsO(1) amortized (end)O(1)
Insert in middleO(n) shiftO(1) once located
MemoryCompactHigher (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.
07Interface vs abstract class — when do you use each?Java
InterfaceAbstract Class
Multiple inheritanceYes (implement many)No (extend one)
State (fields)Only constantsInstance fields allowed
ConstructorsNoYes
Method bodiesdefault/static onlyConcrete + abstract
Use an interface for a capability many unrelated types can share (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, 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
Records are implicitly final, their fields are final, and they can't extend a class (they already extend Record).
10Explain the four access modifiers.Java
ModifierClassPackageSubclassWorld
private
(default)
protected
public
Default (no keyword) is "package-private". Encapsulation favours the tightest modifier that still works.
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.
12Comparable vs Comparator?Java
  • Comparable<T> — the class's natural ordering, via compareTo(). One ordering per class.
  • Comparator<T> — an external, swappable ordering, via compare(). 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 — 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() or new 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.
Modern collectors (G1, ZGC, Shenandoah) aim for low pause times. You cannot force GC — System.gc() is only a hint.
15What is a fail-fast iterator?Java
A fail-fast iterator throws 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)
Concurrent collections like CopyOnWriteArrayList are fail-safe — they iterate over a snapshot and never throw.
No questions match your search.