0% found this document useful (0 votes)
3 views16 pages

Java Interview Bank Clean

This document is a comprehensive question bank for Java backend developer interviews, categorized by experience levels from 0 to 3 years, covering essential topics like Core Java, Spring Framework, SQL, and multithreading. It includes over 370 questions organized into sections based on years of experience and priority tiers, providing a structured approach for candidates to prepare for interviews in the Indian market. The document also emphasizes the importance of mastering core concepts and understanding deeper topics as candidates progress in their careers.
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)
3 views16 pages

Java Interview Bank Clean

This document is a comprehensive question bank for Java backend developer interviews, categorized by experience levels from 0 to 3 years, covering essential topics like Core Java, Spring Framework, SQL, and multithreading. It includes over 370 questions organized into sections based on years of experience and priority tiers, providing a structured approach for candidates to prepare for interviews in the Indian market. The document also emphasizes the importance of mastering core concepts and understanding deeper topics as candidates progress in their careers.
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


Year-Wise Edition | India Market

Service-Based Companies and Mid-Level Product Companies

370+ 3 13 2
Questions Year Bands Topic Sections Priority Tiers

Core Java, OOP, Collections, Strings, Exceptions,


SECTION 1 0 to 1 Year Spring Intro, SQL Basics

JVM, Concurrency, Java 8+, Spring Boot


SECTION 2 1 to 2 Years Internals, JPA, SQL Depth, Testing

Production Debugging, Microservices, Kafka,


SECTION 3 2 to 3 Years Redis, Gateway, Kubernetes

■ Must-Know — Master before every round ■ Good to Know — Strong differentiator for depth
HOW TO USE THIS QUESTION BANK

■ Must-Know Core concept tested in almost every interview at this level. Know these cold.

■ Good to Know Depth question that shows 1-2 year thinking. Asked at stronger companies or when the
interviewer digs deeper.

Section 1 covers what every fresher must walk in knowing. Section 2 adds the depth expected after one year of
real work. Section 3 tests production thinking, system design, and the kind of scenario questions that separate
average from strong 2-3 year candidates.
SECTION 1 — 0 TO 1 YEAR (Fresher Level)
Focus: Core Java OOP, Collections, Strings, Exception Handling, Spring Intro, Basic SQL

1.1 OOP Fundamentals


■ What is the difference between a class and an object in Java? Give a real-world example.
■ What are the four pillars of OOP? Give one backend-relevant example for each pillar.
■ What is the difference between method overloading and method overriding? Can you override a static method?
■ What is the difference between an abstract class and an interface? When do you choose one over the other?
■ What is runtime polymorphism? Give a concrete example where the actual method called is decided at runtime.
■ What is encapsulation? Why is it important in a REST service?
■ What is the difference between 'is-a' and 'has-a' relationships? Which creates tighter coupling?
■ What is constructor chaining? Show how this() and super() interact with a concrete example.
■ What is the 'final' keyword? Explain every context it can be applied to and what each means.
■ What is the difference between upcasting and downcasting? Where can downcasting throw a
ClassCastException?
■ What is the difference between == and .equals() for Strings? Why can == sometimes return true for literals?
■ What is pass-by-value in Java? Use a simple object mutation example to prove Java never passes by reference.
■ What is autoboxing and unboxing? Where can autoboxing cause a NullPointerException?
■ What is the difference between static and instance methods? When would you use a static method?
■ What is the difference between a constructor and a method? Can a constructor call another constructor?
■ What is the difference between an abstract class and a concrete class? Can you instantiate an abstract class?
■ What is covariant return type in overriding? Give an example.
■ Explain the SOLID principles. Give one Spring Boot example for each.
■ What is the difference between composition and inheritance? Why is composition generally preferred?

1.2 Java Collections Framework


■ What is the difference between Collection (interface) and Collections (utility class)?
■ What is the Java Collections Framework? Name the main interfaces: Collection, List, Set, Queue, Map.
■ What is the difference between List, Set, and Map? When would you use each?
■ What is the difference between ArrayList and LinkedList? When does LinkedList outperform ArrayList?
■ What is the difference between HashMap and TreeMap? How do they differ in ordering and time complexity?
■ What is the difference between HashMap and HashSet?
■ What is the difference between HashMap and LinkedHashMap? When would you use LinkedHashMap?
■ What happens when you add a duplicate key to a HashMap?
■ What is the initial capacity and load factor of HashMap? How do they affect resizing?
■ What is the difference between fail-fast and fail-safe iterators? Give one example of each.
■ What is the difference between Comparable and Comparator? How do you sort Employee objects by salary?
■ What is the difference between Iterator and ListIterator?
■ What is a PriorityQueue? How does it determine ordering?
■ What is the difference between Stack and Deque? Why is Stack discouraged?

