0% found this document useful (0 votes)
1 views50 pages

Java Interview Prep Handbook

Uploaded by

Anil Paul
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views50 pages

Java Interview Prep Handbook

Uploaded by

Anil Paul
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA BACKEND DEVELOPER

Interview Preparation Handbook


2–4 Years Experience | Comprehensive Guide

Covers: Core Java • Spring Boot • Microservices • JPA/Hibernate


REST APIs • Databases • Design Patterns • Performance
CHAPTER 1: CORE JAVA FUNDAMENTALS
This chapter covers the core Java concepts most frequently tested in backend developer interviews,
from OOP principles to advanced features like generics and lambda expressions.

1.1 Object-Oriented Programming (OOP) Principles


❓ Interview Question
What are the four pillars of OOP in Java? Explain each with an example.

✅ Short Answer (For Interview)


The four pillars are: Encapsulation (hiding internal state), Abstraction (exposing only
necessary details),
Inheritance (acquiring properties from parent class), and Polymorphism (one interface, many
behaviors).

Detailed Explanation
1. Encapsulation
Encapsulation is the mechanism of wrapping data (variables) and code acting on the data (methods)
into a single unit (class) and restricting direct access to some of the object's components.
public class BankAccount {
private double balance; // private = hidden from outside
private String accountId;

public double getBalance() { // controlled access


return balance;
}
public void deposit(double amount) {
if (amount > 0) [Link] += amount; // validation logic
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) [Link] -= amount;
}
}

2. Abstraction
Abstraction hides implementation complexity and exposes only the essential features. Achieved via
abstract classes and interfaces.
public interface PaymentGateway {
boolean processPayment(double amount); // what it does, not how
void refund(String transactionId);
}

public class StripePayment implements PaymentGateway {


@Override
public boolean processPayment(double amount) {
// complex Stripe API logic hidden here
return [Link](amount);
}
}

3. Inheritance
Inheritance allows a class (child) to acquire properties and behaviours of another class (parent),
enabling code reuse.
public class Animal {
protected String name;
public void eat() { [Link](name + " is eating"); }
}

public class Dog extends Animal {


public void bark() { [Link](name + " barks"); }
}

// Dog inherits eat() from Animal

4. Polymorphism
Polymorphism means 'many forms'. Java supports compile-time polymorphism (method overloading)
and runtime polymorphism (method overriding).
// Runtime Polymorphism
Animal animal = new Dog(); // reference type = Animal
[Link](); // calls Dog's overridden version at runtime

// Compile-time Polymorphism (Overloading)


public class Calculator {
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; }
public int add(int a, int b, int c) { return a + b + c; }
}

💡 Real Interview Tip


Interviewers often ask: 'Can we override static methods?' — Answer: NO. Static methods are
resolved at compile time.
Follow-up: 'Difference between overloading and overriding?' — Overloading = same class,
different params; Overriding = subclass, same signature.
Always mention SOLID principles as the OOP extension.

⚠️Common Mistakes
Confusing abstraction with encapsulation — encapsulation hides data; abstraction hides
complexity.
Saying Java supports multiple inheritance — Java supports multiple inheritance of TYPE
(interfaces), not STATE.
Forgetting to say polymorphism requires IS-A relationship.

❓ Interview Question
What is the difference between an Interface and an Abstract Class?

✅ Short Answer (For Interview)


Abstract class can have state (fields), constructors, and partial implementation. Interface
defines a contract (pure abstraction before Java 8).
From Java 8, interfaces can have default and static methods. Use abstract class for 'is-a'
with shared code; use interface for 'can-do' behavior.
Feature Abstract Class Interface
Instantiation Cannot be instantiated Cannot be instantiated
Methods Can have abstract + concrete Default/static methods (Java
methods 8+), abstract by default
Variables Any type (instance, static, final) Only public static final
(constants)
Constructors Yes No
Extends/Implements A class extends ONE abstract A class implements MULTIPLE
class interfaces
Use Case 'Is-A' relationship with shared 'Can-Do' capability contract
code
Java 8+ Same default methods, static methods
Java 9+ Same private methods allowed

// Abstract class example


public abstract class Vehicle {
protected int speed; // state
public Vehicle(int speed) { [Link] = speed; } // constructor
public abstract void startEngine(); // must override
public void displaySpeed() { [Link](speed); } // concrete
}

// Interface example
public interface Flyable {
void fly();
default void land() { [Link]("Landing..."); } // Java 8
}

public class Helicopter extends Vehicle implements Flyable {


public Helicopter(int speed) { super(speed); }
@Override public void startEngine() { [Link]("Rotor starting"); }
@Override public void fly() { [Link]("Helicopter flying"); }
}

💡 Real Interview Tip


Java 8 functional interfaces (@FunctionalInterface) have exactly ONE abstract method —
used in lambdas.
If asked 'why use interface over abstract class', answer: for multiple type inheritance and
loose coupling.
Real-world tip: Spring's design uses interfaces heavily (ApplicationContext, BeanFactory,
etc.)

❓ Interview Question
Why is String immutable in Java? What are the benefits?

✅ Short Answer (For Interview)


String is immutable because its internal char[] is declared final and private — once created, it
cannot be changed.
Benefits: Thread safety, String Pool optimization (caching), security (passwords, class
names), hashCode caching.

Detailed Explanation
String immutability is enforced in the [Link] class:
// Simplified internal view of String class
public final class String {
private final char[] value; // final + private = truly immutable
private int hash; // cached hashcode
...
}

// What happens with string operations:


String s = "Hello";
s = s + " World"; // Does NOT modify "Hello" — creates NEW String object
// "Hello" stays in String Pool unchanged

String Pool (Intern Pool)


The JVM maintains a String Pool in the Heap (moved from PermGen to Heap in Java 8). String literals
are pooled — two literals with same value share the same object.
String a = "java"; // goes to String Pool
String b = "java"; // reuses same Pool entry
String c = new String("java"); // creates new Heap object (NOT pooled)

[Link](a == b); // true (same reference)


[Link](a == c); // false (different objects)
[Link]([Link](c)); // true (same content)
[Link](a == [Link]()); // true ([Link]() returns Pool reference)

💡 Real Interview Tip


Always use .equals() for String comparison — never == for content comparison.
Common follow-up: 'How many String objects created by String s = new String("hello")?'
Answer: Up to 2 — 1 in Pool (if not already there) + 1 in Heap. If 'hello' already in Pool, just
1.

⚠️Common Mistakes
Using == for String comparison in production — classic bug.
Not knowing String Pool moves to Heap in Java 8 (from PermGen).
Forgetting StringBuilder / StringBuffer for mutable string operations in loops.

StringBuilder vs StringBuffer vs String


Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread Safety Thread-safe NOT thread-safe Thread-safe
(immutable) (synchronized)
Performance Slow for concatenation Fastest Slower than
in loops StringBuilder
Use Case Constants, keys, config Single-thread string Multi-threaded string
values building building
1.2 Java Collections Framework
The Java Collections Framework (JCF) is one of the most tested areas in interviews. Understanding
internal workings is critical.

❓ Interview Question
How does HashMap work internally in Java?

✅ Short Answer (For Interview)


HashMap uses an array of Node<K,V> buckets (default capacity 16). It uses hashCode() to
find the bucket index,
then equals() to find/insert the key within the bucket. Collisions are handled using LinkedList
(Java 7) or
balanced Tree (Java 8+ when bucket size >= 8).

Internal Working — Step by Step


1. Call hashCode() on the key to get the hash value.
2. Apply hash spreading: index = (n-1) & hash, where n = array length.
3. Go to that bucket (array index).
4. If bucket is empty, create a new Node and place it there.
5. If bucket has entries, iterate using equals() to check for matching key.
6. If matching key found → update value. If not → add to chain (LinkedList/Tree).
7. If load factor exceeded (default 0.75), resize array to 2x and rehash.

// HashMap internal structure (simplified)


transient Node<K,V>[] table; // the bucket array

static class Node<K,V> {


final int hash;
final K key;
V value;
Node<K,V> next; // linked list for collisions
}

// put() logic simplified


public V put(K key, V value) {
int hash = hash([Link]()); // step 1
int index = (capacity - 1) & hash; // step 2
Node<K,V> bucket = table[index]; // step 3
// check for existing key, update or append
// if [Link] >= TREEIFY_THRESHOLD(8) → convert to TreeNode
// if size > loadFactor * capacity → resize()
}

Java 8 Treeification
When a bucket has 8+ nodes, it converts from LinkedList to a Red-Black Tree, improving worst-case
lookup from O(n) to O(log n). It converts back to LinkedList when size drops to 6.

💡 Real Interview Tip


