0% found this document useful (0 votes)
10 views20 pages

Java Interview Question Bank Enhanced

The document is a comprehensive interview question bank for Java Backend Developers, featuring over 380 curated questions tailored for candidates with 0 to 3 years of experience in the Indian market. It covers various essential topics including Core Java, JVM Internals, Collections, Multithreading, Java 8+, and Spring Boot, with questions categorized by priority levels. New additions in this edition address gaps in specific areas such as Spring AOP and advanced debugging scenarios.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views20 pages

Java Interview Question Bank Enhanced

The document is a comprehensive interview question bank for Java Backend Developers, featuring over 380 curated questions tailored for candidates with 0 to 3 years of experience in the Indian market. It covers various essential topics including Core Java, JVM Internals, Collections, Multithreading, Java 8+, and Spring Boot, with questions categorized by priority levels. New additions in this edition address gaps in specific areas such as Spring AOP and advanced debugging scenarios.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA BACKEND DEVELOPER

INTERVIEW QUESTION BANK


Enhanced Edition | 380+ Curated Questions | Zero Duplicates
Fresher to 3 Years Experience | India Market
Service Companies and Mid-Level Product Companies

Core Java | JVM Internals | Collections | Multithreading | Java 8+


Spring Boot | Spring Testing | REST API | JPA/Hibernate | SQL
Microservices | Debugging and Production Scenarios

■ Must-Know ■ Medium Priority ❄ Lower Priority [NEW] Added in this edition

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 1
HOW TO USE THIS QUESTION BANK

■ Must-Know Asked in 80%+ real interviews. Master these before any technical round.

■ Medium Frequently asked for 1-3 year experience roles. Strong differentiators.

❄ Lower Niche or advanced. Useful for senior-leaning or product company roles.

[NEW] Newly added question not present in the original question bank.

This bank spans 12 topic sections with 380+ non-duplicate, interview-tested questions. All questions have been
filtered for real-world relevance. New questions added in this edition fill identified gaps in Spring AOP/Proxy
internals, @Transactional deep behavior, Spring Boot Testing (a complete new section), SQL execution plans, and
advanced debugging scenarios.

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 2
SECTION 1 — CORE JAVA

OOP Fundamentals
1. ■ What are the four pillars of OOP? Give one real-world backend example for each.
2. ■ What is the difference between method overloading and method overriding? Can you override a static
method?
3. ■ What is the difference between an abstract class and an interface in Java 8+? When do you choose one
over the other?
4. ■ What is runtime polymorphism? Give a Spring backend example where it is actually used.
5. ■ What is encapsulation and why is it critical in a REST service?
6. ■ What is the difference between 'is-a' and 'has-a' relationships? Which leads to tighter coupling?
7. ■ What is constructor chaining? Show how this() and super() behave with a concrete example.
8. ■ What is the 'final' keyword? What are all the contexts it can be applied in and what does each mean?
9. ■ What is the difference between == and .equals() for Strings? Why does == sometimes return true for
String literals?
10. ■ What is pass-by-value in Java? Prove using an object mutation example that Java never passes by
reference.
11. ■ Explain the SOLID principles. Give a Spring Boot example for each.
12. ■ What is the difference between composition and inheritance? Why is composition generally preferred?
13. ■ What is the Liskov Substitution Principle? Give a clear violation example.
14. ■ What is an immutable class? List every condition required to make one correctly, including mutable
field protection.
15. ■ What is double-checked locking in Singleton? Write a correct thread-safe Singleton using volatile.
16. ■ What is the difference between shallow copy and deep copy? How do you implement deep cloning?
17. ■ What is autoboxing/unboxing? Where can it cause a NullPointerException or performance issue?
18. ■ What is covariant return type in method overriding? Give a practical example.
19. ❄ How do you protect an immutable class from being broken via reflection?

Strings
1. ■ Why is String immutable in Java? What are the security and performance benefits?
2. ■ What is the String pool? When is a String added to the pool vs allocated on the heap?
3. ■ What is the difference between String, StringBuilder, and StringBuffer? When do you use each?
4. ■ How many objects are created: String s = new String("hello");? Explain each object created.
5. ■ What is the output: String s = "Hello"; [Link](" World"); [Link](s); — and why?
6. ■ Why should you use StringBuilder instead of + concatenation inside a loop?
7. ■ How many objects: String s1 = "hello"; String s2 = "hello"; — and which == comparisons are true?
8. ■ What is [Link]() and when would you use it in a real application?