1.3 Strings
■ Why is String immutable in Java? What are the security and performance benefits?
■ What is the String pool? When is a String added to the pool versus allocated on the heap?
■ What is the difference between String, StringBuilder, and StringBuffer? When do you use each?
■ How many objects does String s = new String("hello"); create? Explain each.
■ What is the output: String s = "Hello"; [Link](" World"); [Link](s); — and why?
■ Why should you use StringBuilder instead of + concatenation inside a loop?
■ What is [Link]() and when would you use it?
■ How many objects: String s1 = "hello"; String s2 = "hello"; — and which == comparisons return true?

1.4 Exception Handling


■ What is the difference between checked and unchecked exceptions? Give two examples of each.
■ What is the parent class of all exceptions in Java? How does the exception hierarchy look?
■ What is the difference between Error and Exception? Should you ever catch an Error?
■ What does a finally block guarantee? Can it ever be skipped?
■ Can a finally block override a return statement in the try block? What is the output?
■ What is try-with-resources? Why is it preferred over manual finally-based cleanup?
■ How do you create a custom exception? Show both checked and unchecked variants.
■ When should you use throws versus wrapping in try-catch?
■ What are the dangers of catching Exception or Throwable broadly in a Spring service?
■ What is exception chaining (getCause)? Why is it useful for debugging?

1.5 Spring Framework — Introduction


Freshers must know what Spring is, why it exists, and exactly how Spring Boot differs from plain Spring.
■ What is the Spring Framework? What problems does it solve compared to plain Java EE?
■ Why do companies use Spring instead of plain Java? Name four core benefits.
■ What is Inversion of Control (IoC)? Give a simple example of how it works.
■ What is a Spring Bean? How is it different from a regular Java object?
■ What are the three types of Dependency Injection in Spring? Which is recommended and why?
■ What is the difference between Spring Framework and Spring Boot? When would you choose Spring Boot?
■ What problem does Spring Boot solve over plain Spring? What is auto-configuration?
■ What is the Spring Boot starter concept? What does spring-boot-starter-web include?
■ What does @SpringBootApplication do internally? Which three annotations does it combine?
■ What is the default scope of a Spring Bean? What are all the available scopes?
■ What is the difference between @Component, @Service, @Repository, and @Controller?
■ What is @Autowired? How does Spring inject a dependency at runtime?
■ What is the difference between @RequestMapping and @GetMapping?
■ What is the difference between @RequestParam and @PathVariable? Give a URL example for each.
■ What is @RequestBody? When is it used?
■ What is the difference between @Controller and @RestController?
■ What HTTP status codes should you return for GET, POST, PUT, DELETE, and validation errors?
■ What is the difference between PUT and PATCH?
■ What is the Spring Boot architecture? Name its main layers: presentation, service, repository.
■ What is @Value? How do you inject a property from [Link]?
■ What is [Link] versus [Link]? Which supports profiles better?

1.6 SQL — Fundamentals


■ What is the difference between DDL (CREATE, ALTER, DROP) and DML (INSERT, UPDATE, DELETE)?
■ What is the correct order of SQL clause execution: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER
BY?
■ What is the difference between WHERE and HAVING? When can you NOT use WHERE?
■ What is the difference between DELETE, TRUNCATE, and DROP?
■ What is INNER JOIN versus LEFT JOIN? When do you need each? Give a clear example.
■ What is the difference between UNION and UNION ALL?
■ What are ACID properties? Explain each with a bank transfer example.
■ What is a primary key versus a foreign key?
■ What is normalisation? Explain 1NF, 2NF, and 3NF with simple examples.
■ What is an index in a database? Why is it used and what is its trade-off?
■ What is the difference between a subquery and a JOIN? When do you use each?
■ What is a self join? Give a manager-employee hierarchy use case.
■ Write a query to find the second highest salary from an Employee table.
■ What is the difference between a View and a table? When would you create a View?
SECTION 2 — 1 TO 2 YEARS
Focus: JVM, Collections internals, Multithreading, Java 8+, Spring Boot depth, JPA, SQL depth, Testing