Expected follow-ups: What is load factor? (0.75 — balance between space and time).
What is capacity? (default 16, always power of 2 for efficient bitwise index calculation).
What happens when two keys have same hashCode but different equals? → same bucket,
different nodes (collision).
What if equals() returns true but hashCode() is different? → VIOLATION of contract, causes
data loss in HashMap!

⚠️Common Mistakes
Not implementing hashCode() when overriding equals() — breaks HashMap contract!
Using mutable objects as HashMap keys — if key state changes, you can't retrieve the
value.
Assuming HashMap is ordered — it is NOT. Use LinkedHashMap for insertion order,
TreeMap for sorted order.

❓ Interview Question
What is the difference between HashMap, LinkedHashMap, TreeMap, and
ConcurrentHashMap?

Feature HashMap LinkedHashMap TreeMap ConcurrentHash


Map
Order No order Insertion order Sorted No order
(natural/Comparat
or)
Null keys 1 null key allowed 1 null key allowed NO null key NO null key
Thread safety Not thread-safe Not thread-safe Not thread-safe Thread-safe
Performance O(1) avg O(1) avg O(log n) O(1) avg
Implementation Array + HashMap + Red-Black Tree Segment/CAS-
LinkedList/Tree DoublyLinkedList based
Use Case General purpose Cache (LRU), Sorted maps, Concurrent
ordered iteration ranges access

❓ Interview Question
How does ConcurrentHashMap work internally?

✅ Short Answer (For Interview)


In Java 8+, ConcurrentHashMap uses CAS (Compare-And-Swap) operations for lock-free
reads and writes.
It locks only individual buckets (not the entire map) during writes, allowing high concurrency.
In Java 7, it used Segment-based locking (16 segments by default).

// Java 8 ConcurrentHashMap — key operations


// READ: completely lock-free using volatile reads
// WRITE to empty bucket: uses CAS (no lock needed)
// WRITE to non-empty bucket: synchronized on that bucket only

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();


[Link]("key", 1);

// Atomic operations
[Link]("key", 2); // atomic
[Link]("key", k -> [Link]()); // atomic
[Link]("key", 1, Integer::sum); // atomic increment

❓ Interview Question
What is the difference between ArrayList and LinkedList?

Feature ArrayList LinkedList


Internal Structure Dynamic array (Object[]) Doubly linked list of Node
objects
Random Access O(1) — index-based O(n) — must traverse from head
Add at end O(1) amortized O(1)
Add/Remove at middle O(n) — shifting required O(1) if node reference available;
O(n) to find
Memory Less — only data More — data + prev/next
pointers
Cache performance Better (contiguous memory) Worse (scattered memory)
Use Case Read-heavy, index access Frequent insertions/deletions in
middle
// ArrayList — resizing happens when capacity exceeded
// Initial capacity = 10, grows by 50% each time (newCapacity = oldCapacity * 3/2
+ 1)
ArrayList<String> list = new ArrayList<>(100); // always set initial capacity if
size known

// LinkedList — implements both List and Deque


LinkedList<String> linked = new LinkedList<>();
[Link]("A"); // O(1)
[Link]("B"); // O(1)
[Link](5); // O(n) — avoid for large lists

💡 Real Interview Tip


In practice: ArrayList is preferred for most cases due to better cache performance.
LinkedList is good as a Deque/Queue — addFirst/addLast are O(1).
Interviewer may ask: 'When would you choose LinkedList over ArrayList?' — Answer: When
you have frequent O(1) insertions/removals at head/tail AND don't need random access.

❓ Interview Question
What is the contract between equals() and hashCode()?

✅ Short Answer (For Interview)


If two objects are equal (equals() returns true), they MUST have the same hashCode().
If two objects have the same hashCode(), they do NOT have to be equal (collision).
Violating this contract breaks HashMap, HashSet, and all hash-based collections.

// CORRECT implementation
public class Employee {
private int id;
private String name;

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee e = (Employee) o;
return id == [Link] && [Link](name, [Link]);
}

@Override
public int hashCode() {
return [Link](id, name); // same fields as equals()
}
}

// With Java records (Java 14+), equals/hashCode auto-generated:


public record Employee(int id, String name) {}

1.3 Java 8+ Features (Critical for Interviews)


❓ Interview Question
What are the major features introduced in Java 8?

✅ Short Answer (For Interview)


Java 8 introduced: Lambda expressions, Stream API, Functional Interfaces, Optional,
default/static interface methods,
Method references, new Date/Time API ([Link]), CompletableFuture, Nashorn JavaScript
engine, and parallel streams.

❓ Interview Question
Explain Lambda expressions and Functional Interfaces.

✅ Short Answer (For Interview)


A lambda is an anonymous function: (params) -> body. It can be assigned to a Functional
Interface reference.
A Functional Interface has exactly ONE abstract method (can have multiple default/static
methods).

// Functional Interface
@FunctionalInterface
interface MathOperation {
int operate(int a, int b); // single abstract method
}

// Lambda usage
MathOperation add = (a, b) -> a + b;
MathOperation multiply = (a, b) -> a * b;
[Link]([Link](5, 3)); // 8
[Link]([Link](5, 3)); // 15

// Built-in functional interfaces ([Link])


Predicate<String> isLong = s -> [Link]() > 5; // boolean test(T)
Function<String, Integer> len = String::length; // R apply(T)
Consumer<String> print = [Link]::println; // void accept(T)
Supplier<String> greeting = () -> "Hello"; // T get()
BiFunction<Integer,Integer,Integer> sum = (a,b)->a+b; // R apply(T,U)

❓ Interview Question
Explain the Stream API with examples.

✅ Short Answer (For Interview)


Stream API provides functional-style operations on collections. Streams are lazy, not data
structures.
Operations are: Intermediate (filter, map, sorted — return Stream) and Terminal (collect,
count, forEach — trigger processing).

List<Employee> employees = getEmployees();

// Find names of active employees earning > 50000, sorted by name


List<String> result = [Link]()
.filter(e -> [Link]()) // intermediate
.filter(e -> [Link]() > 50000) // intermediate
.map(Employee::getName) // intermediate
.sorted() // intermediate
.collect([Link]()); // terminal

// Group by department
Map<String, List<Employee>> byDept = [Link]()
.collect([Link](Employee::getDepartment));

// Average salary by department


Map<String, Double> avgSalary = [Link]()
.collect([Link](
Employee::getDepartment,
[Link](Employee::getSalary)));

// Parallel stream (use carefully!)


long count = [Link]()
.filter(e -> [Link]() > 50000)
.count();

💡 Real Interview Tip


Interviewers love: 'What is the difference between map() and flatMap()?'
map() transforms each element (1-to-1). flatMap() flattens nested streams (1-to-many).
Example: stream of lists → flatMap to get single stream of elements.
Also know: findFirst() vs findAny() (findAny is better for parallel streams).

// flatMap example
List<List<Integer>> nested = [Link]([Link](1,2),
[Link](3,4));
List<Integer> flat = [Link]()
.flatMap(Collection::stream) // [1,2,3,4]
.collect([Link]());

// map vs flatMap
List<String> words = [Link]("Hello World", "Java Stream");
// map gives Stream<String[]>
[Link]().map(s -> [Link](" "));
// flatMap gives Stream<String>
[Link]().flatMap(s -> [Link]([Link](" "))); //
[Hello,World,Java,Stream]

❓ Interview Question
What is Optional in Java 8 and how do you use it?

✅ Short Answer (For Interview)


Optional<T> is a container that may or may not contain a non-null value.
It is used to avoid NullPointerException and to make null-handling explicit in APIs.

// Creating Optional
Optional<String> opt1 = [Link]("value"); // throws NPE if null
Optional<String> opt2 = [Link](null); // empty Optional
Optional<String> opt3 = [Link](); // explicitly empty

// Using Optional
String result = [Link]("default"); // "value"
String result2 = [Link]("default"); // "default"
String result3 = [Link](() -> computeDefault()); // lazy
[Link](() -> new EntityNotFoundException()); // throw if empty

// Chaining
Optional<String> upper = opt1
.filter(s -> [Link]() > 3)
.map(String::toUpperCase);

// In service layer
public Optional<User> findUserById(Long id) {
return [Link](id); // Spring Data returns Optional
}

// In controller
User user = [Link](id)
.orElseThrow(() -> new UserNotFoundException("User not found: " + id));

⚠️Common Mistakes
Using Optional as method parameters — anti-pattern. Use overloads instead.
Calling [Link]() without isPresent() — defeats the purpose.
Using Optional for collection return types — return empty collection instead.
Serializing Optional fields — Optional is not Serializable.
CHAPTER 2: JVM INTERNALS & MEMORY MODEL

2.1 JVM Architecture