Exception Handling
1. ■ What is the difference between checked and unchecked exceptions? Give two examples of each.
2. ■ What is the difference between Error and Exception? Should you ever catch an Error?
3. ■ What does a finally block guarantee? Can it ever be skipped?
4. ■ Can a finally block override a return statement in the try block? What is the actual output?
5. ■ What is try-with-resources? Why is it preferred over manual finally-based cleanup?
6. ■ How do you create a meaningful custom exception? Show checked vs unchecked variants.
7. ■ When should you use throws vs wrapping in try-catch? What is exception propagation?
8. ■ What is exception chaining (getCause)? Why is it important for production debugging?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 3
9. ■ [NEW] What are the dangers of catching Exception or Throwable broadly in a Spring service?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 4
SECTION 2 — JVM & MEMORY INTERNALS

JVM Architecture & GC


1. ■ What is the difference between JVM, JDK, and JRE? Which do you ship to production?
2. ■ Explain the JVM runtime data areas: Heap, Stack, Metaspace, Code Cache, PC Register.
3. ■ What is the difference between Young Generation, Old Generation, and Metaspace? What objects live in
each?
4. ■ What is the difference between Minor GC and Full GC? What triggers a Full GC in production?
5. ■ What is Metaspace? How is it different from PermGen? What causes a Metaspace OutOfMemoryError?
6. ■ What is JIT compilation? How does tiered compilation (C1 vs C2) improve performance in long-running
services?
7. ■ What is an OutOfMemoryError? Describe three distinct root causes with examples.
8. ■ What is a StackOverflowError? What causes it and how do you fix it?
9. ■ [NEW] How do you detect a memory leak in a running Java production service? What tools do you use?
10. ■ [NEW] What is the difference between a heap dump and a thread dump? When do you take each?
11. ■ What is the difference between G1GC, ZGC, and Shenandoah GC? Which suits low-latency REST APIs?
12. ■ What JVM flags would you set for a high-throughput Spring Boot REST API? Explain each flag.
13. ❄ What is Java Flight Recorder (JFR)? How do you use it for production performance analysis?

Java Memory Model (JMM)


1. ■ What is the Java Memory Model (JMM)? Why is it important for multithreaded code correctness?
2. ■ What is the happens-before relationship? Give three concrete examples from the JMM specification.
3. ■ What is the volatile keyword? When is it sufficient and when is it not enough?
4. ■ Can you mark an array reference volatile in Java? What limitation does this have on array elements?
5. ❄ Why does 5 * 0.1 == 0.5 return false in Java? How do you handle floating-point comparisons?
6. ❄ What is serialVersionUID and what happens if it is missing or mismatched during deserialization?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 5
SECTION 3 — COLLECTIONS

Core Collections
1. ■ What is the difference between ArrayList and LinkedList? When does LinkedList actually outperform
ArrayList?
2. ■ What is the difference between HashMap and TreeMap in terms of time complexity and iteration order?
3. ■ What is the difference between HashMap and LinkedHashMap? When would you use LinkedHashMap?
4. ■ What is the initial capacity and load factor of HashMap? How do they affect performance and memory?
5. ■ What happens when you add a duplicate key to a HashMap?
6. ■ What is the difference between fail-fast and fail-safe iterators? Give one example of each.
7. ■ What is the difference between Comparable and Comparator? How do you sort Employee objects by
salary?
8. ■ What is the difference between Stack and Deque? Why is Stack discouraged in Java?
9. ■ What is a PriorityQueue? How does it determine ordering and what is its time complexity for operations?
10. ■ What is a WeakHashMap? When and why would you use it?
11. ■ What is the difference between WeakReference, SoftReference, and StrongReference?

HashMap Internals
1. ■ Explain the internal working of HashMap: hashing, index generation, bucket array, collision handling,
treeification.
2. ■ What is the hashCode() and equals() contract? What breaks if you override only one?
3. ■ What happens when two keys have the same hashCode? How is collision resolved in Java 8+?
4. ■ At what threshold does a HashMap bucket convert from a linked list to a red-black tree? Why?
5. ■ Why are String and Integer preferred as HashMap keys? What makes a good map key?
6. ■ HashMap has load factor 0.75 and initial capacity 16. After how many entries does it resize?
7. ■ You put a mutable object as a HashMap key and then mutate it. What happens on the next get() call?
8. ■ How does ArrayList resize internally? What is the growth factor and amortized cost per insertion?
9. ■ What is the difference between HashMap and Hashtable? Why was Hashtable deprecated?

Concurrent Collections
1. ■ What is the difference between HashMap and ConcurrentHashMap?
2. ■ How does ConcurrentHashMap achieve thread safety without locking the entire map in Java 8?
3. ■ What changed in ConcurrentHashMap between Java 7 (segment locking) and Java 8 (CAS +
synchronized buckets)?
4. ■ What is CopyOnWriteArrayList? What is its trade-off and when should you use it?
5. ■ What is the difference between synchronized collections ([Link]) and concurrent
collections?
6. ■ When should you use [Link]() vs CopyOnWriteArrayList? Justify with a scenario.
7. ■ What is a NavigableMap? Name two implementations and a real use case for each.

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 6
SECTION 4 — MULTITHREADING & CONCURRENCY