2.1 JVM & Memory Internals


■ Explain the JVM runtime data areas: Heap, Stack, Metaspace, Code Cache, and PC Register.
■ What is the difference between Young Generation, Old Generation, and Metaspace? What objects live in each?
■ What is the difference between Minor GC and Full GC? What triggers a Full GC?
■ What is Metaspace? How is it different from PermGen? What causes a Metaspace OutOfMemoryError?
■ What is JIT compilation? How does tiered compilation (C1 vs C2) improve performance?
■ What is an OutOfMemoryError? Describe three distinct root causes with examples.
■ What is a StackOverflowError? What causes it and how do you fix it?
■ How do you detect a memory leak in a running Java production service? What tools do you use?
■ What is the difference between a heap dump and a thread dump? When do you take each?
■ What is the Java Memory Model (JMM)? Why is it important for multithreaded correctness?
■ What is the happens-before relationship? Give three concrete examples.
■ What is the volatile keyword? When is it sufficient and when is it not enough?
■ What JVM flags would you set for a high-throughput Spring Boot REST API? Explain each flag.
■ What is the difference between G1GC, ZGC, and Shenandoah GC? Which suits low-latency REST APIs?

2.2 Collections Internals


■ Explain the internal working of HashMap: hashing, index generation, bucket array, collision handling, and
treeification threshold.
■ What is the hashCode() and equals() contract? What breaks if you override only one?
■ At what threshold does a HashMap bucket convert from a linked list to a red-black tree?
■ Why are String and Integer preferred as HashMap keys? What properties make a good key?
■ HashMap has load factor 0.75 and initial capacity 16. After how many entries does it resize?
■ You put a mutable object as a HashMap key and then mutate it. What happens on the next get()?
■ What is the difference between HashMap and ConcurrentHashMap?
■ How does ConcurrentHashMap achieve thread safety without locking the entire map in Java 8?
■ What is CopyOnWriteArrayList? What is its trade-off and when should you use it?
■ How does ArrayList resize internally? What is the growth factor and amortised cost?
■ What changed in ConcurrentHashMap between Java 7 segment locking and Java 8 CAS approach?
■ What is the difference between WeakReference, SoftReference, and StrongReference?

2.3 Multithreading & Concurrency


■ What are the different ways to create a thread in Java? Which is preferred and why?
■ What is the difference between Runnable and Callable? How do you retrieve a result from Callable?
■ Describe the complete Java thread lifecycle with all states and transitions.
■ What is the difference between sleep() and wait() in terms of lock release behavior?
■ What is a race condition? Give a bank account update example.
■ What is a deadlock? Give an example and explain three prevention strategies.
■ What is the difference between a synchronized method and a synchronized block? Which is more granular?
■ What is a ReentrantLock? Why would you use it instead of synchronized?
■ What is the difference between notify() and notifyAll()? When can notify() cause a missed-signal bug?
■ What is ThreadLocal? Give a real backend use case such as storing request-scoped user context.
■ What is ExecutorService? What are the four standard thread pool types and when do you use each?
■ What are the parameters of ThreadPoolExecutor? How do you size a pool for IO-bound versus CPU-bound work?
■ What is CountDownLatch? Give a real use case such as parallel service calls with a deadline.
■ What is a BlockingQueue? How do you implement a producer-consumer pattern using it?
■ A service uses ThreadLocal to store user session but runs on a thread pool. What bug can occur and how do you
fix it?
■ What is ReentrantReadWriteLock? When does it outperform a plain synchronized block?
■ What is a livelock? How is it different from a deadlock?
■ What is a Semaphore? How is it different from a lock? Give a rate-limiting use case.
■ How does the JVM implement synchronization internally? Explain monitor enter/exit and lock inflation.
■ What is ForkJoinPool? How does work-stealing work and when would you use it?

