Java Core — Interview Cheat Sheet
OOP, JVM memory model, garbage collection, String internals, equals/hashCode — senior Java interview essentials.
Interview tip For equals/hashCode: "Equal objects MUST have equal hash codes; override both together or neither."
① OOP pillars in Java
| Pillar | Java mechanism | Interview example |
|---|---|---|
| Encapsulation | private fields + getters/setters | Hide internal state; validate in setter |
| Inheritance | extends — is-a relationship | Dog extends Animal; favor composition over inheritance |
| Polymorphism | Method overriding, interfaces | List ref = new ArrayList(); runtime dispatch |
| Abstraction | abstract class, interface | PaymentProcessor interface; Stripe impl |
| Abstract class vs Interface | Abstract class | Interface |
|---|---|---|
| State | Can have fields, constructors | Only constants (before Java 8) |
| Methods | Abstract + concrete | Abstract (impl classes) + default/static (Java 8+) |
| Multiple inheritance | Single extends | Multiple implements |
| Use when | Shared base implementation | Capability contract (Comparable, Runnable) |
② JVM memory model
JVM memory (simplified)
Stack (per thread)
Heap (shared)
Local vars, frames
Young Gen (Eden, S0, S1)
Method area / Metaspace
Old Gen (Tenured)
Stack: method frames, local primitives and references — thread-private, fast alloc/dealloc.
Heap: all objects and arrays — shared, GC-managed.
Metaspace: class metadata (Java 8+ replaced PermGen).
Heap: all objects and arrays — shared, GC-managed.
Metaspace: class metadata (Java 8+ replaced PermGen).
③ Garbage collection basics
| Collector | Strategy | Typical use |
|---|---|---|
| Serial | Single thread, stop-the-world | Small apps, client |
| Parallel (Throughput) | Multi-thread young/old GC | Batch, throughput priority |
| G1 (default Java 9+) | Region-based, predictable pauses | General server default |
| ZGC / Shenandoah | Low-latency, concurrent | Large heaps, strict p99 latency |
Generational hypothesis: most objects die young → Eden collection frequent (minor GC); survivors promote to Old Gen (major GC less frequent, costlier).
Triggers: Eden full, Old Gen threshold, System.gc() (hint only), metaspace pressure.
Triggers: Eden full, Old Gen threshold, System.gc() (hint only), metaspace pressure.
- Strong references — normal objects; GC when unreachable
- Soft — cleared before OOM (caches)
- Weak — GC at next cycle (WeakHashMap keys)
- Phantom — post-mortem cleanup (reference queues)
④ String immutability & pool
String is immutable — internal char array (byte[] since Java 9) cannot change after creation. Thread-safe, cacheable hashCode, safe as HashMap key.
String pool: literals (
String pool: literals (
"hello") interned in pool. new String("hello") creates heap object NOT in pool unless intern() called.| Type | Thread-safe | Use |
|---|---|---|
| String | Yes (immutable) | Constants, keys, short concat |
| StringBuilder | No | Single-thread string building — preferred |
| StringBuffer | Yes (synchronized) | Legacy; rarely needed |
Performance trap:
String s = ""; for(...) s += x; creates O(n²) objects — use StringBuilder.⑤ equals() and hashCode() contract
- Reflexive: x.equals(x) is true
- Symmetric: x.equals(y) ↔ y.equals(x)
- Transitive: x.equals(y) and y.equals(z) → x.equals(z)
- Consistent: repeated calls same result (unless mutated)
- x.equals(null) is false
- Critical: if x.equals(y) then x.hashCode() == y.hashCode()
- Unequal objects MAY have same hash (collision) — OK
HashMap lookup: hashCode → bucket; equals → exact match. Break contract → lost entries, duplicates.
Never use mutable fields in equals/hashCode if object used as map key — or make fields final.
Never use mutable fields in equals/hashCode if object used as map key — or make fields final.
⑥ == vs equals & common pitfalls
| Comparison | Compares | Example |
|---|---|---|
| == (primitives) | Values | int a=1, b=1 → true |
| == (objects) | Reference identity | new String("a") == new String("a") → false |
| equals() | Logical equality (override) | Objects with same field values |
| Objects.equals(a,b) | Null-safe | null-safe equals check |
Autoboxing NPE:
Integer cache: -128 to 127 cached —
Integer a = null; a == 1 throws NPE on unboxing.Integer cache: -128 to 127 cached —
Integer.valueOf(127) == Integer.valueOf(127) true; 128 false.⑦ Java 8+ essentials
| Feature | Purpose | Interview note |
|---|---|---|
| Lambda / streams | Functional-style collection ops | Lazy; terminal ops trigger; parallelStream cautiously |
| Optional | Explicit absence vs null | Do not use as field or method param — return type OK |
| Default methods | Interface evolution | Diamond problem if two defaults — must override |
| Records (Java 16+) | Immutable data carriers | Auto equals/hashCode/toString |
| Sealed classes | Restricted inheritance | Exhaustive pattern matching (Java 21+) |
⑧ Object lifecycle & initialization
Object creation order
Static init→Instance init blocks→Constructor→Object ready
Shallow vs deep copy: clone() default is shallow — mutable fields shared. Deep copy requires manual or serialization libraries.
⑨ Interview Q&A
| Question | Answer sketch |
|---|---|
| Why String immutable? | Security, thread safety, pool interning, stable hashCode for keys |
| finalize()? | Deprecated — unreliable; use try-with-resources, Cleaner |
| fail-fast vs fail-safe? | Fail-fast (ArrayList iter) throws on concurrent mod; fail-safe (ConcurrentHashMap iter) snapshot |
| Checked vs unchecked exception? | Checked must declare/catch (IOException); unchecked extends RuntimeException |
| Composition vs inheritance? | Composition — has-a, flexible; inheritance — is-a, tight coupling |
⑩ Revision checklist
- Explained heap vs stack with GC role
- Named default GC (G1) and generational model
- String immutability + pool + StringBuilder for concat
- Stated equals/hashCode contract and HashMap impact
- == vs equals with Integer cache example
- Abstract class vs interface with Java 8 defaults