Thread Basics
1. ■ What is the difference between a process and a thread? What is a context switch?
2. ■ What are the different ways to create a thread in Java? Which approach is preferred and why?
3. ■ What is the difference between Runnable and Callable? How do you retrieve a result from Callable?
4. ■ What is the thread lifecycle in Java? Describe all states and transitions.
5. ■ What is the difference between sleep() and wait() in terms of lock release behavior?
6. ■ What is a race condition? Give a simple bank account example.
7. ■ What is a deadlock? Give an example and explain three prevention strategies.
8. ■ What is volatile and when is it not sufficient to guarantee thread safety?
9. ■ Why are wait(), notify(), and notifyAll() defined in Object class and not in Thread class?
10. ■ What is the difference between notify() and notifyAll()? When can notify() cause a missed signal bug?
11. ■ What is a daemon thread? How do you create one and when is it useful?

Locks & Synchronization


1. ■ What is the difference between a synchronized method and a synchronized block? Which is more
granular?
2. ■ What object is used as the lock in a synchronized instance method vs a synchronized static method?
3. ■ What is a ReentrantLock? Why would you use it instead of synchronized?
4. ■ What is the fairness policy in ReentrantLock? What is the trade-off of enabling fairness?
5. ■ What is ReentrantReadWriteLock? When does it outperform a plain synchronized block?
6. ■ What is a Condition variable? How is it used with ReentrantLock as an alternative to wait/notify?
7. ■ What is a livelock? How is it different from a deadlock? Give an example.
8. ■ [NEW] How does JVM implement synchronization internally? Explain monitor enter/exit and lock
inflation.
9. ■ What is StampedLock? How does optimistic read differ from ReadWriteLock?
10. ■ What is a Semaphore? How is it different from a lock? Give a real rate-limiting use case.
11. ■ What is thread starvation? How do you prevent it using ReentrantLock fairness?

Thread Pools & Executors


1. ■ What is ExecutorService? What are the four standard thread pool types and when do you use each?
2. ■ What are the parameters of ThreadPoolExecutor? How do you size the pool for an IO-bound vs
CPU-bound service?
3. ■ What is the difference between submit() and execute() in ExecutorService?
4. ■ What is [Link]()? What happens if the task throws an exception or times out?
5. ■ What is CountDownLatch? Give a real backend use case (e.g., parallel service calls with a timeout).
6. ■ What is BlockingQueue? How do you implement a producer-consumer pattern using it?
7. ■ What is ThreadLocal? Give a real-world backend use case (e.g., storing request-scoped user context).
8. ■ [NEW] A service uses ThreadLocal to store user session but runs on a thread pool. What bug can occur
and how do you fix it?
9. ■ What is CyclicBarrier? How is it different from CountDownLatch?
10. ■ What is ForkJoinPool? How does work-stealing work?
11. ■ How do you implement a timeout on a task using [Link] or [Link](timeout)?
12. ■ How do you handle thread interruption correctly in a long-running task?
13. ❄ What is a CompletionService? How is it different from using CompletableFuture?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 7
SECTION 5 — JAVA 8+

Lambdas, Functional Interfaces & Method References


1. ■ What is a functional interface? Is the @FunctionalInterface annotation mandatory?
2. ■ What is the difference between Predicate, Function, Consumer, and Supplier? Give an example of each.
3. ■ What is a method reference? Give an example of each of the four types.
4. ■ What is the difference between a default method and a static method in an interface? Why were they
added?
5. ■ What is the default method diamond problem in Java 8? How does the compiler resolve it?
6. ■ Can a functional interface extend another functional interface? What rules apply?

Streams
1. ■ How does a Stream pipeline work internally? What is lazy evaluation and why does it matter for
performance?
2. ■ What is the difference between intermediate and terminal operations? Give three examples of each.
3. ■ What is the difference between map() and flatMap()? Give a real example with a list of lists.
4. ■ How do you group a list of employees by department using Streams? Write the full pipeline.
5. ■ How do you find the employee with the highest salary using Streams?
6. ■ How do you remove duplicates from a list using Streams when the list has custom objects?
7. ■ What is the difference between findFirst() and findAny() in a parallel stream?
8. ■ When should you use parallelStream()? What are its pitfalls in a Spring web application?
9. ■ [NEW] Write a stream pipeline to find the top 3 highest-paid employees per department.
10. ■ What is the difference between peek() and map()? When is peek() useful for debugging?
11. ■ What is a Spliterator? How is it used internally by parallel streams?
12. ■ What is the difference between [Link]() and [Link]()?
13. ■ What is the difference between [Link]() and [Link]()?

