$ Core Java & OOP — Complete Interview Cheat Sheet
// Single consolidated reference — Java Fundamentals, OOP, Collections, Multithreading, Java 8+, JVM/GC, Design Practices (0–10 YoE)
1. Java Platform & Execution
Quick Reference
JDK
Development Kit = JRE + Compiler (javac) + Debugger + Tools
JRE
Runtime Environment = JVM + Core Libraries
JVM
Loads classes, executes bytecode, manages memory & GC
javac
Compiles .java → .class (bytecode)
Remember
JDK = JRE + Development Tools
JRE = JVM + Libraries
JVM = Executes Java Bytecode
Execution Flow & Features
.java → Output
.java File
javac Compiler
.class Bytecode
JVM loads+verifies
main() → JIT → Machine Code
JVM makes Java platform independent — bytecode runs on any OS with a JVM (WORA: "write once, run anywhere"). main() must be public static void main(String[] args) — the mandatory entry point.
Java Features
✓ Platform Independent ✓ Object Oriented ✓ Secure ✓ Robust ✓ Portable ✓ Multithreaded ✓ High Performance (JIT) ✓ Auto Garbage Collection ✓ Distributed ✓ Dynamic
Trap: == compares references for objects (memory address) and values for primitives. .equals() compares actual content.
2. Data Types, Wrappers, Casting & Variables
Primitive Data Types (8)
byte
1 byte
short
2 bytes
int
4 bytes
long
8 bytes
float
4 bytes
double
8 bytes
char
2 bytes
boolean
TRUE/FALSE
Primitive vs Object · Wrapper Classes · Autoboxing
Primitive
StorageStored Directly (Stack)
SpeedFast
NullCannot Be Null
Exampleint age = 25;
Object (Wrapper)
StorageReference Type, stored in Heap
SpeedSlower (boxing overhead)
NullCan Be Null
ExampleInteger age = 25;
Wrapper Mapping + Why Needed
byte→Byteshort→Short, int→Integer, long→Long
float→Floatdouble→Double
char→Characterboolean→Boolean
Why Wrapper Classes?
Collections store Objects → Generics require Objects → gives utility methods → can store null
Autoboxing / Unboxing & Integer Caching
Autoboxing vs Unboxing
int
→ autobox →
Integer
Integer
→ unbox →
int
Example: Integer x = 10; int y = x;
Integer Cache (-128 to 127)
Integer a=100; Integer b=100; → a==b → true (cached) Integer a=200; Integer b=200; → a==b → false (new objects)
⚠ Always use .equals() to compare wrapper values, never ==.
Variable Scope & Casting
Variable Types
LocalInside a method/block; must be initialized before use; no default value
InstanceInside class, outside methods; per-object copy; gets default value
StaticBelongs to class; one copy shared across all objects; gets default value
Type Casting & Operators
Implicit small→large, automatic, safe (int → long) Explicit large→small, manual cast, may lose data (double)→(int) Arithmetic + − * / % · Relational == != > < · Logical && || · Bitwise & | ^ · Shift << >> >>> · Ternary ? :
3. OOP — Four Pillars, Relationships & Design
Quick Reference
Class
Blueprint / Template — Variables & Methods
Object
Instance of a Class
Encapsulation
Data Hiding — Wraps Data + Methods
Inheritance
Code Reusability — IS-A Relationship
Polymorphism
One Interface, Many Forms
Abstraction
Hide Implementation Details
Four Pillars Detail
1. Encapsulation
Wrapping data and methods into a single unit; achieved using private variables with public getters/setters.
Data HidingSecurityMaintainability
Ex: private balance + getBalance()
2. Inheritance
Child class inherits properties & behavior from a parent class — promotes code reusability, IS-A relationship.
SingleMultilevelHierarchicalMultiple (via Interface)
Ex: class Dog extends Animal
3. Polymorphism
One interface, many forms — the same action behaves differently on different objects. Compile-time via Overloading, Runtime via Overriding (Dynamic Method Dispatch).
Compile-Time (Overload)Runtime (Override)
Ex: A Person can be Employee, Patient & Father at once
4. Abstraction
Showing only essential details and hiding implementation complexity from the user.
Abstract ClassInterface
Ex: car.start() hides engine internals
Inheritance Types, Polymorphism & Abstraction — Structure
Class / Object, Inheritance, Polymorphism
│ ├── Class (Blueprint): defines variables (state) + methods (behavior) │ └── Object = Instance of Class, created via new keyword │ ├── Inheritance (IS-A): child reuses parent's members │ ├── Single: Dog extends Animal │ ├── Multilevel: Puppy extends Dog extends Animal │ ├── Hierarchical: Dog, Cat both extend Animal │ └── Multiple (via Interface): class Duck implements Flyable, Swimmable — Java disallows multiple class inheritance (Diamond Problem) │ └── Polymorphism: same call, different behavior ├── Compile-Time — Overloading: add(int,int) vs add(int,int,int) └── Runtime — Overriding: Animal.speak() → Dog.speak() @Override, via Dynamic Method Dispatch: Animal a = new Dog();
Abstraction:Abstract Class vs Interface
│ ├── Abstract Class: Partial Implementation — "What + How" │ ├── Variables: Instance, Static, Final variables │ ├── Methods: Abstract and Concrete methods │ ├── Constructors: Allowed │ ├── Inheritance: Single inheritance │ └── Keyword: extends │ └── Interface: Defines a Contract — "What to do" ├── Variables: public static final variables ├── Methods: Abstract, Default, Static (Private since Java 9) ├── Constructors: Not Allowed ├── Inheritance: Multiple inheritance └── Keyword: implements
Relationship Types (HAS-A) & Abstract Class vs Interface
Abstract Class vs Interface
FeatureAbstract ClassInterface
ConstructorYesNo
VariablesAny Typepublic static final
MethodsAbstract + ConcreteAbstract, Default, Static
InheritanceSingleMultiple
StateYesNo
Use Abstract Class for shared implementation among closely related classes; use Interface for a contract + loose coupling + multiple inheritance.
AssociationHAS-A, fully independent — Teacher ↔ Student
AggregationWeak HAS-A, parts exist independently — Department ↔ Employee
CompositionStrong HAS-A, parts can't exist alone — Car ↔ Engine
Composition > InheritancePrefer HAS-A over IS-A when there's no true "is-a" relation — looser coupling
Trap — Why no multiple inheritance via classes? Avoids the Diamond Problem — ambiguity over which parent method to inherit when two parents define the same method. Solved in Java via interfaces + default methods with explicit resolution required.
Trap — Object Slicing:child object is converted to a parent object by value; Not possible in Java (unlike C++) — Java always uses references, never copies objects by value.
4. Constructors, this/super, Overload vs Override
Object / Constructor Flow
new Employee()
Memory Allocated
Constructor Executed
Object Initialized
Reference Returned
Constructor: same name as class, no return type, auto-invoked on new — differs from a method (any name, may return value, called explicitly). Default constructor is auto-supplied by the compiler only if none is explicitly defined. Constructors can be overloaded but cannot be final/static (only access modifiers allowed).
Constructor Chaining: this() = same class, super() = parent class. Must be the first statement.
this
Refers toCurrent Object
Used forResolve field/param clash, chain constructors via this()
super
Refers toImmediate Parent Class
Used forAccess parent field/method, call parent constructor via super()
Overloading vs Overriding
Overloading
WhenCompile-Time Polymorphism
RuleSame name, different signature
Varies byNumber / Type / Order of Params
ClassSame class
Overriding
WhenRuntime Polymorphism
RuleSame signature, same/covariant return
Varies byImplementation in Child Class
ClassParent → Child (@Override)
5. Object Class, String & Memory
Object Class — Root of Every Class
Methods on java.lang.Object
toString() equals() hashCode() clone() getClass() wait() notify() notifyAll() finalize() (deprecated)
Default toString()ClassName@HashCode. Always override for readable output.
String Immutability, Pool & Comparison
String Memory Model
│ ├── String s1 = "Java"; → String Constant Pool (special Heap area), reused if value already exists └── String s2 = new String("Java"); → new Heap Object, separate from pool
new String() → creates a new object in Heap memory.
intern() → returns the reference of the String from the String Pool.
Pool purpose: reuse objects, save memory, improve performance.
Why Strings are Immutable
SecuritySensitive data (URLs, file paths, DB creds) can't be altered after creation
Thread SafetyShared across threads with no synchronization needed
Pool ReuseSafe to share the same object for equal literals
PerformanceCaches hashCode() — fast use as HashMap keys
Concatenation with + creates a new object each time (internally uses StringBuilder).
String vs StringBuilder vs StringBuffer
String
Immutable — every modification creates a new object.
Thread SafeSlow on Modification
StringBuilder ⭐
Mutable, modifies same object, no synchronization.
Not Thread SafeFastestSingle Thread
StringBuffer
Mutable, synchronized methods — safe across threads.
Thread SafeSlowerMulti Thread
Common String Methods
length()size of string
charAt()char at index
substring()extract portion
equalsIgnoreCase()case-insensitive compare
startsWith()/endsWith()prefix/suffix check
split() / trim() / replace()tokenize / clean / modify
6. Arrays, Control Flow & Generics
Array vs ArrayList vs Collection
ArrayArrayList / Collection
SizeFixedDynamic (grows)
StoresPrimitives + ObjectsObjects only (autoboxing for primitives)
AccessIndex-based, fast, continuous memoryIndex-based, rich utility API (add/remove/search)
foriteration count known
whilecount unknown
do-whileruns ≥ once (condition checked after)
breakexits the loop
continueskips to next iteration
switchmulti-branch on matching value; case/break/default
Generics: Allow classes, interfaces, and methods to work with a specific data type → provide compile-time type safety, avoid explicit casting, and reduce the risk of ClassCastException.
Note: Enums cannot be generic, but can have generic methods.
7. static / final, Access Modifiers, Packages, SOLID
static Members
Static Variable → one copy, shared by all objects (constants, counters, config) Static Method → can access only static members, cannot use this/super Static Block → runs once when class loads, for static init Static Nested Class → no outer object needed
final Keyword
final Variable → cannot change (constant) final Method → cannot override final Class → cannot extend
static final together → compile-time constant, e.g. final int MAX = 100;
Access Modifiers & Packages
ModifierSame ClassPackageChildOutside
privateYesNoNoNo
defaultYesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes
Packages & Class Loading Order
Packages organize classes, avoid name conflicts, provide access control.
Class Loaded
Static Block
main()
Object + Constructor
SOLID Principles
S — SRP
Single Responsibility Principle — one class, one reason to change
O — OCP
Open/Closed Principle — Open for Extension, Closed for Modification
L — LSP
Liskov Substitution Principle — Child must replace Parent without breaking behavior
I — ISP
Interface Segregation Principle — Many small interfaces > one large interface
D — DIP
Dependency Inversion Principle — Depend on Abstraction, not Concrete class
8. Inner Classes, Enum, Record, Annotations
Types of Inner Classes
Member InnerNon-static, needs outer object, accesses all outer members
Static NestedStatic, no outer object needed, accesses only static members
Local InnerDeclared inside a method, scope limited to that method
Anonymous InnerNo class name, one-time use, now mostly replaced by Lambdas
Enum · Record · Annotations
Enum
Special class for a fixed set of constants. Can have fields, constructors, methods, interfaces, switch support. Cannot be generic (but can have generic methods).
Type SafetyCompile-Time Check
Record (Java 16+)
Immutable data carrier. Auto-generates constructor, getters, equals(), hashCode(), toString().
Less Boilerplaterecord Employee(int id, String name)
Annotations
Metadata for compiler, framework, or runtime — @Override, @Deprecated, @FunctionalInterface, @Component, @Autowired.
Retention: SOURCE/CLASS/RUNTIME
9. Exception Handling
Checked
Checked at
Compile time — must handle/declare
Use when
Caller can recover (file I/O, DB, network)
Examples
IOException, SQLException
Unchecked
Checked at
Runtime — extends RuntimeException
Use when
Programming errors / business rule violations
Examples
NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException
throwexplicitly throws an exception instance
throwsdeclares that a method might throw an exception
finallyexecutes regardless of exception occurs or not (cleanup)
Multiple catchchecked top → bottom, first match wins
Trap: if both try and finally return/throw, finally always wins — it overrides the try block's return value or exception. Avoid returning from finally in real code.
Trap: Throwable can technically be caught (parent of Exception & Error) but avoid it — it also swallows serious JVM Errors that shouldn't be handled by app code. Never silently swallow exceptions.
API / Exception Design (Mid+ level)
PracticeGuidance
Custom exceptionsExtend Exception/RuntimeException for business-specific errors.
Exception hierarchyCommon base exception → categorize into Validation / Business / System subclasses; handle centrally (e.g. Spring @ControllerAdvice).
10. Collections Framework — Core
ListSetMap
DuplicatesAllowedNot allowedUnique keys
OrderInsertion order preservedImpl-dependent (Hash/Linked/Tree)Impl-dependent
AccessIndex-basedNo indexKey-based
Naming Patterns
HashNo Insertion Order Guarantee
LinkedInsertion Order
TreeSorted Order
Collection & Map Hierarchy
Collection Framework Hierarchy
│ │ ├── Collection (I): Root Interface for List, Set and Queue. │ │ │ ├── List (I): Duplicate Allowed, Insertion Order Preserved, Index Based │ │ ├── ArrayList (C): Dynamic Array Structure, Random Access Fast, Middle Insertion/Deletion Slow │ │ ├── LinkedList (C): Doubly Linked List Structure,Insertion/Deletion Fast, Random Access Slow │ │ ├── Vector (C): Same as ArrayList, Synchronized & Thread Safe, Legacy │ │ │ └── Stack (C): Last In First Out (LIFO) │ │ │ ├── Set (I): Unique Elements (No Duplicates) │ │ ├── HashSet (C): No Insertion Order Guarantee │ │ │ └── LinkedHashSet (C): Insertion Order │ │ │ │ │ └── SortedSet (I): Elements are automatically stored in sorted order │ │ └── NavigableSet (I): SortedSet + Navigation Methods │ │ └── TreeSet (C): Sorted Order, Red-Black Tree │ │ │ └── Queue (I): First In First Out (FIFO) │ ├── PriorityQueue (C): Based on Priority (Default: Ascending Order) │ ├── Deque (I): Double Ended Queue │ │ ├── ArrayDeque (C) │ │ └── LinkedList (C) │ │ │ └── BlockingQueue (I): Multithreading │ ├── LinkedBlockingQueue (C) │ ├── ArrayBlockingQueue (C) │ └── PriorityBlockingQueue (C)
Map Hierarchy
└── Map (I): Key-Value Pair, Keys Unique, Values Duplicate │ ├── HashMap (C): No Insertion Order Guarantee, 1 Null Key Allowed │ └── LinkedHashMap (C): Insertion Order, 1 Null Key Allowed │ ├── WeakHashMap (C): If key has no strong reference, GC can remove the corresponding entry ├── IdentityHashMap (C): Uses == instead of equals() for key comparison ├── Hashtable (C): Synchronized & Thread Safe, No Null Key/Value, Legacy, Whole Map Locked ├── ConcurrentHashMap (C): Modern Thread Safe Map, No Null Key/Value, Better Performance than Hashtable, Bucket/Node Locked │ └── SortedMap (I): Keys are automatically stored in sorted order └── NavigableMap (I): SortedMap + Navigation Methods └── TreeMap (C): Sorted by Key, No Null Key, Red-Black Tree
ArrayList vs LinkedList vs Vector
ArrayList
Structure
Dynamic array, grows ~50% when full, copies elements
Access
O(1) random access
Insert/Delete (mid)
Slow (shift elements)
Thread-safe
No
LinkedList
Structure
Doubly linked list
Access
Slow (traverse)
Insert/Delete (mid)
Fast (pointer change)
Vector
Structure
Same as ArrayList, legacy
Thread-safe
Synchronized (whole list) → slower
HashMap — Internal Working (High Frequency)
put(key, value)
HashMap
Array of Buckets
hashCode(key)
Bucket Index Calculation
Bucket Empty?
Yes
Store Entry
No
Collision
Linked List
Nodes > 8?
Yes
Red-Black Tree
No
Linked List
get(key)
get(key)
hashCode(key)
Find Bucket
equals(key)
Return Value
hashCode() Finds Bucket
equals()   Finds Exact Object
Map Family Comparison
HashMapLinkedHashMapTreeMapHashtableConcurrentHashMap
OrderNo orderInsertion orderSorted (Red-Black Tree)No orderNo order
Null key1 allowed1 allowedNot allowedNot allowedNot allowed
Thread-safeNoNoNoYes (whole map locked)Yes (bucket/node-level)
Use whenDefault fast mapNeed HashMap speed + insertion orderNeed sorted keys, O(log n) opsLegacy code onlyHigh-concurrency reads/writes
Comparable vs Comparator
Comparable
Natural sort · compareTo() · single sort logic · defined inside the class · e.g. Employee ID
Comparator
Custom sort · compare() · multiple sort strategies · defined outside · e.g. sort by Salary, Age
Iterators & Set/Map Internals
Fail-FastThrows ConcurrentModificationException if the collection is modified during iteration (ArrayList, HashMap)
Fail-SafeDoes not throws ConcurrentModificationException if the collection is modified during iteration beacuse it works on copy(snapshot) of collection (CopyOnWriteArrayList, ConcurrentHashMap)
HashSet internalsbacked by a HashMap; element = key, dummy constant = value
TreeSet/TreeMapRed-Black Tree; sort via Comparable or supplied Comparator
Iterable vs IteratorIterable provides the iterator() to obtain an iterator; Iterator iterates elements using hasNext()/next()
SortedMap vs NavigableMapSortedMap = sorted keys; NavigableMap adds floor/ceiling/higher/lower navigation
hashCode() / equals() contract: Equal objects must have the same hashCode, but objects with the same hashCode are not necessarily equal.
11. Concurrent & Special Collections
HashMapHashtableCollections.synchronizedMapConcurrentHashMap
Thread-safeNoYesYesYes
LockingWhole mapWhole map (wrapper)Bucket/node-level + CAS
Null key/value1 null key okNot allowedDepends on backing mapNot allowed (avoids ambiguity: missing vs null)
Perf under concurrencyN/A single-threadSlowSlowFast (fine-grained locking)
CopyOnWriteArrayList
Every write creates a new array copy. Best for read-heavy, rarely-written lists. Fail-safe iteration.
Custom List/Set/Map
Custom List → dynamic array. Custom Set → backed by a Map (dedupe). Custom Map → hash table + buckets + key-value nodes.
12. Multithreading Basics
Multithreading allows multiple threads to run concurrently within a single process.
Thread Lifecycle
NEW (created) → RUNNABLE (start() called) → RUNNING (CPU scheduled)WAITING / BLOCKED (for lock/event) → TERMINATED
Process vs ThreadProcess = independent running program; Thread = smallest execution unit inside a process
Runnable vs ThreadRunnable defines the task; Thread class executes it
start() vs run()start() creates a new thread and invokes run(); run() alone just executes task on the current thread — no new thread!
Runnable vs CallableRunnable.run() returns nothing; Callable.call() returns a value (used with ExecutorService)
Coordination Primitives
sleep()Pauses thread, keeps the lock
wait()Releases lock, waits for notify()/notifyAll()
notify()Wakes one waiting thread
notifyAll()Wakes all waiting threads
Trap — Race Condition: multiple threads try to access or modify the same shared resource at the same time → inconsistent results. avoided using synchronization, locks, atomic classes, or concurrent collections.
Trap — Deadlock: two or more threads are waiting for each other, resulting no thread proceed. avoided by maintaining a consistent lock order.
13. Concurrency Toolkit (Mid–Senior)
Locking Options
synchronized
Intrinsic lock — simple, automatic acquire/release
ReentrantLock
Manual lock — tryLock(), timeouts, more control
ReadWriteLock
Multiple concurrent readers, single exclusive writer
StampedLock
Java 8 — optimistic read locking for better throughput
Double-Checked Locking: Two null checks + synchronized block to create a thread-safe Singleton efficiently (needs volatile on the instance field to be truly correct).
volatile vs synchronized
volatilesynchronized
GuaranteesVisibility onlyVisibility + Atomicity
Use caseStatus/flag variablesIncrement/decrement, compound operations
Executor Framework & Async
Executor FrameworkExecutor Framework automatically manages and executes threads using a thread pool instead of creating threads manually.
Why Executor over manual Thread?reuses existing threads via thread pool → less overhead, improves performance, better resource control
execute() vs submit()execute() - Executes a task and returns void; submit() - Executes a task and returns a Future object.
Future vs CompletableFuture
Future = result of asynchronous computation, retreive result, blocking execution; CompletableFuture = advanced Future, asynchronous, non-blocking execution, task chaining.
ExecutorService lifecycleCreate → Submit → Execute → shutdown() (graceful) / shutdownNow() (force) → Terminate
CountDownLatch
One thread waits for N other threads to finish (one-time use).
CyclicBarrier
N threads wait for each other at a barrier, then proceed together (reusable).
Semaphore
Permit-based access control (shared resource) — permit before accessing resource & release after use.
ThreadLocal
Each thread gets its own independent copy of a variable. changes made by one thread are not visible to other threads.
Fork/Join Framework
Java 7+ — divides a large task into smaller subtasks, executes in parallel, combines results.
ConcurrentModificationException
Throws if the collection is modified during iteration (fail-fast).
14. Java 8+ Features
Functional Interface
Exactly one abstract method (any number of default/static methods). Enables lambdas. @FunctionalInterface is optional but recommended.
Lambda Expressions
Concise implementation of a functional interface; reduces boilerplate vs anonymous classes.
Method References
Shorthand for a lambda that just calls an existing method: System.out::println.
Default / Static Interface Methods
Default: Inherited by Class, Called using Object, overridden.
Static: belongs to interface, Called using interface, cannot overridden.
Core Functional Interfaces
InterfaceSignaturePurpose
Consumer<T>accept(T) → voidTakes input, no output
Supplier<T>get() → TNo input, returns output
Function<T,R>apply(T) → RTakes input, returns output
Predicate<T>test(T) → booleanTakes input, returns boolean
Stream Pipeline
Source (Collection)
Intermediate ops (filter, map, sorted...)
Terminal op (collect, forEach, reduce)
Intermediate ops are lazy — nothing executes until a terminal op is invoked.
Source provides data to the stream. Intermediate operations prepare/transform the data and are lazy. Terminal operations execute the stream and produce the final result.
map() vs flatMap()map: 1-to-1 transform (List<Employee>→List<List<Skill>>). flatMap: transform + flatten (→List<Skill>)
OptionalAvoids NullPointerException. Best for method return types — avoid as a class field
Parallel Streams Processes stream elements using multiple threads. Uses common ForkJoinPool, splits data into tasks, executes concurrently & combines results. Good for CPU-heavy, large datasets — not always faster; risk of overhead on small data.
Collectorscollect or transform processed stream elements into final result such as a List, Set, Map, String, or grouped data.
Trap: Don't default to parallel streams for "performance" — measure first. Small collections or I/O-bound work often get slower due to thread coordination overhead.
15. Cloning, Immutability, equals/hashCode
Shallow vs Deep Copy
Shallow Copy
PrimitivesCopied
ReferencesShallow copy copies references
Deep Copy
PrimitivesCopied
Referencesdeep copy creates independent copies of nested objects
Cloneable is a marker interface indicates object can be cloned, otherwise CloneNotSupportedException.
Immutable Class — How to Build
final class
private final fields
No Setters
Initialize via Constructor
Defensive Copies for mutable fields
Benefits: Thread Safe, Simple, Secure, Cache Friendly, Reliable. Examples: String, Wrapper Classes, Record. Defensive copying = return a copy (not the original reference) of mutable internal state to protect encapsulation.
== vs equals() vs hashCode()
==
ComparesReference / Memory Address
equals()
ComparesContent / Business Value
Why Override Both equals() & hashCode()?
Key
hashCode()
Find Bucket
equals()
Correct Entry
Rule: Equal objects must have the same hashCode(). Overriding only equals() breaks HashMap/HashSet.
16. Serialization, Reflection & I/O
Serialization Flow
Java Object
ObjectOutputStream
Byte Stream
File / Network
ObjectInputStream
Java Object (restored)
Requires Serializable (marker interface). serialVersionUID ensures class compatibility. transient fields are skipped; static fields are never serialized. Externalizable gives full custom control via writeExternal/readExternal.
Reflection & I/O
Reflection inspects/modifies/invokes classes at runtime. Get Class Object: obj.getClass() · Employee.class · Class.forName() Used By: Spring, Hibernate, JUnit, DI, ORM Disadvantages: Slow, breaks encapsulation, security risk
Large file reads: use BufferedReader/buffered streams — chunked, not fully loaded into memory. try-with-resources works with AutoCloseable; compiler auto-generates a finally block calling close().
17. JVM, Memory Model & Garbage Collection
Runtime Memory Areas
Stack — method calls, local variables, method parameters, and object references. Thread-safe (per-thread), auto-cleared. Heap — objects, arrays, instance variables. Shared, managed by GC. Method Area / Metaspace — class metadata, static variables. PC Register & Native Stack — per-thread execution bookkeeping.
ClassLoader Hierarchy (Parent Delegation)
Bootstrap (loads core Java classes) └─ Platform/Extension (loads Java platform libraries) └─ Application (loads application-specific classes) Loading → Linking → Initialization
GC Flow, Eligibility & Errors
Object Created
Used
Reference Lost
Eligible for GC
Memory Reclaimed
Eligible when: reference = null · out of scope · anonymous object · reassigned reference · island of isolation.
GC Roots are the starting points for reachability analysis — anything reachable from a GC root is "alive". & not reachable becomes eligble for GC
System.gc() only requests GC, not guaranteed.
Memory LeakUnused object but reference still exists → never collected. Common causes: static collections, unclosed resources, listeners, unbounded caches, ThreadLocal.
Strong / Weak / Soft / Phantom RefStrong → one normal reference, so GC cannot remove it. Weak → no strong reference, so GC can remove it (used in caching). Soft → removes when memory is low. Phantom → advanced cleanup, rare in interviews.
OutOfMemoryErroroccurs when Memory is Full + GC Cannot Free Memory (leak, large objects, unbounded growth)
StackOverflowErrorDeep or infinite recursion exhausts the Stack
Young → Old GenerationNew objects are created in the Young Generation; If they survive multiple garbage collection cycles, they are moved to the Old Generation.
Minor GC vs Major GCMinor GC cleans the Young Generation and is fast; Major/Full GC cleans the Old Generation and is slower and more expensive.
Stop-The-WorldJVM pauses all application threads during Garbage Collection
PermGen → MetaspacePermGen (fixed size, caused OutOfMemoryError) removed in Java 8, replaced by dynamically-growing Metaspace
JIT CompilerConverts hot bytecode to native machine code at runtime for speed
GC AlgorithmsMark-Sweep (Mark Live Objects, Remove Unused Objects), Mark-Compact (Mark Live Objects, Remove Unused Objects, Compact Memory), Generational Copying (Copy/Move Live Objects from one memory area to another)
Analyzing memory leaksHeap dump + Eclipse MAT / VisualVM → find retained objects with no legitimate live reference
GC drawbacksSTW pauses, CPU/memory overhead, unpredictable timing, latency spikes under load
18. Design & Best Practices
Prefer Composition Over Inheritance
Use Constructor Injection over Setter Injection
Mark constants as static final
Keep fields private, program to interfaces
Follow SOLID Principles
Avoid deep inheritance hierarchies
Always override toString()
Override equals() and hashCode() together
Never use == for String/wrapper comparison
Use StringBuilder inside loops
Prefer Record for DTOs (Java 17+)
Use Enum instead of String constants
Avoid clone() in modern Java — use copy constructor/Builder
Make domain objects immutable where possible
Close resources via try-with-resources
Use Optional as return type, not as field/param
Follow DRY, KISS, YAGNI
Keep methods small, one responsibility per class
Design Pattern categories: Creational (create objects — Singleton, Factory, Builder), Structural (connect objects — Adapter, Decorator), Behavioral (communicate between objects — Strategy, Observer).
Interview Tips — Frequently Asked "Why"
Why override hashCode() with equals()?
HashMap first uses hashCode() to locate the bucket, then equals() to identify the correct object. Overriding only equals() breaks hash-based collections.
Comparable or Comparator?
Comparable for one natural ordering (inside the class). Comparator when multiple sorting strategies are needed (outside the class).
Why prefer Enum over String constants?
Type safety, compile-time checking, better readability, and switch support.
19. Real-World Problem-Solving Patterns
Thread-safe Cache
ConcurrentHashMap + computeIfAbsent() // avoid duplicate loads // production: add TTL/LRU eviction or use Caffeine / Ehcache / Redis
Remove Duplicates from a List
new HashSet<>(list) // order not preserved new LinkedHashSet<>(list) // order preserved list.stream().distinct().collect(...) // Java 8 way
Top-N Frequent Elements
// 1. Count via HashMap<T,Integer> // 2. Push into a PriorityQueue (max-heap) by frequency // 3. Poll top N
Processing Millions of Records
// Pagination / streaming / batch processing // bulk DB ops + parallel processing where safe // avoids OutOfMemoryError, minimizes memory footprint
Optimizing a slow app (interview framework): Profile first (VisualVM/JProfiler/JFR) → find the real bottleneck → check DB queries/indexing, memory & GC behavior, thread contention, external service latency → apply targeted fix (caching, batching, reduce object churn, JVM tuning). Data-driven, not guesswork.
20. Senior / Architect Radar (5–10 YoE Awareness)
Terms interviewers probe at Senior/Lead level — know the term, be ready to go one level deep.
JIT & HotSpot OptimizationsEscape analysis, lock elision/coarsening, biased/lightweight/heavyweight locking, deoptimization, safepoints.
GC AlgorithmsG1 (region-based, balanced), ZGC & Shenandoah (ultra-low pause, concurrent). Know region/remembered-set/card-table vocabulary.
Java Memory Model (JMM)"happens-before" relationship governs visibility/ordering across threads — basis for volatile/synchronized correctness.
CAS & Lock-FreeCompare-And-Swap underlies atomic classes and lock-free algorithms. Know the ABA problem and its fix (versioned stamps).
ForkJoinPoolWork-stealing scheduler — idle threads "steal" tasks from busy threads' queues. Powers parallel streams.
False SharingThreads on different cores modifying variables on the same CPU cache line → invisible contention/perf loss.
Production TroubleshootingCPU 100% → thread dump + top -H. OOM → heap dump + MAT. Deadlock → jstack. Slow after deploy → compare GC logs/thread dumps.
Securitychar[] for passwords (wipeable). Deserialization vulnerabilities (validate/whitelist). Reflection can bypass access control.
Architecture at ScaleMonolith-vs-microservices, backpressure, distributed locking, rate limiting, cascading-failure prevention (circuit breakers), CAP trade-offs.
21. Rapid-Fire One-Liners & Common Traps
Making a HashSet synchronized does not make its iterator fail-safe — still fail-fast.
Two different objects can never share the same memory address at the same time.
Equal objects → same hashCode (required). Same hashCode → not necessarily equal.
Custom class as HashMap key → override equals() + hashCode(); keep fields immutable.
Collections.unmodifiableList/Map() → read-only view; normal List/Map remain mutable.
Cloneable is a marker interface (no methods) — signals clone() support.
Concurrency = ability to manage multiple tasks; Concurrent = tasks actually progressing independently.
Constructors cannot be static/final — only access modifiers allowed.
@FunctionalInterface is a compiler check, not mandatory — always add it anyway.
Concatenating Strings with + in a loop is costly — prefer StringBuilder.
Collections utility: sort(), reverse(), max(), min(), unmodifiableX(), synchronizedX().
ExecutorService methods: execute(), submit(), shutdown(), shutdownNow().
JDK/JRE/JVM → Dev Kit / Runtime Env / Bytecode Executor
Autoboxing/Unboxing → Primitive↔Wrapper conversion
Encapsulation/Abstraction → Data Hiding / Hide Implementation
this/super → Current Object / Parent Object
static/final→ Belongs to Class / Cannot Change
SOLID → Maintainable Code Design
Record → Immutable Data Carrier (auto ctor/getters/equals)
Serializable/transient → Object→Bytes / Skip Field
Heap/Stack → Object Memory / Method Memory
DRY / KISS / YAGNI → Don't Repeat / Keep Simple / Build Only What's Needed
22. Interview Expectations & Revision Flow
Interviewers Expect You To Explain
✓ Internal Working ✓ JVM Basics ✓ Memory Management ✓ OOP Design ✓ SOLID Principles ✓ Object Lifecycle ✓ Collection Selection ✓ Performance Considerations ✓ Multi-threading Basics ✓ Real Project Examples ✓ Why One Approach Is Better Than Another
Full Revision Flow
Java Platform (JDK→JRE→JVM)
Data Types → Wrappers → String → OOP (4 Pillars) → SOLID
Constructors → static/final → Exceptions
Collections → Multithreading → Concurrency Toolkit → Java 8+ Streams
equals/hashCode → Serialization → Reflection
JVM/GC → Design Practices → Real-World Scenarios