❓ Interview Question
Explain the JVM architecture and memory areas.

✅ Short Answer (For Interview)


JVM has: Class Loader (loads .class files), Runtime Data Areas (Heap, Stack, Method Area,
PC Register, Native Stack),
and Execution Engine (Interpreter + JIT Compiler + Garbage Collector).

JVM Memory Areas (Runtime Data Areas)


Memory Area Scope Content GC'd?
Heap Shared (all threads) Object instances, Yes
arrays
Stack Per thread Stack frames (local No (auto)
vars, operands, return
addresses)
Method Area Shared Class metadata, static Rarely
variables, constant
pool
PC Register Per thread Current instruction No
address
Native Method Stack Per thread Native (JNI) method No
calls

Heap Structure (Java 8+)


Heap Memory
├── Young Generation
│ ├── Eden Space ← new objects created here
│ ├── Survivor S0 ← survived one GC cycle
│ └── Survivor S1 ← survived another GC cycle
└── Old Generation (Tenured) ← long-lived objects

Metaspace (off-heap, Java 8+) ← class metadata (was PermGen in Java 7)

💡 Real Interview Tip


'Where are static variables stored?' → Method Area (Metaspace in Java 8+), NOT Heap.
'Where are String literals stored?' → String Pool in Heap (Java 8+).
Common follow-up: difference between PermGen and Metaspace — Metaspace auto-grows
(no fixed size), uses native memory.
2.2 Garbage Collection
❓ Interview Question
Explain the Garbage Collection process in Java.

✅ Short Answer (For Interview)


GC automatically reclaims memory from unreachable objects. Java uses generational GC:
most objects die young (Minor GC),
long-lived ones move to Old Gen (Major/Full GC). GC roots are the starting points: stack
variables, static fields, JNI references.

GC Process — Generational Collection


8. New objects created in Eden Space.
9. Minor GC: Eden is full → live objects moved to Survivor S0/S1 (copying), dead objects
collected.
10. Objects surviving multiple GC cycles (age threshold, default 15) promoted to Old Gen.
11. Major/Full GC: Old Gen is full → GC runs on entire Heap (stop-the-world pause).

GC Algorithm Description Use Case


Serial GC Single-threaded, stop-the-world Small heaps, single-core
Parallel GC (default Java 8) Multi-threaded Minor GC, stop- Throughput-focused apps
the-world Major GC
G1 GC (default Java 9+) Splits heap into regions, Large heaps (> 4GB), balanced
concurrent marking, predictable
pauses
ZGC (Java 15 GA) Concurrent, <10ms pause, Low-latency, very large heaps
region-based
Shenandoah Concurrent compaction, low Low-latency, open-source
pause

💡 Real Interview Tip


For Spring Boot microservices with containers: G1GC is default and usually fine.
Key JVM flags: -Xms (initial heap), -Xmx (max heap), -XX:+UseG1GC, -
XX:MaxGCPauseMillis=200.
If GC pauses are too long: increase heap, tune GC, check for memory leaks, use ZGC for
low-latency.

⚠️Common Mistakes
Calling [Link]() in production — just a hint, JVM may ignore it, causes full GC if
executed.
Memory leaks in Java are possible! Static collections, thread-local variables, unclosed
resources, listeners.
Not setting -Xmx in containers — JVM may take all container memory leading to OOM kill.
2.3 Multithreading & Concurrency
❓ Interview Question
What is the difference between synchronized, volatile, and ReentrantLock?

✅ Short Answer (For Interview)


synchronized: mutual exclusion for methods/blocks; volatile: visibility guarantee (no caching),
no atomicity;
ReentrantLock: explicit lock with more control (try-lock, fairness, multiple conditions).

// synchronized — simplest mutual exclusion


public synchronized void increment() { // method-level lock (this)
count++;
}
synchronized(this) { count++; } // block-level lock

// volatile — visibility only, NOT atomic for compound ops


private volatile boolean running = true; // changes visible across threads
immediately
// count++ is NOT safe with volatile (it's read-modify-write = 3 ops)

// ReentrantLock — explicit, flexible


private final ReentrantLock lock = new ReentrantLock();
public void increment() {
[Link]();
try {
count++;
} finally {
[Link](); // ALWAYS unlock in finally!
}
}
// Try-lock with timeout
if ([Link](5, [Link])) {
try { /* critical section */ }
finally { [Link](); }
}

❓ Interview Question
What are common concurrency issues and how do you prevent them?

Issue Description Prevention


Race Condition Multiple threads modify shared synchronized, Lock, AtomicXxx
state simultaneously
Deadlock Two threads wait for each Lock ordering, tryLock, timeout
other's locks forever
Livelock Threads keep responding to Randomized backoff
each other, no progress
Starvation Thread never gets CPU time Fair locks, thread priority tuning
Visibility Problem Thread reads stale cached volatile, synchronized, Atomic
value classes
// Deadlock example and prevention
// Deadlock: Thread1 holds lock A, waits for B
// Thread2 holds lock B, waits for A

// Prevention: always acquire locks in same order


// Or use tryLock with timeout:
if ([Link](100, [Link])) {
if ([Link](100, [Link])) {
try { /* work */ }
finally { [Link](); [Link](); }
} else { [Link](); } // release if can't get B
}

// AtomicInteger — lock-free thread-safe counter


AtomicInteger counter = new AtomicInteger(0);
[Link](); // atomic, no lock needed
[Link](expected, newValue); // CAS operation

💡 Real Interview Tip


ExecutorService is preferred over raw Thread creation for production code.
Use [Link] classes: ConcurrentHashMap, CopyOnWriteArrayList,
BlockingQueue, CountDownLatch, Semaphore.
ThreadPoolExecutor vs ForkJoinPool: use ForkJoinPool for recursive decomposable tasks
(parallel streams use it).
CHAPTER 3: SPRING BOOT & SPRING FRAMEWORK

3.1 Spring Core Concepts


❓ Interview Question
What is Dependency Injection and IoC? How does Spring implement it?

✅ Short Answer (For Interview)


IoC (Inversion of Control): the framework controls object creation instead of the application
code.
DI (Dependency Injection): dependencies are provided to a class from outside (by the
container), not created inside.
Spring implements DI via ApplicationContext (IoC container) using annotations or XML
configuration.

// Without DI — tightly coupled


public class OrderService {
private EmailService emailService = new EmailService(); // hard-coded
dependency
}

// With DI — loosely coupled


@Service
public class OrderService {
private final EmailService emailService; // injected by Spring

@Autowired // Constructor injection (RECOMMENDED)


public OrderService(EmailService emailService) {
[Link] = emailService;
}
}

Types of Dependency Injection


Type Mechanism Pros Cons
Constructor Injection @Autowired on Immutable, testable, Verbose with many
constructor (or implicit mandatory deps clear deps
in Spring 4.3+)
Setter Injection @Autowired on setter Optional deps, re- Object can be in
method injectable incomplete state
Field Injection @Autowired on field Concise code Not testable without
Spring, hides deps, not
recommended

💡 Real Interview Tip


Always prefer Constructor Injection — it ensures immutability and makes testing easy (no
Spring needed in unit tests).
Spring 4.3+: if class has single constructor, @Autowired is implicit.
Common follow-up: 'What is @Qualifier?' — used when multiple beans of same type exist to
specify which one to inject.
Type Mechanism Pros Cons

❓ Interview Question
Explain Spring Bean lifecycle.

✅ Short Answer (For Interview)


Bean lifecycle: Instantiation → Populate Properties → BeanNameAware/BeanFactoryAware
→ [Link]
→ @PostConstruct / afterPropertiesSet → [Link]
→ Bean Ready
→ @PreDestroy / destroy() when container shuts down.

@Component
public class MyBean implements InitializingBean, DisposableBean {

@PostConstruct // Phase 1: after properties set


public void init() {
[Link]("@PostConstruct: bean initialized");
}

@Override // Phase 2: from InitializingBean


public void afterPropertiesSet() {
[Link]("afterPropertiesSet called");
}

@PreDestroy // Phase 3: before bean destroyed


public void cleanup() {
[Link]("@PreDestroy: releasing resources");
}
}

❓ Interview Question
What are Spring Bean Scopes?

Scope Description Use Case


singleton (default) One instance per Spring Stateless services, DAOs
container
prototype New instance every time bean is Stateful beans, per-request
requested processing
request One instance per HTTP request Request-scoped data
(web only)
session One instance per HTTP session User session data
(web only)
application One instance per App-level shared state
ServletContext (web only)
websocket One instance per WebSocket WebSocket apps
session

