Java Backend Interview Master Handbook (Detailed
Edition)
Comprehensive answers, explanations, architecture notes, and coding examples based on the
uploaded interview guide.
JVM, JDK, JRE and Memory Management
JVM executes Java bytecode and provides platform independence. JRE contains JVM and runtime
libraries.
JDK contains JRE plus compiler, debugger and development tools.
JVM Runtime Areas:
• Heap – objects and arrays.
• Stack – method frames and local variables.
• Metaspace – class metadata.
• PC Register – current instruction.
• Native Method Stack – native code execution.
GC Analysis:
1. Collect GC logs.
2. Check allocation rate.
3. Identify Full GC frequency.
4. Analyze heap dump.
5. Tune heap sizing and collectors (G1GC, ZGC).
Example:
public class MemoryDemo {
public static void main(String[] args){
List data = new ArrayList<>();
while(true){
[Link](new byte[1024*1024]);
}
}
}
Java Memory Model and Concurrency
JMM defines visibility, ordering and atomicity.
Happens-Before Rules:
• Lock release before lock acquire.
• Volatile write before volatile read.
• Thread start before thread execution.
• Thread completion before join returns.
Volatile Example:
private volatile boolean running=true;
Atomic Operations:
AtomicInteger counter = new AtomicInteger();
[Link]();
Java 8 Functional Programming
Functional Interface:
@FunctionalInterface
interface Calculator {
int add(int a,int b);
}
Lambda:
Calculator c=(a,b)->a+b;
Method References:
String::toUpperCase
[Link]::println
CompletableFuture:
[Link](() -> fetch())
.thenApply(String::toUpperCase)
.thenAccept([Link]::println);
Parallel Streams:
Use for CPU intensive workloads.
Avoid for blocking IO-heavy web requests.
Collections Framework Deep Dive
ArrayList:
Dynamic array with O(1) random access.
HashMap Internal Flow:
hashCode -> bucket index -> linked list/tree.
Treeification occurs after threshold and sufficient capacity.
Employee Salary Sorting:
[Link](
[Link](Employee::getSalary)
.reversed()
);
ConcurrentHashMap:
Provides high concurrency with bucket-level synchronization.
CopyOnWriteArrayList:
Creates new copy on every write.
Best for read-heavy systems.
Exception Handling
Hierarchy:
Throwable
|- Error
|- Exception
Checked Exception:
IOException
Unchecked:
NullPointerException
Try-With-Resources:
try(BufferedReader br =
new BufferedReader(new FileReader("[Link]"))){
}
Finally Block:
Executes even after return unless JVM terminates.
String Internals
Strings are immutable.
String Pool:
String a="Java";
String b="Java";
Both refer to same pooled object.
Interning:
String x=new String("Java");
String y=[Link]();
StringBuilder:
Fastest mutable string manipulation.
Multithreading
Creating Threads:
1. Extend Thread
2. Implement Runnable
3. Callable + Future
4. ExecutorService
Synchronization:
synchronized(this){
// critical section
}
ReentrantLock:
[Link]();
try{
}finally{
[Link]();
}
CountDownLatch:
Used for one-time coordination.
CyclicBarrier:
Reusable synchronization barrier.
Spring Core
IOC:
Spring manages object creation.
Dependency Injection:
Constructor Injection (recommended).
@Bean Example:
@Configuration
class Config {
@Bean
EmployeeService service(){
return new EmployeeService();
}
}
Bean Lifecycle:
Instantiation -> Dependency Injection -> PostConstruct -> Ready -> Destroy.
Spring Boot
@SpringBootApplication =
@Configuration +
@EnableAutoConfiguration +
@ComponentScan
@RestController Example:
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@GetMapping("/{id}")
public Employee get(@PathVariable Long id){
return [Link](id);
}
}
ResponseEntity allows custom headers and status codes.
REST API Design
Best Practices:
• Use nouns in URLs.
• Version APIs.
• Proper HTTP status codes.
GET /api/v1/employees
POST /api/v1/employees
Idempotent:
GET PUT DELETE
Non-Idempotent:
POST
File Upload:
@PostMapping("/upload")
public String upload(
@RequestParam MultipartFile file){
}
Caching
@EnableCaching
@Cacheable(value="users",key="#id")
public User get(Long id){}
@CachePut updates cache.
@CacheEvict removes cache.
Multi-Level Cache:
L1: Local Cache
L2: Redis
Cache Stampede Prevention:
• Locking
• Random TTL
• Warm-up strategies
Validation and Exception Handling
@Valid validates request bodies.
@Validated validates method parameters.
Custom Validation:
@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy=[Link])
Global Handler:
@RestControllerAdvice
public class GlobalHandler {
@ExceptionHandler([Link])
public ResponseEntity handle(Exception ex){
return [Link]().build();
}
}
JPA and Hibernate
Entity Example:
@Entity
@Table(name="employee")
class Employee {
@Id
@GeneratedValue(strategy=[Link])
private Long id;
private String name;
}
Fetch Types:
LAZY – load when required.
EAGER – load immediately.
N+1 Problem:
Occurs due to repeated queries while traversing relations.
Solutions:
• Fetch Join
• Entity Graph
• Batch Fetching
Advanced Spring Data JPA
Pagination:
Page result =
[Link]([Link](0,10));
JPQL:
@Query("select e from Employee e where [Link]>:salary")
Update Query:
@Modifying
@Transactional
Optimistic Locking:
@Version
Pessimistic Locking:
@Lock(PESSIMISTIC_WRITE)
Database Concepts
ACID:
Atomicity
Consistency
Isolation
Durability
INNER JOIN:
Returns matching records.
LEFT JOIN:
Returns all left rows plus matches.
Second Highest Salary:
SELECT MAX(salary)
FROM employee
WHERE salary <
(SELECT MAX(salary) FROM employee);
Window Function:
ROW_NUMBER()
OVER(PARTITION BY dept ORDER BY salary DESC)
Indexes and Partitioning
Index Advantages:
• Faster Reads
• Faster Searches
Disadvantages:
• More storage
• Slower inserts
Partition Types:
• Range
• List
• Hash
Example:
PARTITION BY RANGE(order_date)
Microservices Architecture
Benefits:
• Independent deployment
• Independent scaling
• Fault isolation
Challenges:
• Distributed transactions
• Monitoring
• Network latency
Communication:
REST
gRPC
Kafka
RabbitMQ
Event Driven Architecture and Saga
Event:
Something happened.
Command:
Request to do something.
Saga Types:
1. Choreography
2. Orchestration
Compensation Example:
Order Created
Payment Failed
→ Cancel Order
Ensures eventual consistency.
Resilience Patterns
Circuit Breaker:
Open -> Half Open -> Closed
Resilience4j:
@CircuitBreaker(name="payment")
Retry:
@Retry(name="payment")
Bulkhead:
Limits resource consumption.
Rate Limiting:
Protects services from overload.
Kubernetes and Scalability
Horizontal Scaling:
More instances.
Vertical Scaling:
More CPU/RAM.
HPA:
Horizontal Pod Autoscaler
kubectl autoscale deployment app
--cpu-percent=70 --min=2 --max=10
Service Discovery:
Eureka
Consul
Kubernetes Services
Distributed Tracing
TraceId identifies request flow.
SpanId identifies individual operation.
Spring Boot:
Micrometer
OpenTelemetry
Zipkin
Jaeger
Flow:
Client -> Gateway -> ServiceA -> ServiceB
All carry same TraceId.