Optional & CompletableFuture


1. ■ What is Optional? How does it prevent NullPointerException and what are its limitations?
2. ■ What is the difference between [Link]() and [Link]()? Which is more efficient?
3. ■ What is the risk of [Link]() without isPresent()? What is the correct alternative?
4. ■ What is CompletableFuture? How is it different from Future?
5. ■ What is the difference between thenApply(), thenAccept(), and thenRun()?
6. ■ How do you handle exceptions in a CompletableFuture pipeline using exceptionally() or handle()?
7. ■ How do you combine two CompletableFutures using thenCombine() vs thenCompose()?
8. ■ [NEW] How do you run 50 external API calls in parallel and collect all results within a timeout using
CompletableFuture?
9. ■ How do you chain multiple Optionals safely using map() and flatMap()?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 8
SECTION 6 — SPRING BOOT

IoC, DI & Bean Lifecycle


1. ■ What is Inversion of Control (IoC)? How does Spring's IoC container implement it?
2. ■ What are the three types of Dependency Injection? Which is recommended and why?
3. ■ What is the default scope of a Spring Bean? What are all the available scopes?
4. ■ What is the difference between @Component, @Service, @Repository, and @Controller?
5. ■ Describe the full Spring Bean lifecycle from instantiation to destruction.
6. ■ What is @PostConstruct vs InitializingBean vs init-method? Which is preferred and why?
7. ■ What is @Configuration and @Bean? When do you use them instead of component scanning?
8. ■ What is the difference between @Primary and @Qualifier? When does a conflict occur?
9. ■ What is the difference between a Spring Singleton bean and the GoF Singleton pattern?
10. ■ Is a Spring Singleton bean thread-safe by default? Why not? How do you fix it?
11. ■ [NEW] What is the difference between @Autowired on field, constructor, and setter? Why is constructor
injection recommended?
12. ■ What is @Value? How do you inject a property from [Link]?
13. ■ What is @ConfigurationProperties? How is it different from @Value for bulk property binding?
14. ■ How do you implement Spring profiles? What is the preferred way using YAML?

Auto-Configuration, Proxies & AOP


1. ■ What does @SpringBootApplication do internally? Which three annotations does it combine?
2. ■ How does Spring Boot auto-configuration work? Explain [Link] / [Link].
3. ■ What is @ComponentScan? What is the default package scanned if none is specified?
4. ■ [NEW] What is the difference between JDK dynamic proxy and CGLIB proxy in Spring? When does
Spring use each?
5. ■ [NEW] What is Spring AOP? How does it work internally through proxies?
6. ■ [NEW] What are the five Spring AOP advice types? When do you use Around advice?
7. ■ [NEW] What is a pointcut expression? Write one that intercepts all public methods in the service layer.
8. ■ [NEW] Can Spring AOP intercept a private method or an internal same-class method call? Why not?
9. ■ How can you exclude a specific auto-configuration class in Spring Boot?

@Transactional Deep Dive


1. ■ How does @Transactional work internally in Spring? What role does the proxy play?
2. ■ If a @Transactional method calls another @Transactional method in the same class, does a new
transaction start? Why not?
3. ■ Does @Transactional on a private method work? Why or why not?
4. ■ What is @Transactional propagation? Explain REQUIRED, REQUIRES_NEW, and NESTED with clear
differences.
5. ■ What is @Transactional isolation? Which anomaly does each isolation level prevent?
6. ■ What is the default rollback behavior of @Transactional? How do you trigger rollback for checked
exceptions?
7. ■ [NEW] List three specific reasons why @Transactional might not roll back even when an exception is
thrown.
8. ■ [NEW] What is readOnly=true in @Transactional? What Hibernate optimization does it enable?

REST API Design


1. ■ What is the difference between @Controller and @RestController?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 9
2. ■ What is the difference between @RequestParam and @PathVariable? When do you use each?
3. ■ What HTTP status codes should you return for GET, POST, PUT, DELETE, and validation errors?
4. ■ What is the difference between PUT and PATCH? Which is idempotent?
5. ■ How does DispatcherServlet work in the Spring MVC request lifecycle? Walk through each step.
6. ■ How do you implement global exception handling using @ControllerAdvice?
7. ■ How do you validate a request body using @Valid and @Validated? What is the difference between
them?
8. ■ How do you handle MethodArgumentNotValidException and return a structured 400 error response?
9. ■ How do you configure CORS in Spring Boot to allow only your production frontend domain?
10. ■ How do you implement idempotency for a payment API endpoint?
11. ■ What is the difference between @ResponseBody and ResponseEntity?
12. ■ How do you implement API versioning in Spring Boot (URI, header, parameter approaches)?
13. ■ [NEW] How do you stream a 500MB file download without loading it fully into JVM memory?
14. ■ [NEW] How do you implement rate limiting in a Spring Boot REST API?
15. ❄ What is the Richardson Maturity Model and what are the four levels?
16. ❄ How does Spring Boot auto-configure Jackson? How do you customize date serialization?