⚠️Common Mistakes
Injecting prototype bean into singleton bean — prototype won't work as expected (only one
instance created).
Fix: use [Link](), @Lookup annotation, or ObjectProvider<T>.
Putting state in singleton beans — not thread-safe! Singletons are shared across all threads.

❓ Interview Question
What is the difference between @Component, @Service, @Repository, and @Controller?

✅ Short Answer (For Interview)


@Component is the generic stereotype. @Service, @Repository, and @Controller are
specializations.
@Repository adds exception translation (converts DB exceptions to Spring's
DataAccessException).
@Controller marks a Spring MVC controller. @RestController = @Controller +
@ResponseBody.

Annotation Layer Extra Features


@Component Any Generic Spring-managed
component
@Service Business Logic Semantic — marks service layer
(no extra magic)
@Repository Data Access Exception translation
(PersistenceException →
DataAccessException)
@Controller Presentation Spring MVC request handling
@RestController Presentation @Controller + @ResponseBody
on all methods
@Configuration Config Marks class as source of
@Bean definitions

❓ Interview Question
How does @Transactional work internally?

✅ Short Answer (For Interview)


@Transactional uses AOP proxy. Spring wraps the bean with a proxy that opens a
transaction before the method,
and commits/rolls back after the method completes. It uses ThreadLocal to bind the
transaction to the current thread.

// What @Transactional does behind the scenes:


// Spring creates a proxy wrapping your class:

// Conceptually equivalent to:


// try {
// [Link]();
// yourMethod();
// [Link]();
// } catch (RuntimeException e) {
// [Link]();
// throw e;
// }
@Service
public class OrderService {

@Transactional // default: propagation=REQUIRED, rollback on RuntimeException


public void placeOrder(Order order) {
[Link](order);
[Link](order); // if this fails, [Link]() rolls
back
[Link](order);
}

@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor =


[Link])
public void auditLog(String event) { // always runs in its own transaction
[Link](event);
}
}

Transaction Propagation Types


Propagation Behavior
REQUIRED (default) Join existing transaction or create new one
REQUIRES_NEW Always create new transaction, suspend existing
SUPPORTS Join if exists, run non-transactional if not
NOT_SUPPORTED Always run non-transactional, suspend existing
MANDATORY Must have existing transaction, throw if none
NEVER Must NOT have transaction, throw if one exists
NESTED Run within nested transaction if one exists

⚠️Common Mistakes
Self-invocation: calling @Transactional method from same class bypasses the proxy —
transaction NOT applied!
Fix: inject self reference, or use AspectJ mode.
@Transactional on private methods — does NOT work (proxy can't intercept private
methods).
Default rollback only on RuntimeException — checked exceptions do NOT trigger rollback by
default.
Use rollbackFor = [Link] to rollback on checked exceptions too.

3.2 Spring Boot Auto-Configuration


❓ Interview Question
How does Spring Boot auto-configuration work?

✅ Short Answer (For Interview)


@SpringBootApplication includes @EnableAutoConfiguration which loads [Link]
(or spring/autoconfigure/imports in Boot 3)
file from META-INF. Each AutoConfiguration class checks conditions
(@ConditionalOnClass, @ConditionalOnMissingBean)
to decide whether to create beans. This is convention over configuration.

@SpringBootApplication
// Equivalent to:
// @Configuration + @EnableAutoConfiguration + @ComponentScan

// How auto-configuration is triggered:


// 1. Spring Boot reads
META-INF/spring/[Link]
// 2. Finds classes like DataSourceAutoConfiguration
// 3. Checks conditions:

@ConditionalOnClass([Link]) // only if DataSource is on classpath


@ConditionalOnMissingBean([Link]) // only if user hasn't defined their
own
public class DataSourceAutoConfiguration {
@Bean
public DataSource dataSource() {
// creates HikariCP datasource from [Link]
}
}

// To debug what's auto-configured:


// --debug flag or [Link]=DEBUG
// Shows: 'CONDITIONS EVALUATION REPORT'
CHAPTER 4: REST API DESIGN & SPRING MVC

4.1 REST Principles


❓ Interview Question
What are the REST constraints and HTTP methods?

✅ Short Answer (For Interview)


REST (Representational State Transfer) constraints: Client-Server, Stateless, Cacheable,
Uniform Interface,
Layered System, Code on Demand (optional). HTTP methods: GET (read), POST (create),
PUT (full update),
PATCH (partial update), DELETE (remove), HEAD (headers only), OPTIONS (supported
methods).

HTTP Method Operation Idempotent? Safe? Request Body


GET Read resource Yes Yes No
POST Create resource No No Yes
PUT Full update Yes No Yes
(replace)
PATCH Partial update No (can be) No Yes
DELETE Remove resource Yes No Optional
HEAD Headers only (like Yes Yes No
GET)
OPTIONS Supported Yes Yes No
methods

HTTP Status Codes — Must Know


Code Meaning Use Case
200 OK Success GET, PUT, PATCH responses
201 Created Resource created POST creating new resource
204 No Content Success, no body DELETE, PUT with no response
body
400 Bad Request Client error — invalid input Validation failure, bad JSON
401 Unauthorized Not authenticated Missing/invalid JWT token
403 Forbidden Authenticated but not authorized Valid token but insufficient role
404 Not Found Resource not found ID doesn't exist
409 Conflict Conflict with current state Duplicate record, version
conflict
422 Unprocessable Entity Semantic validation error Business rule violation
500 Internal Server Error Server error Unhandled exception
Code Meaning Use Case
503 Service Unavailable Server not ready During maintenance, circuit
breaker open

❓ Interview Question
How do you design a RESTful API for a User resource?

// RESTful URL Design


GET /api/v1/users → get all users (with pagination)
GET /api/v1/users/{id} → get user by ID
POST /api/v1/users → create new user
PUT /api/v1/users/{id} → full update user
PATCH /api/v1/users/{id} → partial update user
DELETE /api/v1/users/{id} → delete user
GET /api/v1/users/{id}/orders → get orders for user (nested resource)

// Spring REST Controller


@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {

private final UserService userService;

@GetMapping
public ResponseEntity<Page<UserDTO>> getUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String search) {
return [Link]([Link](page, size, search));
}

@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable Long id) {
return [Link](id)
.map(ResponseEntity::ok)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
}

@PostMapping
public ResponseEntity<UserDTO> createUser(@Valid @RequestBody
CreateUserRequest req) {
UserDTO created = [Link](req);
URI location = [Link]("/api/v1/users/" + [Link]());
return [Link](location).body(created);
}

@PatchMapping("/{id}")
public ResponseEntity<UserDTO> updateUser(
@PathVariable Long id,
@Valid @RequestBody UpdateUserRequest req) {
return [Link]([Link](id, req));
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
[Link](id);
return [Link]().build();
}
}
❓ Interview Question
How do you implement global exception handling in Spring Boot?

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException
ex) {
return [Link](HttpStatus.NOT_FOUND)
.body(new ErrorResponse("NOT_FOUND", [Link]()));
}

@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse>
handleValidation(MethodArgumentNotValidException ex) {
List<String> errors = [Link]().getFieldErrors()
.stream()
.map(e -> [Link]() + ": " + [Link]())
.collect([Link]());
return [Link]()
.body(new ErrorResponse("VALIDATION_FAILED", [Link]()));
}

