Java

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

PillarJava mechanismInterview example
Encapsulationprivate fields + getters/settersHide internal state; validate in setter
Inheritanceextends — is-a relationshipDog extends Animal; favor composition over inheritance
PolymorphismMethod overriding, interfacesList ref = new ArrayList(); runtime dispatch
Abstractionabstract class, interfacePaymentProcessor interface; Stripe impl
Abstract class vs InterfaceAbstract classInterface
StateCan have fields, constructorsOnly constants (before Java 8)
MethodsAbstract + concreteAbstract (impl classes) + default/static (Java 8+)
Multiple inheritanceSingle extendsMultiple implements
Use whenShared base implementationCapability 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).

③ Garbage collection basics

CollectorStrategyTypical use
SerialSingle thread, stop-the-worldSmall apps, client
Parallel (Throughput)Multi-thread young/old GCBatch, throughput priority
G1 (default Java 9+)Region-based, predictable pausesGeneral server default
ZGC / ShenandoahLow-latency, concurrentLarge 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.
  • 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 ("hello") interned in pool. new String("hello") creates heap object NOT in pool unless intern() called.
TypeThread-safeUse
StringYes (immutable)Constants, keys, short concat
StringBuilderNoSingle-thread string building — preferred
StringBufferYes (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.

⑥ == vs equals & common pitfalls

ComparisonComparesExample
== (primitives)Valuesint a=1, b=1 → true
== (objects)Reference identitynew String("a") == new String("a") → false
equals()Logical equality (override)Objects with same field values
Objects.equals(a,b)Null-safenull-safe equals check
Autoboxing NPE: 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

FeaturePurposeInterview note
Lambda / streamsFunctional-style collection opsLazy; terminal ops trigger; parallelStream cautiously
OptionalExplicit absence vs nullDo not use as field or method param — return type OK
Default methodsInterface evolutionDiamond problem if two defaults — must override
Records (Java 16+)Immutable data carriersAuto equals/hashCode/toString
Sealed classesRestricted inheritanceExhaustive pattern matching (Java 21+)

⑧ Object lifecycle & initialization

Object creation order
Static initInstance init blocksConstructorObject ready
Shallow vs deep copy: clone() default is shallow — mutable fields shared. Deep copy requires manual or serialization libraries.

⑨ Interview Q&A

QuestionAnswer 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
OOPJVMGCStringequalshashCode