2.4 Java 8+
■ What is a functional interface? Is @FunctionalInterface annotation mandatory?
■ What is the difference between Predicate, Function, Consumer, and Supplier? Give an example of each.
■ What is a method reference? Give an example of each of the four types.
■ How does a Stream pipeline work internally? What is lazy evaluation and why does it matter?
■ What is the difference between map() and flatMap()? Give a real example.
■ What is the difference between intermediate and terminal operations? Give three examples of each.
■ How do you group a list of employees by department using Streams?
■ How do you find the employee with the highest salary using Streams?
■ When should you use parallelStream()? What are its pitfalls in a Spring web application?
■ What is Optional? How does it prevent NullPointerException and what are its limitations?
■ What is the difference between [Link]() and [Link]()? Which is more efficient?
■ What is CompletableFuture? How is it different from Future?
■ What is the difference between thenApply(), thenAccept(), and thenRun()?
■ How do you handle exceptions in a CompletableFuture pipeline?
■ What is the difference between a default method and a static method in an interface?
■ What is the default method diamond problem in Java 8? How is it resolved?
■ How do you run 50 external API calls in parallel and collect all results within a timeout using CompletableFuture?

2.5 Spring Boot — Internals & Bean Lifecycle


■ What does @SpringBootApplication do internally? Which three annotations does it combine?
■ How does Spring Boot auto-configuration work? Explain [Link] and [Link].
■ Describe the full Spring Bean lifecycle from instantiation to destruction.
■ What is @PostConstruct versus InitializingBean versus init-method? Which is preferred?
■ What is @Configuration and @Bean? When do you use them instead of component scanning?
■ What is the difference between @Primary and @Qualifier? When does a conflict occur?
■ What is the difference between a Spring Singleton bean and the GoF Singleton pattern?
■ Is a Spring Singleton bean thread-safe by default? Why not and how do you fix it?
■ What is the difference between @Autowired on field, constructor, and setter? Why is constructor injection
recommended?
■ What is the difference between JDK dynamic proxy and CGLIB proxy in Spring? When does Spring use each?
■ What is Spring AOP? How does it work internally through proxies?
■ What are the five Spring AOP advice types? When do you use Around advice?
■ What is a pointcut expression? Write one that intercepts all public methods in the service layer.
■ Can Spring AOP intercept a private method or an internal same-class call? Why not?
■ How does @Transactional work internally in Spring? What role does the proxy play?
■ A @Transactional method calls another @Transactional method in the same class. Does a new transaction start?
■ What is @Transactional propagation? Explain REQUIRED, REQUIRES_NEW, and NESTED.
■ What is @Transactional isolation? What anomaly does each isolation level prevent?
■ What is the default rollback behavior of @Transactional? How do you trigger rollback for a checked exception?
■ List three specific reasons why @Transactional might not roll back even when an exception is thrown.
■ What is @ConfigurationProperties? How is it different from @Value for bulk property binding?
■ How do you implement Spring profiles? What is the recommended approach using YAML?
■ What is readOnly=true in @Transactional? What Hibernate optimisation does it enable?

2.6 Spring Security


■ What is Spring Security? What two core concerns does it address?
■ What is the difference between authentication and authorisation in Spring Security?
■ How does Spring Security's filter chain work? What is the role of SecurityFilterChain?
■ What is JWT? What is its structure: header, payload, and signature?
■ How do you implement JWT authentication in Spring Boot? Describe the complete flow from login to accessing a
protected resource.
■ How do you validate a JWT token in a Spring Security filter without hitting the database?
■ How do you implement role-based access control (RBAC) in Spring Boot?
■ What is the difference between JWT and session-based authentication? When would you prefer each?
■ What is the difference between @PreAuthorize and @Secured?
■ How does Spring Security handle CSRF protection? When should you disable it?
■ What is OAuth2 at a high level? How does Spring Security integrate with it?

2.7 REST API Design


■ How does DispatcherServlet work in the Spring MVC request lifecycle? Walk through each step.
■ How do you implement global exception handling using @ControllerAdvice?
■ How do you validate a request body using @Valid and @Validated? What is the difference?
■ How do you handle MethodArgumentNotValidException and return a structured 400 error response?
■ How do you configure CORS in Spring Boot to allow only your production frontend domain?
■ How do you implement idempotency for a payment API endpoint?
■ How do you implement API versioning in Spring Boot (URI, header, and parameter approaches)?
■ What is the difference between @ResponseBody and ResponseEntity?
■ How do you stream a 500MB file download without loading it fully into JVM memory?
■ How do you implement rate limiting in a Spring Boot REST API?

2.8 Spring Actuator & Observability


■ What is Spring Boot Actuator? Which endpoints are most useful in production and why?
■ How do you expose only specific Actuator endpoints in production? What are the security implications?
■ What is the difference between /actuator/health and /actuator/info? How do you customise a health indicator?
■ What is Micrometer? How does Spring Boot integrate with Prometheus for metrics collection?
■ How do you create a custom metric using Micrometer: Counter, Gauge, and Timer?
■ What is /actuator/loggers? How do you change a log level at runtime without restarting the service?
■ How do you configure liveness and readiness probes in Kubernetes using Actuator endpoints?