@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {
[Link]("Unexpected error", ex);
return [Link](HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ErrorResponse("INTERNAL_ERROR", "An unexpected error
occurred"));
}
}

@Data @AllArgsConstructor
public class ErrorResponse {
private String code;
private String message;
private Instant timestamp = [Link]();
}
CHAPTER 5: DATABASE, JPA & HIBERNATE

5.1 JPA & Hibernate Internals


❓ Interview Question
What is the difference between JPA and Hibernate?

✅ Short Answer (For Interview)


JPA (Jakarta Persistence API) is a specification/standard — it defines interfaces and
annotations.
Hibernate is an ORM implementation of the JPA specification. Other JPA providers:
EclipseLink, OpenJPA.
You code to JPA interfaces; Hibernate provides the implementation under the hood.

Aspect JPA Hibernate


Type Specification (JSR-338) Implementation (ORM)
Package [Link].* [Link].*
Query Language JPQL HQL (superset of JPQL)
Extra Features None beyond spec Caching, criteria, types, envers,
search
Usage Prefer JPA annotations Use Hibernate-specific features
when needed

❓ Interview Question
Explain Hibernate Persistence Context and Entity States.

✅ Short Answer (For Interview)


Persistence Context is a first-level cache that tracks all entities within a transaction.
Entity states: Transient (new, not managed), Persistent (managed by PC, changes auto-
synced),
Detached (was persistent, session closed), Removed (marked for deletion).
// Entity lifecycle states
@Transactional
public void entityLifecycle() {
// TRANSIENT — not associated with any persistence context
User user = new User("John");

// PERSISTENT — managed by EntityManager (first-level cache)


[Link](user); // now tracked by PC
[Link]("Jane"); // dirty checking — auto-saved on commit!

// DETACHED — after transaction ends or explicit detach


[Link](user); // changes no longer tracked
[Link]("Bob"); // this change NOT saved

// REMOVED
[Link]([Link](user)); // merge then remove
}

// Spring Data JPA equivalents:


User saved = [Link](user); // persist or merge
[Link](user); // remove

❓ Interview Question
What is the N+1 problem and how do you fix it?

✅ Short Answer (For Interview)


N+1 problem: when loading N entities causes N additional queries for associations (1 query
for parents + N for each child).
Fixes: EAGER loading (JOIN FETCH in JPQL), @EntityGraph, batch fetching, or DTO
projections.

// N+1 problem example


List<Order> orders = [Link](); // 1 query
for (Order o : orders) {
[Link]([Link]().getName()); // N queries!
}

// Fix 1: JOIN FETCH in JPQL


@Query("SELECT o FROM Order o JOIN FETCH [Link]")
List<Order> findAllWithCustomer();

// Fix 2: @EntityGraph
@EntityGraph(attributePaths = {"customer", "items"})
@Query("SELECT o FROM Order o")
List<Order> findAllWithDetails();

// Fix 3: @BatchSize (load lazily but in batches)


@OneToMany(mappedBy = "order", fetch = [Link])
@BatchSize(size = 50)
private List<OrderItem> items;

// Fix 4: DTO projection (most efficient)


@Query("SELECT new [Link]([Link], [Link]) FROM Order o JOIN
[Link] c")
List<OrderSummary> findOrderSummaries();

💡 Real Interview Tip


Enable SQL logging to detect N+1: [Link]-sql=true and
[Link]=DEBUG.
Use hibernate.generate_statistics=true and look at query count.
For complex read operations, consider using native queries or Spring Data Projections.
N+1 is one of the most common performance interview questions — always mention
detection AND all fix approaches.

❓ Interview Question
What is the difference between EAGER and LAZY loading?

Feature EAGER Loading LAZY Loading


When loaded Immediately with parent entity On first access
Default for @ManyToOne, @OneToOne @OneToMany, @ManyToMany
Performance More data fetched upfront Better if association often
unused
Risk Over-fetching, slow queries LazyInitializationException
outside transaction
Best practice Use for frequently-needed small Use for large collections
associations
// LazyInitializationException fix
// Problem: accessing lazy collection outside transaction

// Fix 1: @Transactional on calling method


@Transactional
public OrderDTO getOrderWithItems(Long id) {
Order order = [Link](id).orElseThrow();
[Link]().size(); // triggers lazy load within transaction
return [Link](order);
}

// Fix 2: JPQL with JOIN FETCH


// Fix 3: DTO projection (avoids entity graphs entirely)
// Fix 4: [Link]-in-view=false + explicit loading (recommended)
CHAPTER 6: MICROSERVICES ARCHITECTURE

6.1 Microservices Fundamentals


❓ Interview Question
What are microservices and how do they differ from monolith?

Aspect Monolith Microservices


Deployment Single deployable unit Each service deployed
independently
Scaling Scale entire application Scale individual services
Technology Single tech stack Polyglot (different tech per
service)
Development Simple, all in one codebase Complex, distributed system
Failure isolation One failure can crash all Failure isolated to service
Data Shared database Each service owns its data
Communication In-process method calls Network (REST, gRPC,
messaging)
Testing Easier integration testing Complex, needs contract testing
Use Case Small teams, simple domains Large teams, complex domains,
high scale

❓ Interview Question
What are the key patterns in microservices?

Essential Microservices Patterns


• API Gateway Pattern
• Single entry point for all clients. Handles routing, auth, rate limiting, SSL termination.
• Tools: Spring Cloud Gateway, Netflix Zuul, AWS API Gateway, Kong.

• Service Discovery Pattern


• Services register themselves; clients discover them dynamically.
• Tools: Eureka (client-side), Consul, Kubernetes DNS (server-side).

• Circuit Breaker Pattern


• Prevents cascading failures. States: Closed (normal), Open (fail fast), Half-Open (test recovery).
• Tools: Resilience4j, Hystrix (deprecated).

• Saga Pattern
• Manages distributed transactions across services. Choreography (events) vs Orchestration
(central coordinator).

• Event Sourcing & CQRS


• Event Sourcing: store state as sequence of events, not current state.
• CQRS: separate Command (write) and Query (read) models.

// Circuit Breaker with Resilience4j


@Service
public class PaymentService {

@CircuitBreaker(name = "paymentService", fallbackMethod = "fallbackPayment")


@Retry(name = "paymentService")
@TimeLimiter(name = "paymentService")
public CompletableFuture<PaymentResult> processPayment(PaymentRequest req) {
return [Link](() ->
[Link](req));
}

public CompletableFuture<PaymentResult> fallbackPayment(


PaymentRequest req, Throwable ex) {
[Link]("Payment service unavailable, using fallback", ex);
return
[Link]([Link]([Link]()));
}
}

# [Link]
resilience4j:
circuitbreaker:
instances:
paymentService:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 30s

❓ Interview Question
How do microservices communicate with each other?

Communication Style Technology Use Case


Synchronous REST Spring RestTemplate, Simple request-response,
WebClient, Feign CRUD operations
Synchronous gRPC gRPC (Protocol Buffers) High performance, strong
typing, streaming
Async Messaging Kafka, RabbitMQ, ActiveMQ Event-driven, decoupled, high
throughput
GraphQL GraphQL over HTTP Flexible queries, BFF pattern
// OpenFeign — declarative REST client
@FeignClient(name = "user-service", url = "${[Link]}",
fallbackFactory = [Link])
public interface UserClient {
@GetMapping("/api/v1/users/{id}")
Optional<UserDTO> getUserById(@PathVariable Long id);
}

// Kafka — event-driven communication


@Component
public class OrderEventProducer {
@Autowired private KafkaTemplate<String, OrderEvent> kafkaTemplate;

public void publishOrderCreated(Order order) {


[Link]("order-events", [Link]().toString(),
new OrderCreatedEvent([Link](), [Link]()));
}
}

@Component
public class InventoryEventConsumer {
@KafkaListener(topics = "order-events", groupId = "inventory-service")
public void handleOrderCreated(OrderCreatedEvent event) {
[Link]([Link]());
}
}
CHAPTER 7: SPRING SECURITY & API SECURITY

❓ Interview Question
How do you implement JWT-based authentication in Spring Boot?

✅ Short Answer (For Interview)


JWT (JSON Web Token) is a stateless token containing: [Link] (Base64
encoded).
Flow: Login → server generates JWT → client stores JWT → sends in Authorization header
→ server validates signature.

// JWT structure: [Link]


// Header: {"alg": "HS256", "typ": "JWT"}
// Payload: {"sub": "userId", "roles": ["ADMIN"], "exp": 1718000000}
// Signature: HMAC-SHA256(base64(header)+'.'+base64(payload), secretKey)

// JWT Filter
@Component
public class JwtAuthFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse
res,
FilterChain chain) throws ServletException, IOException {
String header = [Link]("Authorization");
if (header == null || ![Link]("Bearer ")) {
[Link](req, res); return;
}
String token = [Link](7);
try {
Claims claims = [Link](token);
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(
[Link](), null,
[Link]([Link]("roles")));
[Link]().setAuthentication(auth);
} catch (JwtException e) {
[Link]([Link]()); return;
}
[Link](req, res);
}
}

// Security Config
@Configuration @EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> [Link]()) // stateless — no CSRF needed
.sessionManagement(s ->
[Link]([Link]))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.addFilterBefore(jwtAuthFilter,
[Link])
.build();
}
}

💡 Real Interview Tip


Access token: short-lived (15 min), Refresh token: long-lived (7 days), stored in HttpOnly
cookie.
Common follow-up: 'How do you invalidate JWT?' — store token ID in Redis blacklist, or use
short expiry.
JWT vs Session: JWT is stateless (good for microservices), Session needs shared store for
multiple instances.
CHAPTER 8: CACHING, PERFORMANCE & OPTIMIZATION

8.1 Caching Strategies


❓ Interview Question
How do you implement caching in Spring Boot?

✅ Short Answer (For Interview)


Spring Cache abstraction with @EnableCaching. Use @Cacheable (read), @CachePut
(write-through), @CacheEvict (invalidate).
Backends: in-memory (ConcurrentHashMap), Caffeine (local), Redis (distributed).