Caching & Security


1. ■ How does @Cacheable work internally (CacheInterceptor, CacheManager, CacheResolver)?
2. ■ What is the difference between @Cacheable, @CachePut, and @CacheEvict?
3. ■ [NEW] Your @Cacheable method is being called every time despite a supposed cache hit. List the three
most common causes.
4. ■ How does Spring Security's filter chain work? What is the order of filters?
5. ■ How do you implement JWT authentication in Spring Boot? Describe the complete flow.
6. ■ What is the structure of a JWT token (header, payload, signature)? How is it verified?
7. ■ What is the difference between authentication and authorization in Spring Security?
8. ■ How do you implement role-based access control (RBAC) in Spring Boot?
9. ■ What is conditional caching using 'unless' and 'condition' in @Cacheable?
10. ■ How do you set cache expiration in Spring Cache backed by Redis?
11. ■ [NEW] What is the difference between JWT and session-based authentication? When would you prefer each?
12. ❄ What is a cache stampede and how do you prevent it?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 10
SECTION 7 — SPRING BOOT TESTING
Note: This entire section is new. Testing is consistently asked in 1-3 year experience interviews but was missing from the
original bank.

Testing Strategy & Annotations


1. ■ [NEW] What is the difference between unit tests, integration tests, and end-to-end tests? When should
you write each?
2. ■ [NEW] What is the test pyramid? How does it guide test investment in a Spring Boot project?
3. ■ [NEW] What is the difference between @SpringBootTest, @WebMvcTest, and @DataJpaTest? When do
you use each?
4. ■ [NEW] What does @SpringBootTest load? Why is it slow and when is it justified vs @WebMvcTest?
5. ■ [NEW] What does @WebMvcTest load? How do you test a controller layer in complete isolation from the
service layer?
6. ■ [NEW] What does @DataJpaTest load? How do you test a repository against an in-memory database?
7. ■ [NEW] What is @TestConfiguration? How is it different from @Configuration in tests?
8. ■ [NEW] What is @ActiveProfiles used for in Spring Boot tests?

Mockito
1. ■ [NEW] What is Mockito? What is the difference between @Mock, @Spy, and @InjectMocks?
2. ■ [NEW] What is the difference between when().thenReturn() and doReturn().when()? When do you use
each?
3. ■ [NEW] How do you verify that a method was called with specific arguments using Mockito?
4. ■ [NEW] What is an ArgumentCaptor and when would you use it?
5. ■ [NEW] What is @MockBean vs @Mock? When do you use @MockBean in Spring Boot tests?
6. ■ [NEW] How do you mock a static method in Mockito 3.4+ using MockedStatic?
7. ■ [NEW] What is the difference between [Link]() and AssertJ assertions?

Controller, Service & Integration Testing


1. ■ [NEW] How do you test a Spring MVC controller using MockMvc? Describe a test for a POST endpoint
with validation.
2. ■ [NEW] How do you test a service layer method that calls a repository? What do you mock and what do
you assert?
3. ■ [NEW] How do you test global exception handling (@ControllerAdvice) using MockMvc?
4. ■ [NEW] How do you write an integration test that starts a real server on a random port using
@SpringBootTest?
5. ■ [NEW] How do you test a @Transactional service method to confirm rollback on exception in an integration test?
6. ■ [NEW] How do you test a @Cacheable method to verify the caching behavior?
7. ■ [NEW] What is WireMock and how do you use it to stub external HTTP calls in integration tests?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 11
SECTION 8 — JPA / HIBERNATE

Core Concepts
1. ■ What is the difference between JPA, Hibernate, and Spring Data JPA? What does each layer provide?
2. ■ What is the JPA persistence context? What is its default scope in a Spring Boot application?
3. ■ What are the four entity states in JPA (Transient, Managed, Detached, Removed)? How do you transition
between them?
4. ■ What is dirty checking in Hibernate? How does it work and when does the flush occur?
5. ■ What is [Link] vs [Link]? What is the default for @OneToMany and
@ManyToOne?
6. ■ What is the N+1 query problem? How do you detect it using Hibernate SQL logs and what are all the
ways to fix it?
7. ■ What is the difference between @JoinColumn and mappedBy in a bidirectional relationship?
8. ■ How do you avoid infinite recursion in JSON when using bidirectional JPA relationships?
9. ■ What is optimistic locking in JPA? How do you implement it with @Version?
10. ■ What are the GenerationType strategies? When would you use SEQUENCE over IDENTITY?
11. ■ What is the difference between JpaRepository and CrudRepository?
12. ■ How do you write a custom query using @Query? What additional annotation is needed for modifying
queries?
13. ■ [NEW] What is a LazyInitializationException? What are the three ways to fix it and which is preferred?
14. ■ [NEW] What is an Entity Graph? How do you use @EntityGraph to solve N+1 without over-fetching?
15. ■ What is pessimistic locking? When would you use PESSIMISTIC_WRITE vs PESSIMISTIC_READ?
16. ■ How do you implement pagination and sorting in Spring Data JPA?
17. ■ How do you implement batch inserts efficiently in JPA? What Hibernate properties must you enable?
18. ■ [NEW] How do you implement projections in Spring Data JPA? What is the difference between interface-based
and class-based projections?
19. ❄ How do you define a composite key using @EmbeddedId?
20. ❄ How do you implement auditing (@CreatedDate, @LastModifiedDate) in Spring Data JPA?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 12
SECTION 9 — SQL