2.9 JPA / Hibernate & Spring Data JPA


■ What is the difference between JPA, Hibernate, and Spring Data JPA? What does each layer provide?
■ What is the JPA persistence context? What is its default scope in a Spring Boot application?
■ What are the four entity states in JPA (Transient, Managed, Detached, Removed)? How do you transition
between them?
■ What is dirty checking in Hibernate? How does it work and when does the flush happen?
■ What is [Link] versus [Link]? What is the default for @OneToMany and @ManyToOne?
■ 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?
■ What is the difference between @JoinColumn and mappedBy in a bidirectional relationship?
■ How do you avoid infinite recursion in JSON when using bidirectional JPA relationships?
■ What is optimistic locking in JPA? How do you implement it with @Version?
■ What are the GenerationType strategies? When would you use SEQUENCE over IDENTITY?
■ What is the difference between JpaRepository and CrudRepository?
■ How do you write a custom query using @Query? What additional annotation is needed for modifying queries?
■ What is a LazyInitializationException? What are three ways to fix it and which is preferred?
■ What is an Entity Graph? How do you use @EntityGraph to solve N+1 without over-fetching?
■ What is pessimistic locking? When would you use PESSIMISTIC_WRITE versus PESSIMISTIC_READ?
■ How do you implement pagination and sorting in Spring Data JPA?
■ How do you implement batch inserts efficiently in JPA? What Hibernate properties must be enabled?
■ How do you implement projections? What is the difference between interface-based and class-based projections?

2.10 SQL — Depth, Indexing & Optimisation


■ What is a CTE (Common Table Expression)? How is it different from a subquery? Write a real example.
■ What is a window function? Write a query using RANK(), DENSE_RANK(), and ROW_NUMBER() and explain the
difference.
■ Write a query to find the top 3 highest-paid employees per department using window functions.
■ Write a query to find employees earning more than the average salary of their own department.
■ Write a query to detect duplicate rows and delete all but one copy.
■ What is an index? How does a B-Tree index work internally?
■ What is the difference between a clustered and a non-clustered index?
■ What is a composite index? What is the left-prefix rule? Give an example where the index is NOT used.
■ What is a covering index? How can it eliminate a table lookup entirely?
■ When does an index hurt performance instead of helping? Give three scenarios.
■ What is the difference between LIMIT/OFFSET pagination and keyset (cursor) pagination? Why is OFFSET slow
on large tables?
■ What are transaction isolation levels? What anomaly does each level prevent?
■ How do you read and interpret a SQL EXPLAIN plan? What do Seq Scan and Index Scan mean?
■ Write a recursive CTE to traverse an employee-manager hierarchy up to the root CEO.
■ Write a query using LEAD() and LAG() to calculate month-over-month revenue growth.

2.11 Spring Boot Testing


■ What is the difference between unit tests, integration tests, and end-to-end tests? When should you write each?
■ What is the test pyramid? How does it guide test investment in a Spring Boot project?
■ What is the difference between @SpringBootTest, @WebMvcTest, and @DataJpaTest? When do you use each?
■ What does @WebMvcTest load? How do you test a controller in complete isolation from the service layer?
■ What does @DataJpaTest load? How do you test a repository against an in-memory database?
■ What is Mockito? What is the difference between @Mock, @Spy, and @InjectMocks?
■ What is the difference between when().thenReturn() and doReturn().when()?
■ What is an ArgumentCaptor and when would you use it?
■ What is @MockBean versus @Mock? When do you use @MockBean in a Spring Boot test?
■ How do you test a Spring MVC controller using MockMvc? Describe a test for a POST endpoint with validation.
■ How do you test global exception handling (@ControllerAdvice) using MockMvc?
■ What is WireMock and how do you use it to stub external HTTP calls in integration tests?
■ What is contract testing? How does Pact work at a high level?
SECTION 3 — 2 TO 3 YEARS
Focus: Production debugging, advanced concurrency, microservices, Kafka, API Gateway, Redis, Kubernetes

3.1 Advanced Concurrency