@Service
@CacheConfig(cacheNames = "users")
public class UserService {

@Cacheable(key = "#id") // cache result by id


public UserDTO findById(Long id) {
return [Link](id).map(mapper::toDTO)
.orElseThrow(() -> new UserNotFoundException(id));
}

@CachePut(key = "#[Link]") // update cache after save


public UserDTO save(UserDTO dto) {
return [Link]([Link]([Link](dto)));
}

@CacheEvict(key = "#id") // remove from cache on delete


public void deleteById(Long id) {
[Link](id);
}

@CacheEvict(allEntries = true) // flush all cache entries


@Scheduled(fixedRate = 3600000) // every hour
public void evictAllCache() {}
}

# Redis configuration
[Link]=redis
[Link]=localhost
[Link]=6379
[Link]-to-live=30m

Cache Eviction Strategies


Strategy Description Use Case
LRU (Least Recently Used) Evict least recently accessed General purpose (default for
most caches)
LFU (Least Frequently Used) Evict least frequently accessed When access patterns matter
more than recency
TTL (Time To Live) Evict after fixed time Data with known staleness
tolerance
Strategy Description Use Case
Write-Through Write to cache and DB Read-heavy, consistency
simultaneously required
Write-Behind (Lazy) Write to cache, async write to Write-heavy, eventual
DB consistency OK
Cache-Aside App manages cache explicitly Flexibility, Spring @Cacheable
uses this
CHAPTER 9: DESIGN PATTERNS IN JAVA

❓ Interview Question
What are the most important design patterns for Java backend interviews?

Design patterns are categorized as Creational, Structural, and Behavioral. Focus on patterns used in
Spring itself.
Category Pattern Java/Spring Usage
Creational Singleton Spring singleton beans,
[Link]
Creational Factory Method BeanFactory,
[Link]()
Creational Builder StringBuilder,
[Link], Lombok
@Builder
Creational Prototype Spring prototype scope,
[Link]()
Structural Proxy Spring AOP, @Transactional,
@Cacheable
Structural Decorator InputStream wrapping, Spring
Security filters
Structural Adapter [Link](),
InputStreamReader
Behavioral Observer/Event ApplicationEvent, Kafka
consumers
Behavioral Template Method JdbcTemplate, RestTemplate
Behavioral Strategy Comparator, sorting algorithms
Behavioral Chain of Responsibility Servlet filters, Spring Security
filter chain
// Builder Pattern — production style
@Builder @Data
public class EmailRequest {
private String to;
private String subject;
private String body;
private List<String> cc;
private boolean isHtml;
}
// Usage: clean, readable, immutable
EmailRequest req = [Link]()
.to("user@[Link]")
.subject("Welcome!")
.body("<h1>Hello</h1>")
.isHtml(true)
.build();

// Strategy Pattern
public interface DiscountStrategy {
Category Pattern Java/Spring Usage
double apply(double price);
}
public class SeasonalDiscount implements DiscountStrategy {
public double apply(double price) { return price * 0.85; }
}
public class LoyaltyDiscount implements DiscountStrategy {
public double apply(double price) { return price * 0.90; }
}
// PricingService takes strategy — open for extension, closed for modification
(OCP)
CHAPTER 10: SCENARIO-BASED & PRODUCTION
QUESTIONS

10.1 System Design Scenarios


❓ Interview Question
Scenario: Your REST API is slow. How would you diagnose and fix it?

✅ Short Answer (For Interview)


Systematic approach: 1) Measure, 2) Profile, 3) Identify bottleneck, 4) Fix. Check DB queries
first (N+1, missing index),
then application logic (serialization, external calls), then infrastructure (connection pool,
network).

Step-by-Step Debugging Approach


12. Enable request timing logs and check P99 latency.
13. Enable SQL logging — look for N+1 queries, slow queries.
14. Check connection pool metrics (HikariCP) — pool exhaustion?
15. Profile with async-profiler or Arthas for CPU hotspots.
16. Check GC logs — excessive GC pauses?
17. Trace external service calls — any slow downstream services?
18. Use distributed tracing (Micrometer + Zipkin) in microservices.

Common Fixes
• DB: Add indexes, fix N+1 (JOIN FETCH), use read replicas, add caching.
• App: Use async processing, CompletableFuture for parallel calls, optimize serialization.
• Connection Pool: Increase pool size, tune checkout timeout.
• Caching: Add Redis cache for frequently-read data with low update frequency.
• Pagination: Avoid loading millions of records — use Pageable.

❓ Interview Question
Scenario: How would you handle duplicate API requests? (Idempotency)

✅ Short Answer (For Interview)


Use an idempotency key — client sends a unique key per request. Server checks if key
already processed.
If yes, return cached response. If no, process and store result with key.

@Service
public class IdempotentOrderService {

@Autowired private IdempotencyKeyRepository keyRepo;


@Autowired private RedisTemplate<String, String> redis;
@Transactional
public OrderResponse createOrder(CreateOrderRequest req, String
idempotencyKey) {
// Check if this request was already processed
String cached = [Link]().get("idempotency:" + idempotencyKey);
if (cached != null) {
return [Link](cached, [Link]);
}

// Process new request


Order order = processOrder(req);
OrderResponse response = [Link](order);

// Cache with TTL


[Link]().set(
"idempotency:" + idempotencyKey,
[Link](response),
[Link](24));

return response;
}
}

❓ Interview Question
Scenario: How would you implement rate limiting in a Spring Boot API?

// Using Bucket4j + Redis for distributed rate limiting


@Component
public class RateLimitFilter implements Filter {

private final Map<String, Bucket> cache = new ConcurrentHashMap<>();

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain
chain)
throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) req;
String clientIp = [Link]();

Bucket bucket = [Link](clientIp, this::newBucket);


if ([Link](1)) {
[Link](req, res);
} else {
((HttpServletResponse) res).setStatus(429); // Too Many Requests
((HttpServletResponse) res).getWriter().write("Rate limit exceeded");
}
}

private Bucket newBucket(String key) {


return [Link]()
.addLimit([Link](100, [Link](100,
[Link](1))))
.build();
}
}

❓ Interview Question
Scenario: How do you handle database migration in production?
✅ Short Answer (For Interview)
Use Flyway or Liquibase. Migration scripts are versioned and run automatically on startup.
Always make migrations backward-compatible: add columns as nullable first, then fill data,
then add constraints.

-- Flyway migration naming: V{version}__{description}.sql


