JAVA BACKEND DEVELOPER
INTERVIEW QUESTION BANK
Fresher → 3 Years Experience | India Market
Service Companies · Mid-Level Product Companies
300 + High-Quality Questions · Zero Duplicates · Real Interview Patterns
Topics: Core Java · Java 8+ · Multithreading · Spring Boot · REST · JPA · SQL ·
Microservices · Frontend Basics
SECTION 1 — FRESHER LEVEL (0 – 1 Year)
■ CORE JAVA — OOP & Basics
1. What is the difference between a class and an object in Java?
2. What are the four pillars of OOP and give one real-world example for each?
3. What is the difference between method overloading and method overriding?
4. What is the difference between an abstract class and an interface?
5. When would you choose an abstract class over an interface?
6. What is polymorphism? Give a backend example.
7. What is encapsulation and why is it important in a REST service?
8. What is the difference between 'is-a' and 'has-a' relationships?
9. What is constructor chaining and how does it work with this() and super()?
10. What is the difference between static and instance methods?
11. Can you override a static method in Java? Why or why not?
12. What is the 'final' keyword and where can it be applied?
13. What is the difference between == and .equals() for Strings?
14. What is autoboxing and unboxing? Where can it cause issues?
15. What is the difference between pass-by-value and pass-by-reference in Java?
■ CORE JAVA — Memory & JVM Basics
1. What is the difference between JVM, JDK, and JRE?
2. What is the difference between heap and stack memory in JVM?
3. What type of data is stored in the stack vs the heap?
4. What is a memory leak in Java? Give a simple example.
5. What does the 'new' keyword do internally in terms of memory?
6. What is the difference between local variables and instance variables in memory?
7. What is garbage collection and how does it work in Java?
8. What is the purpose of the 'finalize()' method? Is it reliable?
■ COLLECTIONS — Fresher
1. What is the difference between ArrayList and LinkedList?
2. When would you use LinkedList over ArrayList?
3. What is the difference between HashMap and TreeMap?
4. What is the difference between HashMap and HashSet?
5. What is the difference between HashMap and LinkedHashMap?
6. What is the initial capacity and load factor of HashMap?
7. What happens when you add a duplicate key to a HashMap?
8. How does HashMap handle null keys and null values?
9. What is the difference between fail-fast and fail-safe iterators?
10. What is the difference between Iterator and ListIterator?
11. How do you iterate over a Map in Java?
12. What is the difference between Comparable and Comparator?
13. How do you sort a list of Employee objects by salary?
14. What is the difference between Stack and Queue in Java?
15. What is a PriorityQueue and how does it order elements?
■ EXCEPTION HANDLING — Fresher
1. What is the difference between checked and unchecked exceptions?
2. What is the parent class of all exceptions in Java?
3. What is the difference between Error and Exception?
4. What is a finally block and when does it execute?
5. Can a finally block override a return statement in try?
6. What is try-with-resources and when should you use it?
7. How do you create a custom exception in Java?
8. What is exception propagation? Show with a simple example.
9. When should you use throws vs try-catch?
■ STRINGS — Fresher
1. Why is String immutable in Java?
2. What is the String pool / String literal pool?
3. What is the difference between String, StringBuilder, and StringBuffer?
4. How many objects are created: String s = new String("hello");?
5. How many objects are created: String s1 = "hello"; String s2 = "hello";?
6. What does [Link]() do?
7. What is the output: String s = "Hello"; [Link](" World"); [Link](s);?
8. When should you use StringBuilder over String concatenation in a loop?
■ JAVA 8 — Fresher
1. What is a functional interface? Is the @FunctionalInterface annotation mandatory?
2. What is a lambda expression? How does it simplify anonymous inner classes?
3. What is the difference between Predicate, Function, Consumer, and Supplier?
4. What is a default method in an interface? Why was it added in Java 8?
5. What is a method reference? Give an example for each type.
6. What is the difference between map() and flatMap() in Streams?
7. What is the difference between filter(), map(), and reduce()?
8. What is the difference between intermediate and terminal operations in Streams?
9. What is Optional in Java 8? How does it prevent NullPointerException?
10. What is [Link]() used for? Give an example.
■ MULTITHREADING — Fresher
1. What is the difference between a process and a thread?
2. What are the different ways to create a thread in Java?
3. What is the difference between Runnable and Callable?
4. What is the thread lifecycle (states) in Java?
5. What is the difference between sleep() and wait()?
6. What is synchronization and why is it needed?
7. What is a race condition? Give a simple example.
8. What is a deadlock? How can you prevent it?
9. What is a daemon thread? How do you create one?
10. What is the volatile keyword and when should you use it?
■ SPRING BOOT — Fresher
1. What is Spring Boot and how is it different from the Spring Framework?
2. What is Inversion of Control (IoC)?
3. What is Dependency Injection and what are its types?
4. What is a Spring Bean?
5. What is the default scope of a Spring Bean?
6. What is the difference between @Component, @Service, @Repository, and @Controller?
7. What does @SpringBootApplication do internally?
8. What is @Autowired? How does Spring inject dependencies?
9. What is the difference between @RequestMapping and @GetMapping?
10. What is the difference between @RequestParam and @PathVariable?
11. What is @RequestBody and when is it used?
12. What is the difference between @Controller and @RestController?
13. What HTTP status codes should you use for GET, POST, PUT, DELETE responses?
14. What is the difference between PUT and PATCH?
■ DATABASE / SQL — Fresher
1. What is the difference between DDL and DML?
2. What is the difference between DELETE and TRUNCATE?
3. What is the difference between WHERE and HAVING?
4. What is an INNER JOIN vs a LEFT JOIN?
5. What are ACID properties?
6. What is a primary key vs a foreign key?
7. What is normalization? Why is it important?
8. What is an index in a database and why is it used?
9. What is the correct order of SQL clause execution?
10. What is the difference between UNION and UNION ALL?
■ FRONTEND BASICS — Fresher
1. What is the difference between HTTP GET and POST?
2. What is JSON and how do you parse it in JavaScript?
3. What is CORS? Why does it occur and how do you fix it?
4. What is the difference between synchronous and asynchronous API calls?
5. How do you make an HTTP request using fetch() in JavaScript?
6. What is the difference between localStorage and sessionStorage?
7. What is a Promise in JavaScript?
SECTION 2 — 1–2 YEARS EXPERIENCE
■ CORE JAVA — OOP Deep Dive
1. Explain the SOLID principles with a real Spring Boot example for each.
2. What is the difference between composition and inheritance? Which is preferred?
3. What is covariant return type in method overriding?
4. What is the difference between shallow copy and deep copy?
5. How do you implement deep cloning without serialization?
6. What is an immutable class? List all conditions to make one properly.
7. How do you protect an immutable class from being broken via reflection?
8. How do you protect an immutable class whose fields include mutable objects like List?
9. What is the difference between String interning and String pooling?
10. What is the Liskov Substitution Principle? Show a violation example.
11. What is the Open/Closed Principle? Show how interfaces help achieve it.
12. What is the difference between abstract class and interface in Java 8+?
13. Can an interface have a constructor? Why or why not?
14. What is double-checked locking in Singleton? Write thread-safe Singleton code.
15. What are the problems with Singleton pattern in multithreaded environments?
■ CORE JAVA — JVM & Memory
1. Explain the JVM runtime data areas in detail (Heap, Stack, Metaspace, Code Cache).
2. What is the difference between Young Generation, Old Generation, and Metaspace?
3. What are the thread-specific runtime areas in JVM?
4. What is the difference between Minor GC and Full GC?
5. What causes a Full GC in production? How do you investigate it?
6. What is Metaspace? How is it different from PermGen?
7. What is the Java Memory Model (JMM)?
8. What is happens-before relationship in JMM? Give two examples.
9. What JVM flags would you use to tune heap size and GC behavior?
10. What is an OutOfMemoryError? List three causes with examples.
11. What is a StackOverflowError and what causes it?
12. What is JIT compilation? How does it improve performance?
13. What is the difference between -Xms and -Xmx?
■ COLLECTIONS — Internals
1. Explain the internal working of HashMap in detail (hashing, index generation, bucket array).
2. What is hashCode() and equals() contract? Why must they be consistent?
3. What happens when two keys have the same hashCode in HashMap?
4. When does a HashMap bucket convert from linked list to red-black tree?
5. What is the role of immutable keys in HashMap? Why are Strings preferred?
6. What is the difference between HashMap and ConcurrentHashMap?
7. How does ConcurrentHashMap achieve thread safety without locking the entire map?
8. What is segmentation in ConcurrentHashMap (Java 7 vs Java 8 approach)?
9. Why was Hashtable deprecated in favor of ConcurrentHashMap?
10. What is CopyOnWriteArrayList and when should you use it?
11. What is the difference between Vector and ArrayList?
12. What is a WeakHashMap? When would you use it?
13. What is the difference between WeakReference, SoftReference, and StrongReference?
14. What is the internal structure of TreeMap?
15. What is the difference between TreeMap and HashMap for iteration order?
16. What is the difference between synchronized collections and concurrent collections?
17. When should you use [Link]() vs CopyOnWriteArrayList?
18. How does ArrayList resize internally? What is the cost of resizing?
19. How do you implement a custom Comparator for descending salary sort on Employee?
20. What is a NavigableMap? Name two implementations.
■ JAVA 8+ — Streams & Lambdas
1. How does the Stream pipeline work internally?
2. What is lazy evaluation in Streams and why does it matter for performance?
3. What is the difference between [Link]() and [Link]()?
4. What is the difference between findFirst() and findAny() in parallel streams?
5. When should you use parallelStream()? What are its pitfalls in a web app?
6. What is a Spliterator? How is it different from an Iterator?
7. How does parallel stream split data using Spliterator?
8. What is the difference between [Link]() and [Link]()?
9. How do you group a list of employees by department using Streams?
10. How do you find the employee with the highest salary using Streams?
11. How do you remove duplicates from a list using Streams?
12. What is the difference between peek() and map() in a Stream?
13. What is [Link]() vs [Link]()? Which is more efficient?
14. How do you chain multiple Optionals safely?
15. What is a CompletableFuture? How is it different from Future?
16. How do you combine two CompletableFutures using thenCombine()?
17. What is the difference between thenApply(), thenAccept(), and thenRun()?
18. How do you handle exceptions in CompletableFuture?
19. What is a default method diamond problem in Java 8? How is it resolved?
20. Can a functional interface extend another functional interface? What are the rules?
■ MULTITHREADING — Intermediate
1. What is the difference between synchronized method and synchronized block? Which is better?
2. What is the difference between synchronized instance method and synchronized static method?
3. What object is used as the lock in a synchronized instance method?
4. What is the difference between synchronized(this) and synchronized([Link])?
5. What is a reentrant lock? Why is ReentrantLock preferred over synchronized in some cases?
6. What is the fairness policy in ReentrantLock?
7. What is the difference between ReentrantLock and ReentrantReadWriteLock?
8. What is a Condition variable? How is it used with ReentrantLock?
9. What is the difference between wait() and sleep() in terms of lock behavior?
10. What happens to the lock when a thread calls wait()?
11. Why are wait(), notify(), notifyAll() defined in Object class, not Thread class?
12. What is the difference between notify() and notifyAll()?
13. What is ThreadLocal? Give a real-world backend use case.
14. What is ExecutorService? What are the different types of thread pools?
15. What is the difference between [Link]() and newCachedThreadPool()?
16. What is [Link]() and what happens if the task throws an exception?
17. What is the difference between submit() and execute() in ExecutorService?
18. How do you ensure two threads T1 and T2 run in sequence?
19. What is CountDownLatch? Give a real use case.
20. What is CyclicBarrier? How is it different from CountDownLatch?
■ SPRING BOOT — Core & Auto-Configuration
1. What is the difference between Spring Singleton bean and GoF Singleton pattern?
2. Is a Spring Singleton bean thread-safe by default? Why?
3. What is the full lifecycle of a Spring Bean (from instantiation to destruction)?
4. What is the difference between @PostConstruct and InitializingBean?
5. What is @Configuration and @Bean? When do you use them over component scanning?
6. What does @EnableAutoConfiguration do internally?
7. How does Spring Boot auto-configuration use [Link] / [Link]?
8. What is @ComponentScan? What is the default package it scans if no package is specified?
9. What is the difference between @Autowired on field, constructor, and setter? Which is recommended?
10. What is the difference between @Primary and @Qualifier?
11. What is the difference between @Autowired and @Inject?
12. What is @Value and how do you inject properties from [Link]?
13. What is @ConfigurationProperties? How is it different from @Value?
14. What is [Link] vs [Link]? Which supports profiles better?
15. How do you implement Spring profiles (dev, prod, test)?
16. What is the difference between @SpringBootTest and @WebMvcTest?
17. What is Spring Actuator and which endpoints are most useful in production?
■ SPRING BOOT — REST API Design
1. What are the best practices for REST API URL naming?
2. What is the difference between @ResponseBody and ResponseEntity?
3. Which HTTP methods are idempotent and which are safe?
4. What is the difference between PUT and PATCH with an example?
5. How do you implement global exception handling using @ControllerAdvice?
6. What is the difference between @ControllerAdvice and @RestControllerAdvice?
7. How do you handle MethodArgumentNotValidException for validation errors?
8. How do you validate request body using @Valid and @Validated?
9. What is the difference between @Valid and @Validated?
10. How do you validate path variables and query parameters in Spring?
11. How do you implement cross-field validation (e.g., password match)?
12. How do you configure CORS in a Spring Boot REST API?
13. What is the Richardson Maturity Model?
14. How does DispatcherServlet work in the Spring MVC lifecycle?
15. What is the order of execution: HandlerInterceptor preHandle, postHandle, afterCompletion?
16. How do you implement file upload in a Spring Boot REST endpoint?
17. What is content negotiation in Spring Boot?
18. How does Spring Boot auto-configure Jackson for JSON serialization?
19. How do you implement API versioning in Spring Boot (URI, header, param)?
■ JPA / HIBERNATE — Core
1. What is the difference between JPA, Hibernate, and Spring Data JPA?
2. What is the role of EntityManager in JPA?
3. What is the JPA persistence context?
4. What are the entity states in JPA (Transient, Managed, Detached, Removed)?
5. What is [Link] vs [Link]? Which is the default?
6. What is the N+1 query problem? How do you reproduce and fix it?
7. What is the difference between @OneToMany and @ManyToOne?
8. How do you map a bidirectional relationship in JPA?
9. How do you avoid infinite recursion in JSON when using bidirectional JPA relationships?
10. What is the difference between @JoinColumn and mappedBy?
11. What are the GenerationType strategies (AUTO, IDENTITY, SEQUENCE, TABLE)?
12. When would you use SEQUENCE over IDENTITY for ID generation?
13. What is the difference between JpaRepository and CrudRepository?
14. How do you write a custom query using @Query in Spring Data JPA?
15. What additional annotation is needed to modify data using @Query?
16. What is @Transactional? What is its default propagation and isolation level?
17. What is optimistic locking in JPA? How do you implement it with @Version?
18. What is pessimistic locking? When would you use it?
19. How do you implement pagination and sorting in Spring Data JPA?
20. How do you implement auditing (@CreatedDate, @LastModifiedDate) in Spring Data JPA?
■ DATABASE / SQL — Intermediate
1. Write a query to find the second highest salary from an Employee table.
2. Write a query to find the top 3 highest-paid employees per department.
3. Write a query to find employees earning more than the average salary of their department.
4. Write a query to find employees who have the same salary as someone in another department.
5. What is a self join? Give a real use case (e.g., manager-employee hierarchy).
6. What is the difference between a subquery and a JOIN? When to use each?
7. What is a CTE (Common Table Expression)? How is it different from a subquery?
8. What is a window function? Give an example using RANK() or ROW_NUMBER().
9. What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?
10. What is the difference between a clustered and non-clustered index?
11. When does an index hurt performance instead of helping?
12. What is a composite index? What is the column order rule?
13. What is a covering index?
14. How do you implement pagination in SQL (LIMIT/OFFSET vs keyset pagination)?
15. What is a View? What are the advantages over writing raw queries?
16. What is the difference between a View and a Materialized View?
17. What are transaction isolation levels? What anomalies does each prevent?
18. What is a deadlock in a database and how do you prevent it?
■ FRONTEND — Intermediate (API Integration Focus)
1. How do you handle API errors gracefully in a fetch() call?
2. What is the difference between axios and fetch? When would you use axios?
3. What is a preflight request in CORS and why does it happen?
4. How do you send a JWT token in an API request from the frontend?
5. What is debouncing and throttling? Where are they used in API calls?
6. How do you handle loading and error states when calling a REST API?
7. What is the difference between async/await and .then() promise chaining?
8. How do you cancel an in-flight API request in JavaScript?
SECTION 3 — 2–3 YEARS EXPERIENCE
■ ADVANCED JAVA & JVM
1. How do you analyze and resolve frequent Full GC in production using GC logs?
2. What JVM flags would you set for a high-throughput REST API service?
3. What is Java Flight Recorder (JFR) and how do you use it for performance analysis?
4. What is the difference between G1GC, ZGC, and Shenandoah GC?
5. How does JIT compilation affect performance in long-running JVM services?
6. How do you detect a memory leak in a Java production service?
7. Can you mark an array volatile in Java? What are the limitations?
8. What is the difference between Externalizable and Serializable?
9. What is the significance of serialVersionUID?
10. What is the difference between a + b and a += b for integer overflow in Java?
11. Why does 5 * 0.1 == 0.5 return false in Java?
■ ADVANCED MULTITHREADING
1. How does JVM implement synchronization (monitor enter/exit, biased locking)?
2. What is the impact of synchronized on performance compared to ReentrantLock?
3. What is a Semaphore in Java? How is it different from a lock?
4. What is a ReadWriteLock? When does it outperform a synchronized block?
5. What is a StampedLock? How does it improve over ReadWriteLock?
6. What is a livelock? How is it different from a deadlock?
7. What is thread starvation? How do you prevent it using fairness?
8. How do you implement a producer-consumer pattern using BlockingQueue?
9. What is a ForkJoinPool? How does work-stealing work?
10. What is the difference between [Link]() and a custom ThreadPoolExecutor?
11. What are the parameters of ThreadPoolExecutor and how do you tune them?
12. What is a CompletionService? How is it different from CompletableFuture?
13. How do you handle thread interruption correctly?
14. What is thread confinement? Give a ThreadLocal example in a Spring request context.
15. How do you implement a timeout on a task using ExecutorService?
■ ADVANCED SPRING BOOT & SECURITY
1. How does Spring Security's filter chain work?
2. How do you implement JWT authentication in Spring Boot?
3. What is the structure of a JWT token (header, payload, signature)?
4. How do you validate a JWT token in a Spring Security filter?
5. What is the difference between authentication and authorization in Spring Security?
6. How do you implement role-based access control (RBAC) in Spring Boot?
7. How do you implement rate limiting in a Spring Boot REST API?
8. How do you implement caching using @Cacheable, @CachePut, and @CacheEvict?
9. What is a cache stampede and how do you prevent it?
10. How do you set cache expiration using Spring Cache with Redis?
11. How do you implement multi-level caching (in-memory + Redis)?
12. What is conditional caching using 'unless' and 'condition' in @Cacheable?
13. How do you implement ETags for HTTP caching in a Spring Boot API?
14. How do you handle asynchronous requests using DeferredResult or Callable?
15. How do you implement DispatcherServlet async processing for long-running tasks?
16. What is WebClient and how is it different from RestTemplate?
17. How do you implement retry logic in a Spring Boot service call?
18. How do you implement circuit breaker using Resilience4j in Spring Boot?
■ ADVANCED JPA / DATABASE
1. How do you integrate Spring Data JPA with multiple data sources?
2. What is multi-tenancy in Spring Boot? Explain the three strategies.
3. How do you optimize slow queries in a Spring Data JPA application?
4. How do you implement Entity Graphs to avoid N+1 queries?
5. How do you implement batch inserts efficiently in JPA?
6. What is the difference between @NamedQuery and @NamedNativeQuery?
7. How do you define and use projections in Spring Data JPA?
8. How do you implement cascade operations in JPA? What are the CascadeType options?
9. How do you define a composite key in JPA using @EmbeddedId?
10. What is table partitioning? What are the types (Range, List, Hash)?
11. What is the difference between horizontal and vertical partitioning?
12. What is a surrogate key vs a natural key? Which is preferred and why?
13. Can a table exist without a primary key? What are the implications?
14. How do you define an index on a JPA entity?
15. What is the impact of adding too many indexes on INSERT/UPDATE performance?
■ MICROSERVICES — Architecture & Patterns
1. What is the difference between a monolith and microservices architecture?
2. What are the main challenges of moving from monolith to microservices?
3. How do microservices communicate synchronously and asynchronously?
4. What is Event-Driven Architecture (EDA)? When should you use it?
5. What is the difference between an event, a command, and a query in EDA?
6. What is Event Sourcing? How is it different from traditional CRUD?
7. What is CQRS? What are its benefits and drawbacks?
8. How do you keep the read model in sync with the write model in CQRS?
9. What is the Saga pattern? When should you use orchestration vs choreography?
10. How do you implement compensating transactions in a Saga?
11. How do you handle retries and idempotency in Saga steps?
12. What is the difference between fault tolerance and resilience?
13. What are the states of a circuit breaker (Closed, Open, Half-Open)?
14. What is the Bulkhead pattern? How does it prevent cascade failures?
15. What is the difference between client-side and server-side load balancing?
16. What is service discovery? How do you implement it with Eureka in Spring Boot?
17. What is distributed tracing? What is the role of traceId and spanId?
18. How do you propagate trace context across microservices?
19. What is the 12-Factor App methodology?
20. What is the CAP theorem? How does it affect distributed system design?
21. How do you implement auto-scaling in Kubernetes (HPA, VPA, CA)?
22. How does Kubernetes Service load balancing differ from API Gateway load balancing?
23. What is the difference between Layer 4 and Layer 7 load balancing?
24. How do you implement a Feign client in Spring Boot with fallback handling?
SECTION 4 — REAL-WORLD SCENARIO QUESTIONS (40+)
■ Performance & Scalability Scenarios
1. Your REST API response time spikes to 10s every few minutes. GC logs show frequent Full GCs. What is your
step-by-step investigation and resolution plan?
2. Your Spring Boot service handles 1000 concurrent requests but starts dropping some. How do you identify the
bottleneck and fix it?
3. A HashMap-based cache in a singleton Spring bean is causing memory leaks in production. What is the likely
cause and how do you fix it?
4. Your service uses parallelStream() for processing orders and intermittently produces wrong results. Why? How
do you fix it?
5. A database query is taking 8 seconds in production but runs in 200ms locally. What do you investigate?
6. Your Spring Boot microservice is CPU-bound under load. How do you profile it and what optimizations would you
consider?
7. A scheduled job reads 1 million records from DB and processes them. After a few hours it throws
OutOfMemoryError. How do you fix this?
■ Concurrency & Thread-Safety Scenarios
1. Two threads update the same account balance simultaneously and some updates are lost. What is this problem
called and how do you fix it in Spring Boot?
2. You have a singleton Spring bean with a counter field. Multiple requests hit it and the count is wrong. How do
you make it thread-safe without blocking all requests?
3. A microservice uses ThreadLocal to store a user session. Requests run in a thread pool. After some requests,
wrong users see wrong session data. What is the bug?
4. Your ExecutorService thread pool is exhausted and requests are queuing forever. How do you diagnose and
tune the pool?
5. A deadlock occurs between two service methods that lock two DB rows in different orders. How do you detect
and fix this?
6. A cached object in a Spring service is being updated by one thread while another reads it. How do you prevent a
stale read without blocking?
7. You need to process 500 external API calls in parallel and collect all results. How do you implement this
efficiently in Java?
■ API Design & Security Scenarios
1. How do you restrict an API endpoint so only users with a specific role can access it in Spring Boot?
2. A client keeps calling your payment API multiple times due to network retries, causing duplicate transactions.
How do you prevent this?
3. How do you design an API that allows users to download a 500MB file without loading it fully into memory?
4. A third-party developer is calling your API 10,000 times per minute and degrading service for other users. How
do you handle this?
5. How do you expose different versions of an API endpoint without breaking existing clients?
6. Your API returns a 200 OK even when a required field is missing in the request body. How do you add proper
validation and return 400 Bad Request?
7. How do you implement CORS to allow only your production frontend domain, not all origins?
■ Database & JPA Scenarios
1. A JPA entity with a @OneToMany list is loaded, causing 100+ SQL queries instead of 1. How do you identify and
fix this N+1 problem?
2. Two users simultaneously update the same product stock. One update gets silently overwritten. What JPA
feature prevents this and how do you implement it?
3. A service method is annotated @Transactional but changes are not being rolled back on exception. What are
three possible causes?
4. A JOIN query on a 10-million-row table takes 30 seconds. What do you investigate and how do you optimize it?
5. Your application must connect to two different databases simultaneously. How do you configure multiple
datasources in Spring Boot JPA?
6. A lazy-loaded collection throws LazyInitializationException after the transaction closes. What are the solutions
and which is preferred?
7. You need to insert 100,000 records into a DB efficiently from a batch job. How do you do this with Spring Data
JPA?
■ Microservices & Distributed System Scenarios
1. A payment microservice calls inventory and notification services. If inventory fails, how do you rollback the
payment using the Saga pattern?
2. Service A calls Service B, which calls Service C. A timeout in C causes all threads in A and B to be exhausted.
What pattern solves this?
3. How do you handle a partial failure where 3 out of 5 microservices succeed in a distributed transaction?
4. Two microservices need to share user data. Should you share the database? What is the recommended
approach?
5. Your event-driven service publishes an event but the consumer fails and the event is lost. How do you ensure
at-least-once delivery?
6. A consumer processes the same event twice due to a retry. How do you ensure idempotency in your event
handler?
7. How do you debug a slow request that crosses 5 microservices without a centralized log?
8. Your Kubernetes pod keeps restarting due to OOM. How do you configure memory limits and tune the JVM
correctly?
9. Two microservices need the same data but update it independently. How do you keep them eventually
consistent?
10. Your circuit breaker is opening too aggressively on transient errors. How do you tune it to distinguish transient
from permanent failures?
11. A new deployment of a microservice breaks an existing consumer because the event schema changed. How
do you handle schema evolution?
12. How do you implement zero-downtime deployment for a Spring Boot microservice in Kubernetes?
SECTION 5 — TOP 30 MUST-REVISE QUESTIONS
1. Explain the internal working of HashMap including hashing, bucket array, collision handling, and treeification
threshold.
2. What is the N+1 query problem in JPA? How do you detect it and what are all the ways to fix it?
3. What is the difference between @Transactional propagation REQUIRED, REQUIRES_NEW, and NESTED?
4. What is the difference between optimistic and pessimistic locking? When would you use each in a
high-concurrency service?
5. What is the happens-before relationship in the Java Memory Model?
6. What is a ReentrantLock? When and why would you use it instead of synchronized?
7. What are the differences between ConcurrentHashMap and [Link]()?
8. What is CompletableFuture? How do you handle exceptions in an async pipeline?
9. What is the full lifecycle of a Spring Bean from construction to destruction?
10. How does Spring Boot auto-configuration work internally?
11. What is the difference between @Valid and @Validated in Spring Boot?
12. How do you implement global exception handling in Spring Boot?
13. What is JWT? Describe its structure and the full authentication flow in Spring Security.
14. What is a circuit breaker pattern? Describe its three states and transitions.
15. What is the Saga pattern and when would you use orchestration vs choreography?
16. What is CQRS and what problems does it solve?
17. What is Event Sourcing? What are its pros and cons over traditional CRUD?
18. What is the difference between [Link] and EAGER and which is safer in REST APIs?
19. How do you prevent duplicate API requests (idempotency) at the service layer?
20. What is the difference between parallelStream() and a custom ForkJoinPool? Which is safer in web apps?
21. What are all the conditions required to make a class truly immutable in Java?
22. What is double-checked locking in Singleton and how do you implement it correctly?
23. How does the JVM allocate memory for threads (thread stack vs heap)?
24. What is Metaspace and what causes a Metaspace OutOfMemoryError?
25. How do you implement pagination efficiently for a table with millions of records?
26. What is a composite index and what is the rule for column ordering?
27. What is the difference between RANK() and ROW_NUMBER() in SQL?
28. How do you implement distributed tracing across microservices in Spring Boot?
29. What are the CAP theorem trade-offs and how do they apply to your service design?
30. How does @Cacheable work internally in Spring (CacheInterceptor, CacheManager, CacheResolver)?
SECTION 6 — TOP 20 CRITICAL SCENARIO QUESTIONS
1. You deployed a new version and response time increased 5x. There are no errors. What is your systematic
debugging approach?
2. An API works fine in testing but throws ConcurrentModificationException randomly in production. What causes
this and how do you fix it?
3. A Spring Boot service processes payments and intermittently double-charges customers. What are the possible
causes and how do you prevent this?
4. Your @Cacheable method is called every time despite a cache hit supposedly existing. What are the three most
common reasons this happens?
5. A service has a thread pool of 10 threads. Under load, requests queue up and timeout. How do you size the pool
correctly?
6. Your JPA application throws LazyInitializationException in production but not in tests. What are the causes and
the best fix?
7. You need to call 50 external APIs and aggregate results for a single user request within 2 seconds. How do you
architect this?
8. Two microservices update shared state. After a network partition, they are out of sync. How do you design for
eventual consistency?
9. Your service consumes Kafka messages, processes them, and saves to DB. Messages are being processed
twice after a crash. How do you fix this?
10. A batch job reads data from DB, transforms it, and writes to another DB. It runs fine for small datasets but
throws OOM for 1M+ records. What do you change?
11. Your Redis cache is down. How does your Spring Boot application behave and how do you configure graceful
degradation?
12. A user reports their session data belongs to another user in your multi-tenant SaaS app. What is the likely bug?
13. You need to add a column to a 500-million-row production table with zero downtime. What is your strategy?
14. Your microservice receives 10x normal traffic due to a viral event. It starts rejecting requests. What auto-scaling
and protection mechanisms should be in place?
15. A scheduled @Async method in a Spring Boot app is running multiple instances simultaneously on a cluster.
How do you ensure it runs only once across nodes?
16. Your service calls a downstream REST API that occasionally takes 30 seconds. Your own response time SLA
is 2 seconds. How do you handle this?
17. A refactoring accidentally removed @Transactional from a service method. How do you detect this in code
review and testing?
18. Two developers merged PRs that change the same Liquibase migration file. What happens when the app starts
and how do you prevent this?
19. Your Kubernetes pod runs a Spring Boot app. It starts but health checks fail and traffic never reaches it. What is
your debugging checklist?
20. A DB index exists on a column but the query planner is not using it. What are the reasons and how do you force
or fix index usage?
SECTION 7 — TOP 15 TRICKY QUESTIONS (Commonly Failed)
1. What is the output when a finally block has a return statement that conflicts with a return in the try block?
2. You call [Link]() with a mutable object as key and then mutate the object. What happens when you call
get() with the same reference?
3. String s1 = "Java"; String s2 = new String("Java"); String s3 = [Link](); — which == comparisons return true?
4. Can a constructor throw an exception? If so, does the object get created in the heap?
5. If a Spring @Transactional method calls another @Transactional method in the same class, does the inner
transaction start a new transaction?
6. You annotate a private method with @Transactional. Does it work? Why or why not?
7. A Spring singleton bean has an instance variable that is modified per-request. Is this thread-safe?
8. HashMap has loadFactor 0.75 and initial capacity 16. After how many entries does it resize?
9. What is the output: List list = new ArrayList<>(); [Link](1); [Link](2); for(Integer i : list) { if(i == 1) [Link](i);
}
10. You use [Link]() without isPresent() — what is the risk? What is the correct alternative?
11. What is the difference between [Link]() returning null meaning the key is absent vs the key maps to a
null value?
12. Can you make a static field volatile in Java? What does that achieve?
13. You call notify() but no thread is waiting. What happens? Is the notification lost?
14. Does adding @Async to a method in a Spring bean guarantee it runs in a separate thread if the caller is in the
same class?
15. You use parallelStream().forEach() to write to a non-thread-safe list. What happens and what is the correct fix?
Java Backend Interview Question Bank · Optimized for India Market (Fresher – 3 Years) · 300+ Questions · Zero Duplicates
Topics: Core Java · Java 8+ · Collections · Multithreading · Spring Boot · REST · JPA/Hibernate · SQL · Microservices · Frontend Basics