■ What is a StampedLock? How does its optimistic read mode differ from ReadWriteLock?
■ What is a Condition variable? How is it used with ReentrantLock as a replacement for wait/notify?
■ What is thread starvation? How do you prevent it using ReentrantLock fairness?
■ What is [Link]()? What happens when the task throws an exception or you call get() without a timeout?
■ How do you run 50 external API calls in parallel and collect all results within a deadline using CompletableFuture?
■ How do you combine two CompletableFutures using thenCombine() versus thenCompose()?
■ What is the difference between submit() and execute() in ExecutorService?
■ How do you handle thread interruption correctly in a long-running background task?
■ What is CyclicBarrier? How is it different from CountDownLatch?
■ What is the ReentrantLock fairness trade-off? What is the impact on throughput?

3.2 Spring Boot — Production Patterns


■ How does @Cacheable work internally (CacheInterceptor, CacheManager, CacheResolver)?
■ What is the difference between @Cacheable, @CachePut, and @CacheEvict?
■ Your @Cacheable method is called every time despite a supposed cache hit. List the three most common causes.
■ How do you set cache expiration in Spring Cache backed by Redis?
■ How do you implement WebClient for async HTTP calls? How is it different from RestTemplate?
■ How do you implement retry logic with exponential backoff in Spring Boot using Resilience4j?
■ How do you implement a circuit breaker using Resilience4j in Spring Boot?
■ What is conditional caching using 'unless' and 'condition' in @Cacheable?
■ How do you implement asynchronous methods using @Async in Spring Boot?

3.3 Microservices Architecture & Patterns


■ What is the difference between a monolith and microservices? What are the main trade-offs?
■ How do microservices communicate? Synchronous REST/gRPC versus asynchronous Kafka/RabbitMQ.
■ What is Event-Driven Architecture? When is it preferable over synchronous REST calls?
■ What is the Saga pattern? When do you choose orchestration versus choreography?
■ How do you implement compensating transactions in a Saga? Give a payment and inventory rollback example.
■ What is CQRS? What problem does it solve and what complexity does it introduce?
■ What is Event Sourcing? How is it different from traditional CRUD? What are the drawbacks?
■ What is a circuit breaker? Describe the three states (Closed, Open, Half-Open) and their transitions.
■ What is the Bulkhead pattern? How does it prevent cascade failures?
■ What is service discovery? How do you implement it with Eureka in Spring Cloud?
■ What is distributed tracing? What is the role of traceId and spanId? How do you propagate context?
■ What is the CAP theorem? How does it affect design choices for a distributed database?
■ What is eventual consistency? How do you achieve it between two microservices?
■ What is the 12-Factor App methodology? Name five factors relevant to Spring Boot.

3.4 API Gateway & Spring Cloud Gateway


■ What is an API Gateway? What responsibilities does it take on in a microservices architecture?
■ What is Spring Cloud Gateway? How is it different from Netflix Zuul?
■ How do you configure routing rules in Spring Cloud Gateway?
■ How do you implement authentication at the API Gateway level using a pre-filter?
■ What is the difference between a Gateway filter and a Global filter in Spring Cloud Gateway?
■ How do you implement rate limiting at the API Gateway using Spring Cloud Gateway and Redis?
■ What is the difference between API Gateway load balancing and service-side load balancing?

3.5 Kafka & Spring Kafka


■ What is Apache Kafka? What problem does it solve compared to synchronous REST?
■ What is the difference between a Kafka topic, partition, offset, and consumer group?
■ How do you publish a message to a Kafka topic using KafkaTemplate in Spring Kafka?
■ How do you consume messages from a Kafka topic using @KafkaListener in Spring Kafka?
■ What is at-most-once, at-least-once, and exactly-once delivery in Kafka?
■ How do you implement idempotent Kafka consumers to handle duplicate messages?
■ What is a Dead Letter Topic (DLT)? How do you configure it in Spring Kafka for failed messages?
■ What is consumer group rebalancing in Kafka? When does it happen and what is its impact?
■ What is the difference between manual and automatic offset commit in Spring Kafka?
■ How do you configure retry logic for a failed @KafkaListener using RetryableTopic?

3.6 Redis & NoSQL Basics


■ What is Redis? What are its primary data structures and when would you use each (String, Hash, List, Set, Sorted
Set)?
■ What is Redis used for in a Spring Boot application beyond simple key-value caching?
■ What is the difference between Redis RDB snapshot and AOF append-only persistence?
■ What is MongoDB? When would you choose it over a relational database?
■ What is a document in MongoDB? How does schema-less design affect query patterns?
■ What is the difference between Redis SETEX and SETNX? Where would you use each?
■ How do you model a one-to-many relationship in MongoDB? Embedding versus referencing trade-offs.