-- V1__create_users_table.sql
CREATE TABLE users (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- V2__add_phone_to_users.sql (backward-compatible: nullable first)


ALTER TABLE users ADD COLUMN phone VARCHAR(20) NULL;

-- V3__add_phone_index.sql
CREATE INDEX idx_users_phone ON users(phone);

# [Link]
[Link]=true
[Link]=classpath:db/migration
[Link]-on-migrate=true
CHAPTER 11: TOP 50 MOST ASKED INTERVIEW
QUESTIONS
This chapter provides a rapid-fire reference of the most commonly asked questions with concise
answers.
# Question Answer
1 What is the difference between == compares object references;
== and equals()? equals() compares content.
Always override equals() and
hashCode() together.
2 Can we override static No. Static methods belong to
methods? the class, not the instance. They
can be hidden (shadowed) in
subclass but not overridden —
no polymorphism.
3 What is the difference between final: modifier (immutable var,
final, finally, and finalize()? no-override method, no-extend
class). finally: block that always
executes. finalize(): deprecated
GC hook.
4 What is the difference between Checked: must be
checked and unchecked caught/declared (IOException,
exceptions? SQLException). Unchecked:
RuntimeException subclasses
(NPE,
IllegalArgumentException).
Spring recommends unchecked.
5 What is try-with-resources? Java 7 feature: resources
implementing AutoCloseable
are automatically closed.
Eliminates finally block for
cleanup.
6 What is a functional interface? Interface with exactly one
abstract method.
@FunctionalInterface
annotation enforces this.
Examples: Runnable,
Comparator, Callable,
Predicate.
7 What is method reference? Shorthand for lambda:
ClassName::methodName.
Types: static (Math::abs),
instance (str::length),
constructor (User::new),
arbitrary instance
(String::toUpperCase).
8 What is CompletableFuture? Java 8 async programming.
Supports chaining: thenApply
(transform), thenAccept
# Question Answer
(consume), thenCompose
(flatMap), allOf (wait all), anyOf
(first completed).
9 What is the difference between Comparable: natural ordering (in
Comparable and Comparator? class, compareTo). Comparator:
external ordering (outside class,
compare).
[Link]() for
chaining.
10 What are generics in Java? Type parameterization for
compile-time type safety.
Wildcards: ? extends T (read), ?
super T (write), ? (unknown).
Type erasure at runtime.
11 What is the difference between List<Object> only accepts
List<?> and List<Object>? List<Object>. List<?> accepts
any parameterized List. Use
wildcards for flexible APIs.
12 What is enum in Java? Type-safe constants. Can have
fields, constructors, methods.
Implicit Comparable,
Serializable.
EnumSet/EnumMap for
efficiency.
13 What is a record in Java 16? Immutable data carrier class.
Auto-generates constructor,
getters, equals, hashCode,
toString. Perfect for DTOs and
value objects.
14 What is a sealed class (Java Restricts which classes can
17)? extend/implement it. Uses
permits keyword. Enables
exhaustive pattern matching in
switch expressions.
15 What is var in Java 10? Local variable type inference.
var infers type from right-hand
side. Only for local variables,
not fields, parameters, or return
types.
16 What is the difference between Hashtable: synchronized (slow),
HashMap and Hashtable? no null keys/values, legacy.
HashMap: not synchronized,
allows one null key. Use
ConcurrentHashMap for thread
safety.
17 What is fail-fast vs fail-safe Fail-fast: throws
iterator? ConcurrentModificationExceptio
n if collection modified during
iteration (ArrayList). Fail-safe:
iterates on copy
(CopyOnWriteArrayList).
# Question Answer
18 What is the purpose of the Marks field to be excluded from
transient keyword? Java serialization. Use for
sensitive data (passwords),
derived fields, or non-
serializable objects.
19 What is reflection in Java? Inspect and modify class
structure at runtime. Used by
Spring (DI), JUnit, ORM
frameworks. Has performance
overhead — avoid in hot paths.
20 What is a ClassLoader? Loads .class files. Hierarchy:
Bootstrap → Extension
(Platform) → Application.
ClassLoader isolation used in
OSGi, containers, hot reload.
21 What is the difference between @Autowired is Spring-specific;
@Autowired and @Inject? @Inject is JSR-330 standard.
Both support
constructor/field/setter injection.
@Autowired has required
attribute.
22 What is @Value in Spring? Injects property values:
@Value("${[Link]}").
Supports SpEL:
@Value("#{[Link]
Role}"). Use
@ConfigurationProperties for
grouped properties.
23 What is Binds external configuration
@ConfigurationProperties? properties to a POJO. Type-
safe, supports validation, IDE
autocomplete with spring-boot-
configuration-processor.
24 What is Spring Profiles? Environment-specific
configuration. @Profile("prod")
activates beans for profile. Set:
[Link]=prod.
Useful for dev/staging/prod
configs.
25 What is @Scheduled in Spring? Schedules methods. Requires
@EnableScheduling. Supports:
fixedRate, fixedDelay, cron
expressions. Not distributed —
use Quartz or ShedLock for
clusters.
26 What is Spring AOP? Aspect-Oriented Programming.
Cross-cutting concerns (logging,
security, transactions) without
modifying business code.
Concepts: Aspect, JoinPoint,
Pointcut, Advice, Weaving.
27 What are Spring AOP advice @Before, @After,
# Question Answer
types? @AfterReturning,
@AfterThrowing, @Around.
@Around is most powerful —
controls method execution.
28 What is the difference between @PathVariable extracts from
@PathVariable and URL path (/users/{id}).
@RequestParam? @RequestParam from query
string (?page=0&size=10).
29 What is ResponseEntity in Wrapper for HTTP response
Spring? with status code, headers, and
body. Gives full control over
response:
[Link](body),
[Link](location
).body(body).
30 What is @RequestBody vs @RequestBody: deserializes
@ResponseBody? request body (JSON → Java).
@ResponseBody: serializes
return value to response body
(Java → JSON).
@RestController = @Controller
+ @ResponseBody.
31 What is Spring Data JPA? Abstraction over JPA.
CrudRepository, JpaRepository,
PagingAndSortingRepository.
Query by method name,
@Query, Specifications,
QueryDSL.
32 What is @Entity and @Table? @Entity marks a class as JPA
entity (maps to DB table).
@Table specifies table name.
@Column maps fields. @Id +
@GeneratedValue for primary
key.
33 What is [Link] vs LAZY: load on first access
EAGER? (default for @OneToMany).
EAGER: load with parent
(default for @ManyToOne).
Prefer LAZY, use JOIN FETCH
when needed.
34 What is JPA Criteria API? Type-safe, programmatic query
building. Alternative to string-
based JPQL. Better for dynamic
queries. Used with Specification
pattern in Spring Data.
35 What is the difference between save(): queues changes
save() and saveAndFlush() in (flushes on transaction commit).
JPA? saveAndFlush(): immediately
flushes to DB. Use
saveAndFlush() when you need
DB to reflect changes
immediately within same
# Question Answer
transaction.
36 What is Kafka and when to use Distributed event streaming
it? platform. Use when: high
throughput, event sourcing,
decoupling services, audit logs,
real-time streaming. Topics,
partitions, consumer groups,
offsets.
37 What is the difference between @RestController = @Controller
@RestController and + @ResponseBody on all
@Controller? methods. @Controller returns
view names (for
JSP/Thymeleaf).
@RestController returns
JSON/XML directly.
38 What is CORS? Cross-Origin Resource Sharing.
Browser security policy.
Configure in Spring with
@CrossOrigin,
[Link]
ppings(), or Spring Security.
39 What is SSL/TLS? HTTPS encryption. In Spring
Boot: configure in
[Link] with
[Link].* properties. In
production: terminate SSL at
load balancer/API gateway.
40 What is connection pooling? Reusing DB connections
instead of creating new ones.
HikariCP is default in Spring
Boot. Key settings:
maximumPoolSize,
minimumIdle,
connectionTimeout,
idleTimeout.
41 What is the difference between PUT: full resource replacement
PUT and PATCH? (send all fields). PATCH: partial
update (send only changed
fields). PUT is idempotent.
PATCH may not be.
42 What is optimistic vs pessimistic Optimistic: @Version field,
locking in JPA? assumes no conflict, fails on
concurrent write. Pessimistic:
DB-level lock (SELECT FOR
UPDATE), assumes conflict,
blocks reads/writes.
43 What is ACID in databases? Atomicity (all or nothing),
Consistency (valid state),
Isolation (transactions don't
interfere), Durability (committed
= persisted). ACID vs BASE in
distributed systems.
# Question Answer
44 What is database indexing? B-tree index accelerates
queries. Add on: WHERE
clause columns, JOIN columns,
ORDER BY columns, foreign
keys. Avoid over-indexing
(slows writes).
45 What is database Organizing to reduce
normalization? redundancy: 1NF (atomic
values), 2NF (no partial
dependency), 3NF (no transitive
dependency). Denormalize for
read performance.
46 What is the difference between INNER JOIN: matching rows
SQL JOIN types? only. LEFT JOIN: all from left +
matching right. RIGHT JOIN:
reverse. FULL OUTER: all rows
from both. CROSS JOIN:
cartesian product.
47 What is a deadlock in SQL? Two transactions wait for each
other's locks. Prevention:
consistent lock ordering, short
transactions, SELECT FOR
UPDATE only when needed.
48 What is Docker and how is it Containerization platform.
used with Spring Boot? Spring Boot JAR runs in Docker
container. Dockerfile: FROM
eclipse-temurin:21-jre, COPY,
ENTRYPOINT. docker-compose
for local multi-service setup.
49 What are 12-Factor App Codebase, Dependencies,
principles? Config (env vars), Backing
services, Build/release/run,
Processes, Port binding,
Concurrency, Disposability,
Dev/prod parity, Logs, Admin
processes.
50 What is observability in Three pillars: Logs (structured,
microservices? centralized — ELK/Loki),
Metrics (Micrometer +
Prometheus + Grafana), Traces
(distributed — Micrometer
Tracing + Zipkin/Jaeger).
CHAPTER 12: TRICKY & CONFUSING QUESTIONS

❓ Interview Question
What is the output of: Integer a = 127; Integer b = 127; [Link](a == b);

✅ Short Answer (For Interview)


true. Java caches Integer objects from -128 to 127 (Integer Cache / Flyweight).
For values outside this range, Integer a = 128; Integer b = 128; a == b → false (different
objects).

Integer a = 127; Integer b = 127;


[Link](a == b); // true (cached)

Integer c = 128; Integer d = 128;


[Link](c == d); // false (different objects)
[Link]([Link](d)); // true (always use equals for comparison)

❓ Interview Question
What happens when you call hashCode() on a null object?

✅ Short Answer (For Interview)


NullPointerException. Use [Link](obj) which returns 0 for null.
Also: [Link](a, b) handles nulls safely.

❓ Interview Question
Can you have a try block without catch?

✅ Short Answer (For Interview)


Yes, with try-finally (no catch). Or try-with-resources (resources auto-closed, no catch
required).
You CANNOT have try without either catch or finally.

❓ Interview Question
What is [Link]() used for?

✅ Short Answer (For Interview)


Returns a canonical representation from the String Pool. If pool has equal string, returns that
reference.
Avoids duplicate strings in memory. Rarely needed today — JVM optimizes string literals
automatically.

❓ Interview Question
Why is [Link] != [Link] true?

✅ Short Answer (For Interview)


IEEE 754 spec: NaN is not equal to anything, including itself.
Use [Link](value) to check for NaN.

❓ Interview Question
What is the difference between Exception and Error in Java?

✅ Short Answer (For Interview)


Both extend Throwable. Exception: recoverable (application errors). Error: unrecoverable
JVM problems
(OutOfMemoryError, StackOverflowError). Catch errors only for logging — you cannot
recover from them.

❓ Interview Question
Can you make a constructor private? What is the use case?

✅ Short Answer (For Interview)


Yes. Used for: Singleton pattern, utility classes (only static methods), Builder pattern, factory
method pattern.
Example: Math class has private constructor — no instantiation intended.

❓ Interview Question
What is the difference between i++ and ++i in multi-threaded code?

✅ Short Answer (For Interview)


Neither is thread-safe — both are read-modify-write operations (3 steps), not atomic.
Use [Link]() (++i equivalent) or [Link]()
(i++ equivalent).

❓ Interview Question
If @Transactional method A calls @Transactional method B in the same class, does B get
its own transaction?

✅ Short Answer (For Interview)


NO. Self-invocation bypasses the AOP proxy — B runs in A's transaction (REQUIRED
propagation behaves as expected but REQUIRES_NEW does NOT start new transaction).
Fix: inject the bean via ApplicationContext, use @Lazy self-injection, or AspectJ weaving.