Fundamentals & Joins


1. ■ What is the correct order of SQL clause execution (FROM, WHERE, GROUP BY, HAVING, SELECT,
ORDER BY, LIMIT)?
2. ■ What is the difference between WHERE and HAVING? In which cases can you NOT use WHERE?
3. ■ What is the difference between DELETE, TRUNCATE, and DROP?
4. ■ What is INNER JOIN vs LEFT JOIN vs RIGHT JOIN vs FULL OUTER JOIN? When do you need each?
5. ■ What is a self join? Give a concrete use case (manager-employee hierarchy).
6. ■ What is the difference between UNION and UNION ALL? When does UNION ALL perform better?
7. ■ What are ACID properties? Explain each with a bank transfer example.
8. ■ What are transaction isolation levels? What anomaly (dirty read, non-repeatable read, phantom read)
does each level prevent?
9. ■ What is normalization? Explain 1NF, 2NF, 3NF. When is denormalization justified?
10. ■ What is the difference between a View and a Materialized View? When would you use each?

Complex Queries
1. ■ Write a query to find the second highest salary from an Employee table without using LIMIT.
2. ■ Write a query to find the top 3 highest-paid employees per department using window functions.
3. ■ Write a query to find employees earning more than the average salary of their own department.
4. ■ What is a CTE (Common Table Expression)? How is it different from a subquery? Write a real example.
5. ■ What is a window function? Write a query using RANK(), DENSE_RANK(), and ROW_NUMBER() and
explain the difference between them.
6. ■ Write a query to detect duplicate rows in a table and delete all but one copy.
7. ■ Write a query to find employees who have the same salary as someone in a different department.
8. ■ Write a recursive CTE to traverse an employee-manager hierarchy up to the root CEO.
9. ■ Write a query using LEAD() and LAG() to calculate month-over-month revenue growth.
10. ❄ What is a PIVOT query? Write one that converts monthly sales rows into a single row with one column per
month.

Indexing, Optimization & Execution Plans


1. ■ What is an index? How does a B-Tree index work internally?
2. ■ What is the difference between a clustered and a non-clustered index?
3. ■ What is a composite index? What is the left-prefix rule? Give an example where the index is NOT used.
4. ■ What is a covering index? How can it eliminate a table lookup entirely?
5. ■ When does an index hurt performance instead of helping? Give three scenarios.
6. ■ What is the difference between LIMIT/OFFSET pagination and keyset (cursor) pagination? Why is
OFFSET slow on large tables?
7. ■ [NEW] How do you read and interpret a SQL EXPLAIN plan? What do Seq Scan and Index Scan mean?
8. ■ [NEW] A JOIN query on a 10-million-row table takes 30 seconds. Walk through your step-by-step
investigation and optimization.
9. ■ [NEW] What is a database deadlock? How do you detect it from database logs and prevent it by ordering
row locks?
10. ■ What is a partial index? When would you create one?
11. ■ What is table partitioning? Explain Range, List, and Hash partitioning with use cases.
12. ■ What is the difference between horizontal and vertical partitioning?
13. ❄ What is a surrogate key vs a natural key? Which is preferred in a high-write system and why?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 13
14. ❄ Can a table exist without a primary key? What are the production implications (e.g., for replication)?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 14
SECTION 10 — MICROSERVICES

Architecture & Patterns