3.7 Performance & Memory Debugging


Practice structured root-cause analysis: Observe, Hypothesize, Investigate, Fix.
■ 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.
■ A Spring Boot service starts dropping requests under 1000 concurrent users. How do you identify the bottleneck
across thread pool, DB connection pool, GC, and CPU?
■ A HashMap-based cache in a singleton Spring bean is growing unboundedly. What is the root cause and fix?
■ A scheduled job reads 1 million DB records and throws OutOfMemoryError. How do you fix it using streaming or
pagination?
■ A database query takes 8 seconds in production but 200ms locally. List your investigation steps.
■ You deployed a new version and response time increased 5x with no errors in logs. Describe your systematic
debugging approach.
■ A batch job throws OOM for 1 million plus records but works fine for small datasets. What do you change?
■ Your Kubernetes pod keeps restarting due to OOM. How do you configure memory limits and tune JVM heap for
a containerised app?
■ How do you profile a CPU-bound Spring Boot service? What tools do you use?
3.8 Concurrency Issues in Production
■ Two threads update the same account balance simultaneously and updates are lost. What is this problem and
how do you fix it using DB locking, synchronized, or AtomicLong?
■ A singleton Spring bean has an instance variable modified per-request and the value is wrong under load. How do
you fix it?
■ A microservice uses ThreadLocal for user session in a thread pool. Wrong users see wrong session data. What is
the bug and fix?
■ Your ExecutorService thread pool is exhausted and requests are queuing forever. How do you diagnose and tune
the parameters?
■ A deadlock occurs between two service methods locking two DB rows in different orders. How do you detect and
prevent it?
■ Your service uses parallelStream() for order processing and intermittently produces wrong totals. Why and how
do you fix it?
■ An API works in testing but throws ConcurrentModificationException randomly in production. What causes this
and how do you fix it?

3.9 JPA & Database Issues


■ A JPA entity with @OneToMany causes 100 plus SQL queries instead of 1. How do you identify and fix the N+1
problem?
■ Two users update the same product stock simultaneously and one update is silently overwritten. What JPA
feature prevents this?
■ A service method annotated @Transactional is not rolling back on exception. List three possible causes.
■ A lazy-loaded collection throws LazyInitializationException after the transaction closes. What are the solutions
and which is preferred?
■ You need to insert 100,000 records efficiently from a batch job. How do you configure and implement this with
Spring Data JPA?
■ A JOIN query on a 10-million-row table takes 30 seconds. Walk through your step-by-step investigation and
optimisation.
■ What is a database deadlock? How do you detect it from DB logs and prevent it by ordering row locks?
■ Your JPA app throws LazyInitializationException in production but not in tests. What causes the difference?
■ A refactoring removed @Transactional accidentally. How do you detect this in code review and integration tests?

3.10 Distributed System Scenarios


■ A payment microservice calls inventory and notification. If inventory fails, how do you rollback using the Saga
pattern?
■ 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?
■ A client calls your payment API multiple times due to retries, causing duplicate charges. How do you prevent this?
■ Your event-driven service publishes an event but the consumer fails and the event is lost. How do you ensure
at-least-once delivery?
■ A Kafka consumer processes the same event twice due to a retry. How do you ensure idempotency in the
handler?
■ How do you debug a slow request that crosses 5 microservices with no centralised logging?
■ Your circuit breaker opens too aggressively on transient errors. How do you tune it?
■ A new deployment breaks an existing Kafka consumer because the event schema changed. How do you handle
schema evolution?
■ Your Redis cache is down. How does your Spring Boot application behave and how do you configure graceful
degradation?

3.11 Logging, Monitoring & Kubernetes


■ What is the ELK stack (Elasticsearch, Logstash, Kibana)? How does it help you debug a production incident?
■ How do you structure logs in a Spring Boot application so they are searchable in Kibana?
■ What is the difference between structured logging (JSON) and plain text logging? Why is structured logging
preferred?
■ How do you correlate logs across multiple microservices using a traceId in the log output?
■ What is a Kubernetes liveness probe versus a readiness probe? What happens when each fails?
■ How do you configure liveness and readiness probes for a Spring Boot service using Actuator endpoints?
■ A Kubernetes pod shows CrashLoopBackOff. What is your debugging checklist?
■ How do you implement a distributed log correlation ID in a Spring Boot service using MDC?
■ What is Logback and how do you configure different log levels per environment?

