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)
Primitive vs Object · Wrapper Classes · Autoboxing
StorageStored Directly (Stack)
SpeedFast
NullCannot Be Null
Exampleint age = 25;
StorageReference Type, stored in Heap
SpeedSlower (boxing overhead)
NullCan Be Null
ExampleInteger age = 25;
Wrapper Mapping + Why Needed
| byte→Byte | short→Short, int→Integer, long→Long |
| float→Float | double→Double |
| char→Character | boolean→Boolean |
Why Wrapper Classes?
Collections store Objects → Generics require Objects → gives utility methods → can store null
Autoboxing / Unboxing & Integer Caching
Autoboxing vs Unboxing
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
| Local | Inside a method/block; must be initialized before use; no default value |
| Instance | Inside class, outside methods; per-object copy; gets default value |
| Static | Belongs 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
| Feature | Abstract Class | Interface |
| Constructor | Yes | No |
| Variables | Any Type | public static final |
| Methods | Abstract + Concrete | Abstract, Default, Static |
| Inheritance | Single | Multiple |
| State | Yes | No |
Use Abstract Class for shared implementation among closely related classes; use Interface for a contract + loose coupling + multiple inheritance.
Association→HAS-A, fully independent — Teacher ↔ Student
Aggregation→Weak HAS-A, parts exist independently — Department ↔ Employee
Composition→Strong HAS-A, parts can't exist alone — Car ↔ Engine
Composition > Inheritance→Prefer 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.
Refers toCurrent Object
Used forResolve field/param clash, chain constructors via this()
Refers toImmediate Parent Class
Used forAccess parent field/method, call parent constructor via super()
Overloading vs Overriding
WhenCompile-Time Polymorphism
RuleSame name, different signature
Varies byNumber / Type / Order of Params
ClassSame class
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.
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
| Array | ArrayList / Collection |
| Size | Fixed | Dynamic (grows) |
| Stores | Primitives + Objects | Objects only (autoboxing for primitives) |
| Access | Index-based, fast, continuous memory | Index-based, rich utility API (add/remove/search) |
for→iteration count known
while→count unknown
do-while→runs ≥ once (condition checked after)
break→exits the loop
continue→skips to next iteration
switch→multi-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
| Modifier | Same Class | Package | Child | Outside |
| private | Yes | No | No | No |
| default | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
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 Inner→Non-static, needs outer object, accesses all outer members
Static Nested→Static, no outer object needed, accesses only static members
Local Inner→Declared inside a method, scope limited to that method
Anonymous Inner→No 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 at
Compile time — must handle/declare
Use when
Caller can recover (file I/O, DB, network)
Examples
IOException, SQLException
Checked at
Runtime — extends RuntimeException
Use when
Programming errors / business rule violations
Examples
NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException
throw→explicitly throws an exception instance
throws→declares that a method might throw an exception
finally→executes regardless of exception occurs or not (cleanup)
Multiple catch→checked 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)
| Practice | Guidance |
| Custom exceptions | Extend Exception/RuntimeException for business-specific errors. |
| Exception hierarchy | Common base exception → categorize into Validation / Business / System subclasses; handle centrally (e.g. Spring @ControllerAdvice). |
10. Collections Framework — Core
| List | Set | Map |
| Duplicates | Allowed | Not allowed | Unique keys |
| Order | Insertion order preserved | Impl-dependent (Hash/Linked/Tree) | Impl-dependent |
| Access | Index-based | No index | Key-based |
Naming Patterns
Hash→No Insertion Order Guarantee
Linked→Insertion Order
Tree→Sorted 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
Structure
Dynamic array, grows ~50% when full, copies elements
Insert/Delete (mid)
Slow (shift elements)
Structure
Doubly linked list
Insert/Delete (mid)
Fast (pointer change)
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?
No
Collision
↓
Linked List
↓
Nodes > 8?
get(key)
get(key)
↓
hashCode(key)
↓
Find Bucket
↓
equals(key)
↓
Return Value
hashCode()
→
Finds Bucket
equals()
→
Finds Exact Object
Map Family Comparison
| HashMap | LinkedHashMap | TreeMap | Hashtable | ConcurrentHashMap |
| Order | No order | Insertion order | Sorted (Red-Black Tree) | No order | No order |
| Null key | 1 allowed | 1 allowed | Not allowed | Not allowed | Not allowed |
| Thread-safe | No | No | No | Yes (whole map locked) | Yes (bucket/node-level) |
| Use when | Default fast map | Need HashMap speed + insertion order | Need sorted keys, O(log n) ops | Legacy code only | High-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-Fast→Throws ConcurrentModificationException if the collection is modified during iteration (ArrayList, HashMap)
Fail-Safe→Does not throws ConcurrentModificationException if the collection is modified during iteration beacuse it works on copy(snapshot) of collection (CopyOnWriteArrayList, ConcurrentHashMap)
HashSet internals→backed by a HashMap; element = key, dummy constant = value
TreeSet/TreeMap→Red-Black Tree; sort via Comparable or supplied Comparator
Iterable vs Iterator→Iterable provides the iterator() to obtain an iterator; Iterator iterates elements using hasNext()/next()
SortedMap vs NavigableMap→SortedMap = 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
| HashMap | Hashtable | Collections.synchronizedMap | ConcurrentHashMap |
| Thread-safe | No | Yes | Yes | Yes |
| Locking | — | Whole map | Whole map (wrapper) | Bucket/node-level + CAS |
| Null key/value | 1 null key ok | Not allowed | Depends on backing map | Not allowed (avoids ambiguity: missing vs null) |
| Perf under concurrency | N/A single-thread | Slow | Slow | Fast (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 Thread→Process = independent running program; Thread = smallest execution unit inside a process
Runnable vs Thread→Runnable 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 Callable→Runnable.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
| volatile | synchronized |
| Guarantees | Visibility only | Visibility + Atomicity |
| Use case | Status/flag variables | Increment/decrement, compound operations |
Executor Framework & Async
Executor Framework→Executor 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 lifecycle→Create → 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
| Interface | Signature | Purpose |
| Consumer<T> | accept(T) → void | Takes input, no output |
| Supplier<T> | get() → T | No input, returns output |
| Function<T,R> | apply(T) → R | Takes input, returns output |
| Predicate<T> | test(T) → boolean | Takes 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>)
Optional→Avoids 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.
Collectors→collect 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
PrimitivesCopied
ReferencesShallow copy copies references
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
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 Leak | Unused object but reference still exists → never collected. Common causes: static collections, unclosed resources, listeners, unbounded caches, ThreadLocal. |
| Strong / Weak / Soft / Phantom Ref | Strong → 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. |
| OutOfMemoryError | occurs when Memory is Full + GC Cannot Free Memory (leak, large objects, unbounded growth) |
| StackOverflowError | Deep or infinite recursion exhausts the Stack |
| Young → Old Generation | New 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 GC | Minor GC cleans the Young Generation and is fast; Major/Full GC cleans the Old Generation and is slower and more expensive. |
| Stop-The-World | JVM pauses all application threads during Garbage Collection |
| PermGen → Metaspace | PermGen (fixed size, caused OutOfMemoryError) removed in Java 8, replaced by dynamically-growing Metaspace |
| JIT Compiler | Converts hot bytecode to native machine code at runtime for speed |
| GC Algorithms | Mark-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 leaks | Heap dump + Eclipse MAT / VisualVM → find retained objects with no legitimate live reference |
| GC drawbacks | STW 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