@Service
public class MyService {
@Autowired private MyService self; // self-injection workaround

@Transactional
public void methodA() {
[Link](); // goes through proxy — transaction works correctly
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodB() { ... }
}
CHAPTER 13: RAPID REVISION NOTES
Use this chapter for last-minute interview preparation. Read through these key points the day before
your interview.

Core Java — Quick Hits


• String is immutable — char[] is final and private. Pool in Heap (Java 8+).
• HashMap: array of buckets + LinkedList/Tree. Default capacity 16, load factor 0.75.
• Java 8: Lambda, Stream, Optional, default methods, new Date/Time API.
• Functional interfaces: Predicate<T>, Function<T,R>, Consumer<T>, Supplier<T>,
BiFunction<T,U,R>.
• Streams are lazy — nothing executes until terminal operation.
• flatMap = map + flatten. Useful for nested collections.
• equals() + hashCode() contract: equal objects MUST have same hashCode.
• Checked exceptions must be caught/declared. Unchecked (RuntimeException) need not.
• synchronized = mutual exclusion. volatile = visibility only (no atomicity).
• AtomicInteger, AtomicLong for lock-free thread-safe counters using CAS.

JVM — Quick Hits


• Heap: Young Gen (Eden + S0 + S1) + Old Gen. Metaspace = off-heap class metadata.
• Minor GC: Young Gen. Major/Full GC: Old Gen. GC roots: stack, statics, JNI.
• G1GC default in Java 9+. ZGC for <10ms pause, large heaps.
• -Xms = initial heap, -Xmx = max heap.

Spring Boot — Quick Hits


• IoC: Spring controls bean creation. DI: Spring injects dependencies.
• Prefer Constructor Injection: immutable, testable, no circular dep issues.
• @Transactional: AOP proxy wraps method. Self-invocation bypasses proxy!
• Default rollback: only RuntimeException. Use rollbackFor = [Link] for checked.
• Singleton beans are NOT thread-safe — no mutable state in singletons.
• @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan.
• [Link] / [Link] drives auto-config via @ConditionalOn*.

JPA/Hibernate — Quick Hits


• N+1 problem: fix with JOIN FETCH, @EntityGraph, batch fetching, or DTO projections.
• Entity states: Transient → Persistent → Detached → Removed.
• Dirty checking: modifications to persistent entities auto-saved on commit.
• @OneToMany LAZY default. @ManyToOne EAGER default. Prefer LAZY everywhere.
• [Link]-in-view=false is recommended (prevents lazy init issues masking design
problems).

REST API — Quick Hits


• GET=read, POST=create, PUT=full update, PATCH=partial, DELETE=remove.
• Idempotent: GET, PUT, DELETE, HEAD, OPTIONS. NOT idempotent: POST.
• 201 Created (POST), 204 No Content (DELETE), 400 validation, 401 unauth, 403 forbidden,
404 not found, 409 conflict.
• Use @Valid + @ControllerAdvice for consistent error handling.
• Pagination: Pageable in Spring Data, return Page<T>.

Microservices — Quick Hits


• API Gateway: single entry point, routing, auth, rate limiting.
• Circuit Breaker states: Closed → Open → Half-Open.
• Saga: distributed transactions. Choreography (events) vs Orchestration (central).
• Kafka: topics, partitions, consumer groups, offsets. At-least-once delivery default.
• Service Mesh (Istio): sidecar proxy for service-to-service auth, observability, traffic control.

Database — Quick Hits


• ACID: Atomicity, Consistency, Isolation, Durability.
• Index types: B-Tree (default), Hash, Full-text, Composite. Index on WHERE, JOIN, ORDER BY
columns.
• Isolation levels: Read Uncommitted < Read Committed < Repeatable Read < Serializable.
• Flyway/Liquibase for DB migrations — always backward-compatible.
• Optimistic locking: @Version field. Pessimistic: SELECT FOR UPDATE.
CHEAT SHEET — KEYWORDS TO REMEMBER

Core Java Keywords


Topic Key Terms
OOP Encapsulation, Abstraction, Inheritance,
Polymorphism, Overloading, Overriding, IS-A,
HAS-A
String Immutable, String Pool, intern(), StringBuilder,
StringBuffer, equals() not ==
Collections HashMap: bucket, hash, equals, treeify, load
factor, capacity. fail-fast, fail-safe
Generics Type erasure, bounded wildcards (? extends, ?
super), raw type
Java 8 Lambda, Stream, Optional, @FunctionalInterface,
Method reference, default methods,
CompletableFuture
Streams lazy, intermediate, terminal, flatMap,
[Link], parallel
Concurrency synchronized, volatile, ReentrantLock, CAS,
AtomicInteger, ThreadPool, deadlock, race
condition
Exceptions Checked, unchecked, try-with-resources, finally,
throw vs throws

Spring Keywords
Topic Key Terms
Core IoC, DI, ApplicationContext, BeanFactory,
BeanLifecycle, @PostConstruct, @PreDestroy
Annotations @Component, @Service, @Repository,
@Controller, @RestController, @Configuration,
@Bean
Transaction @Transactional, propagation, isolation,
rollbackFor, self-invocation, AOP proxy
JPA EntityManager, PersistenceContext, dirty
checking, N+1, JOIN FETCH, @EntityGraph, lazy
loading
Security JWT, stateless, SecurityFilterChain,
@PreAuthorize, RBAC, CORS, CSRF
Boot auto-configuration, @ConditionalOn*,
[Link], @SpringBootApplication, profiles
Cache @Cacheable, @CacheEvict, @CachePut, TTL,
LRU, Redis, cache-aside
Architecture Keywords
Topic Key Terms
REST stateless, idempotent, safe, HATEOAS,
versioning, pagination, rate limiting, idempotency
key
Microservices API Gateway, Service Discovery, Circuit Breaker,
Saga, CQRS, Event Sourcing, Bulkhead
Messaging topic, partition, consumer group, offset, at-least-
once, exactly-once, DLQ (Dead Letter Queue)
Observability Logs (ELK), Metrics (Prometheus/Grafana),
Traces (Zipkin/Jaeger), Micrometer
DB ACID, index, N+1, optimistic/pessimistic locking,
connection pool, migration, normalization
Performance caching, async, pagination, read replica, CQRS,
connection pooling, CDN

🏆 Final Interview Tips


1. Always structure your answers: definition → how it works → example → when to use /
when not to use.
2. Mention real-world experience: 'In my project, I used X to solve Y problem.'
3. Ask clarifying questions before answering system design questions.
4. Explain trade-offs — interviewers want to see you understand there's no silver bullet.
5. Know your CV/project deeply — most questions come from it at 2-4 year experience level.
6. Follow-up questions are expected — prepare 2-3 levels deep on each topic.
7. Show enthusiasm for best practices: SOLID, Clean Code, testing, CI/CD.
8. If you don't know something, say so honestly and describe how you would find out.

You might also like