3.12 SQL — Advanced & Stored Procedures


■ What is a stored procedure? How is it different from a function in SQL?
■ What are the advantages and disadvantages of stored procedures in a microservices architecture?
■ What is table partitioning? Explain Range, List, and Hash partitioning with use cases.
■ What is the difference between horizontal and vertical partitioning?
■ What is a partial index? When would you create one?
■ What is a Materialized View? When would you use it over a regular View?

3.13 Tricky & Commonly Failed Questions


Highest failure rate — test true understanding versus surface memorisation. Know these cold.

■ What is the output when a finally block has a return statement that conflicts with a return in the try block?
■ You put a mutable object as a HashMap key and then mutate it. What happens when you call get() with the same
reference?
■ String s1='Java'; String s2=new String('Java'); String s3=[Link](); — which == comparisons return true and
why?
■ Can a constructor throw an exception? If so, is the object created on the heap?
■ A @Transactional method calls another @Transactional method in the same class. Does the inner transaction
start a new one?
■ You annotate a private method with @Transactional. Does it work? Why or why not?
■ A Spring singleton bean has an instance variable modified per-request. Is this thread-safe?
■ HashMap has load factor 0.75 and initial capacity 16. After exactly how many entries does it resize?
■ What is the output: for(Integer i : list){ if(i==1) [Link](i); } — and why?
■ What is the risk of [Link]() without isPresent()? What is the safe alternative?
■ How do you distinguish [Link]() returning null because the key is absent versus because the key maps to
null?
■ Does adding @Async to a method guarantee it runs in a separate thread if the caller is in the same class?
■ You use parallelStream().forEach() to write to a non-thread-safe ArrayList. What happens and what is the fix?
■ You call notify() but no thread is waiting. What happens? Is the signal lost?
■ What happens when you call a @Transactional method on a bean instantiated directly with new MyService()
instead of injecting it?
■ What exception is thrown to the caller when you call [Link]() and the async task throws a
RuntimeException?
■ Can you make a static field volatile? What does it achieve?
■ What happens when two threads call [Link]() concurrently in Java 8+?
QUICK REFERENCE — TOP 30 MUST-KNOW QUESTIONS

01. OOP four pillars with real backend examples for each. 16. JWT structure and full Spring Security authentication
flow.

02. HashMap internals: hashing, collision handling, 17. Circuit breaker: Closed/Open/Half-Open states and
treeification threshold. transitions.

03. N+1 query problem: detection via SQL logs and all fix 18. Saga pattern: orchestration vs choreography with
strategies. compensating transactions.

04. @Transactional propagation: REQUIRED vs 19. CQRS and Event Sourcing: benefits, drawbacks,
REQUIRES_NEW vs NESTED. when to use.

05. Optimistic vs pessimistic locking in JPA for 20. [Link] vs EAGER: safer choice in REST
high-concurrency. APIs and the LazyInitializationException fix.

06. happens-before relationship in the Java Memory 21. Idempotency for payment APIs: implementation
Model. strategies.

07. ReentrantLock vs synchronized: when and why. 22. parallelStream() pitfalls in a Spring web application.

08. ConcurrentHashMap vs 23. All conditions required to make a class truly


[Link]() internals. immutable.

09. CompletableFuture: async pipelines and exception 24. Spring Actuator: key endpoints and liveness/readiness
handling. for Kubernetes.

10. Full Spring Bean lifecycle from construction to 25. Kafka: at-least-once delivery, idempotent consumers,
destruction. Dead Letter Topic.

11. Spring vs Spring Boot: differences and when to 26. ELK stack: structured logging and log correlation with
choose Spring Boot. traceId.

12. Spring Boot auto-configuration: [Link] / 27. SQL EXPLAIN plan: Seq Scan vs Index Scan and
[Link]. fixing slow queries.

13. @Transactional same-class call: why the proxy is 28. Composite index left-prefix rule: when the index is and
bypassed. is not used.

14. JDK dynamic proxy vs CGLIB proxy: when Spring 29. Redis data structures and their use cases in a Spring
uses each. Boot service.

15. Global exception handling with @ControllerAdvice. 30. @Cacheable internals: CacheInterceptor,
CacheManager, and top 3 miss causes.

You might also like