1. ■ What is the difference between a monolith and a microservices architecture? What are the main
trade-offs?
2. ■ How do microservices communicate? What is the difference between synchronous (REST/gRPC) and
asynchronous (Kafka) communication?
3. ■ What is Event-Driven Architecture? When is it preferable over synchronous REST calls?
4. ■ What is the Saga pattern? When do you choose orchestration vs choreography?
5. ■ How do you implement compensating transactions in a Saga? Give a payment + inventory rollback
example.
6. ■ What is CQRS? What problem does it solve and what complexity does it introduce?
7. ■ What is Event Sourcing? How is it different from traditional CRUD? What are the drawbacks?
8. ■ What is a circuit breaker? Describe the three states (Closed, Open, Half-Open) and their transitions.
9. ■ How do you implement a circuit breaker using Resilience4j in Spring Boot?
10. ■ What is distributed tracing? What is the role of traceId and spanId? How do you propagate context
across services?
11. ■ What is the CAP theorem? How does it affect your design choices for a distributed system?
12. ■ What is the Bulkhead pattern? How does it prevent cascade failures?
13. ■ What is service discovery? How do you implement it with Eureka?
14. ■ How do you implement retry logic with exponential backoff in Spring Boot using Resilience4j?
15. ❄ What is the 12-Factor App methodology? Name five factors most relevant to Spring Boot services.

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 15
SECTION 11 — DEBUGGING & PRODUCTION SCENARIOS
Note: Scenario questions are the highest-signal questions in 1-3 year interviews. Practice structured root-cause analysis:
Observe, Hypothesize, Investigate, Fix.

Performance & Memory


1. ■ Your REST API response time spikes to 10 seconds every few minutes. GC logs show frequent Full GCs.
Describe your step-by-step investigation and resolution.
2. ■ A Spring Boot service starts dropping requests under 1000 concurrent users. How do you identify the
bottleneck (thread pool, DB connection pool, GC, CPU)?
3. ■ A HashMap-based cache in a singleton Spring bean is growing unboundedly in production. What is the
root cause and how do you fix it?
4. ■ A scheduled job reads 1 million records from the DB and throws OutOfMemoryError after a few hours.
How do you fix it using streaming/pagination?
5. ■ A database query takes 8 seconds in production but runs in 200ms locally. List your investigation steps.
6. ■ You deployed a new version and response time increased 5x with no errors in logs. Describe your
systematic debugging approach.
7. ■ A batch job reading from DB and writing to another DB runs fine for small datasets but throws OOM for
1M+ records. What do you change?
8. ■ Your Kubernetes pod keeps restarting due to OOM. How do you configure memory limits and tune the JVM heap
for a containerized Spring Boot app?

Concurrency Issues
1. ■ Two threads update the same account balance simultaneously and some updates are lost. What is this
problem and how do you fix it in Spring Boot (DB locking, synchronized, AtomicLong)?
2. ■ A singleton Spring bean has an instance variable modified per-request. Multiple requests hit it and the
value is wrong. How do you fix it?
3. ■ A microservice uses ThreadLocal for user session in a thread pool. Wrong users see wrong session
data. What is the bug and the fix?
4. ■ Your ExecutorService thread pool is exhausted and requests are queuing forever. How do you diagnose
it and what parameters do you tune?
5. ■ A deadlock occurs between two service methods that lock two DB rows in different orders. How do you
detect it and prevent it?
6. ■ Your service uses parallelStream() for order processing and intermittently produces wrong results. Why
and how do you fix it?
7. ■ An API works fine in testing but throws ConcurrentModificationException randomly in production. What
causes this and how do you fix it?

JPA & Database Issues


1. ■ A JPA entity with @OneToMany is causing 100+ SQL queries instead of 1. How do you identify the N+1
problem and fix it?
2. ■ Two users simultaneously update the same product stock and one update is silently overwritten. What
JPA feature prevents this and how do you implement it?
3. ■ A service method annotated @Transactional is not rolling back on exception. List three possible causes.
4. ■ A lazy-loaded collection throws LazyInitializationException after the transaction closes. What are the
solutions and which is preferred?
5. ■ You need to insert 100,000 records efficiently from a batch job. How do you implement this with Spring
Data JPA and proper batch settings?
6. ■ Your JPA application throws LazyInitializationException in production but not in tests. What causes the difference
in behavior?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 16
7. ■ A refactoring accidentally removed @Transactional from a service method. How do you detect this in code
review and in integration tests?

Distributed Systems
1. ■ A payment microservice calls inventory and notification services. If inventory fails, how do you rollback
payment using the Saga pattern?
2. ■ Service A calls B, which calls C. A timeout in C causes all threads in A and B to be exhausted. What
pattern solves this?
3. ■ A client calls your payment API multiple times due to network retries, causing duplicate charges. How do
you prevent this?
4. ■ Your event-driven service publishes an event but the consumer fails and the event is lost. How do you
ensure at-least-once delivery?
5. ■ A Kafka consumer processes the same event twice due to a retry. How do you ensure idempotency in
the handler?
6. ■ How do you debug a slow request that crosses 5 microservices with no centralized log?
7. ■ Your circuit breaker is opening too aggressively on transient errors. How do you tune it to distinguish transient
from permanent failures?
8. ■ A new deployment breaks an existing Kafka consumer because the event schema changed. How do you handle
schema evolution?
9. ■ Your Redis cache is down. How does your Spring Boot application behave and how do you configure graceful
degradation?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 17
SECTION 12 — TRICKY & COMMONLY FAILED QUESTIONS
Note: These questions have the highest failure rate. They test true understanding vs surface memorization.

1. ■ What is the output when a finally block has a return statement that conflicts with a return in the try
block?
2. ■ You put a mutable object as a HashMap 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
and why?
4. ■ Can a constructor throw an exception? If so, is the object created on the heap?
5. ■ A @Transactional method calls another @Transactional method in the same class. Does the inner
transaction start a new one?
6. ■ You annotate a private method with @Transactional. Does it work? Why or why not?
7. ■ A Spring singleton bean has an instance variable modified per-request. Is this thread-safe?
8. ■ HashMap has load factor 0.75 and initial capacity 16. After exactly 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);} — and why?
10. ■ What is the risk of [Link]() without isPresent()? What is the safe alternative?
11. ■ How do you distinguish [Link]() returning null because the key is absent vs because the key
maps to a null value?
12. ■ Does adding @Async to a method guarantee it runs in a separate thread if the caller is in the same
class?
13. ■ You use parallelStream().forEach() to write to a non-thread-safe ArrayList. What happens and what is
the correct fix?
14. ■ You call notify() but no thread is waiting. What happens? Is the signal lost?
15. ■ [NEW] What happens when you call a @Transactional method on a bean you instantiated directly (new
MyService()) instead of injecting it?
16. ■ [NEW] What exception is thrown to the caller when you call [Link]() and the async task
throws a RuntimeException?
17. ■ Can you make a static field volatile? What does it achieve?
18. ■ [NEW] What happens when two threads call [Link]() concurrently in Java 8+? Can it cause an infinite
loop unlike Java 7?
19. ❄ [NEW] What is the difference between a + b and a += b when a and b are declared as byte in terms of overflow
and casting?

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 18
QUICK REFERENCE — TOP 30 MUST-KNOW QUESTIONS

# Question Topic

1 HashMap internals: hashing, bucket array, collision handling, treeification threshold.

2 N+1 query problem in JPA: how to detect and all ways to fix it.

3 @Transactional propagation: REQUIRED vs REQUIRES_NEW vs NESTED.

4 Optimistic vs pessimistic locking in JPA for high-concurrency scenarios.

5 happens-before relationship in the Java Memory Model with concrete examples.

6 ReentrantLock vs synchronized: when and why to choose ReentrantLock.

7 ConcurrentHashMap vs [Link]() internals and performance.

8 CompletableFuture: building async pipelines and handling exceptions.

9 Full Spring Bean lifecycle from construction to destruction.

10 Spring Boot auto-configuration mechanism: [Link] / [Link].

11 @Transactional on same-class method call: why the proxy is bypassed.

12 JDK dynamic proxy vs CGLIB proxy: when Spring uses each.

13 Global exception handling with @ControllerAdvice and structured error responses.

14 JWT structure and full Spring Security authentication flow.

15 Circuit breaker pattern: Closed/Open/Half-Open states and transitions.

16 Saga pattern: orchestration vs choreography with compensating transactions.

17 CQRS and Event Sourcing: benefits, drawbacks, and when to use them.

18 [Link] vs EAGER: which is safer in REST APIs and why.

19 Idempotency for payment APIs: implementation strategies.

20 parallelStream() pitfalls in a web application context.

21 All conditions required to make a class truly immutable in Java.

22 Double-checked locking in Singleton with volatile: write the correct code.

23 JVM thread stack vs heap: what data lives in each.

24 Metaspace OutOfMemoryError: causes and prevention strategies.

25 Keyset pagination vs LIMIT/OFFSET for tables with millions of rows.

26 Composite index left-prefix rule: when is the index actually used.

27 RANK() vs ROW_NUMBER() vs DENSE_RANK() in SQL with examples.

28 Distributed tracing: traceId/spanId propagation across microservices.

29 CAP theorem trade-offs applied to real distributed system design.

30 @Cacheable internals: CacheInterceptor, CacheManager, CacheResolver.

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 19
JAVA BACKEND DEVELOPER
INTERVIEW QUESTION BANK
Enhanced Edition | 380+ Questions | India Market

■ Must-Know | ■ Medium | ❄ Lower Priority | [NEW] Added in this edition

12 Sections: Core Java | JVM Internals | Collections | Multithreading | Java 8+ | Spring Boot |
Spring Testing | REST API | JPA/Hibernate | SQL | Microservices | Debugging

Java Backend Developer Interview Question Bank | Fresher to 3 Years | India Market Page 20

You might also like