Skip to content

JQ

Here is the segregated list of interview questions categorized by topic in Markdown format:


1. Core Java & OOP Concepts

  • OOP Principles: Explain OOPs concepts (Inheritance, Encapsulation, Polymorphism, Abstraction) and how you used them in your project.

  • Abstraction vs Encapsulation: What is the difference between Abstraction and Encapsulation?

  • SOLID Principles: Explain SOLID principles with real-world examples.

  • Immutability:

  • What is an Immutable Class? How do you create one, and why is it thread-safe?

  • Explain immutability in Java with examples (String, Integer).

  • Why is String immutable in Java?

  • String Pool & Memory:

  • If String str = new String("abc"), how many objects are created?

  • What is the String Constant Pool, and where are String literals stored?

  • Difference between StringBuffer and StringBuilder.

  • Java Modern Features (Java 8, 17, 21):

  • What are sealed classes, records, and pattern matching for switch in Java 17+?

  • What are text blocks, and where are they useful?

  • What are major Java 8 features (Streams, Lambdas, Optional, Functional Interfaces)?

  • Explain the major Java 8 features and their practical use cases.

  • How does Java 8 Stream API work internally?

  • Explain map() vs flatMap() with a real-world example.

  • Keywords & Modifiers:

  • What is a transient variable?

  • Difference between final, finally, and finalize()?

  • Difference between ==, .equals(), and .compareTo().

  • Exception Handling:

  • Difference between throw and throws.

  • Difference between checked and unchecked exceptions.

  • When should checked exceptions be converted into unchecked ones?

  • Why is catching Exception or Throwable considered bad practice?

  • Explain Try-with-Resources. What happens when both the try block and close() throw exceptions?

  • Language Basics:

  • Difference between Abstract Class and Interface.

  • Can a constructor throw an exception? Why can't constructors be overridden?

  • Can we overload the main() method?

  • Static vs Dynamic Binding.

  • Why is it recommended to store passwords in char[] instead of String?

  • What is a Functional Interface? Can it contain default and static methods?


2. Collections Framework & Data Structures

  • HashMap Internals:
  • Explain HashMap internal working (hashing, bucket selection, collision handling, treeification in Java 8).

  • Why are equals() and hashCode() important in HashMap?

  • If a Student class has Roll Number as a unique identifier and is used as a HashMap key, what changes would you make to maintain uniqueness?

  • Map Implementations:

  • Difference between HashMap, LinkedHashMap, Hashtable, and ConcurrentHashMap.

  • Why does ConcurrentHashMap exist, how does it work internally, and why does it not allow null keys or values?

  • Explain the internal working of ConcurrentHashMap in Java 8.

  • HashMap vs ConcurrentHashMap — why do we need ConcurrentHashMap?

  • Internal Data Structures:

  • What underlying Data Structure is used in Hashtable, PriorityQueue, TreeSet, LinkedHashSet, and TreeMap?

  • Are TreeSet and LinkedHashSet thread-safe? Can we insert null in LinkedHashSet?

  • Lists & Sets:

  • Difference between Collection vs Collections.

  • Difference between ArrayList and LinkedList internal implementation.

  • Where to use Array vs ArrayList? Does ArrayList maintain insertion order?

  • Internal working of HashSet.

  • Iterators & Sorting:

  • What causes ConcurrentModificationException? Explain Fail-Fast vs Fail-Safe iterators with examples.

  • Fail-Fast vs Fail-Safe iterators — how do they work internally?

  • Difference between Comparable and Comparator.


3. Multithreading, Concurrency & JVM

  • Thread Fundamentals:
  • Difference between a Process and a Thread.

  • Platform Thread vs Virtual Thread?

  • Thread lifecycle states (especially NEW vs RUNNABLE vs BLOCKED).

  • Difference between start() and run() methods.

  • What happens if we run the same thread twice?

  • What is a Race Condition?

  • How do you prevent Race Conditions?

  • What is Deadlock?

  • How do you detect and prevent Deadlocks?

  • Deadlock vs Livelock vs Starvation?

  • What is Thread Starvation?

  • Thread Creation & Pools:

  • Different ways to create a thread (extending Thread, implementing Runnable, implementing Callable).

  • Pros and cons of extending Thread vs implementing Runnable vs using ExecutorService.

  • What is ExecutorService and Thread Pool, and why is it preferred over creating threads manually?

  • ExecutorService vs ForkJoinPool?

  • How does ThreadPoolExecutor work?

  • How do you choose Core Pool Size and Maximum Pool Size?

  • What happens when a ThreadPoolExecutor queue becomes full?

  • Java Memory Model & Synchronization:

  • How does the Java Memory Model work?

  • What is the happens-before relationship?

  • Difference between volatile, synchronized, and Atomic classes.

  • synchronized vs ReentrantLock?

  • volatile vs Atomic variables?

  • What is CAS and how does it work?

  • How does ConcurrentHashMap achieve thread safety?

  • Synchronization vs Locking difference.

  • Role of notify() and notifyAll().

  • Asynchronous & Modern Concurrency:

  • CompletableFuture API: thenApply() vs thenCompose(), Future vs CompletableFuture.

  • CompletableFuture vs Future?

  • How does CompletableFuture work internally?

  • thenApply vs thenCompose vs thenCombine?

  • What are Virtual Threads in Java 21, and how do they differ from Platform Threads?

  • How do Virtual Threads work internally?

  • When should you NOT use Virtual Threads?

  • Virtual Threads vs CompletableFuture?

  • How do you handle blocking operations with Virtual Threads?

  • How does BlockingQueue work in a Producer–Consumer pattern?

  • What is CountDownLatch?

  • CountDownLatch vs CyclicBarrier?

  • What is Semaphore and where would you use it?

  • What is Phaser?

  • ThreadLocal & Advanced Concurrency:

  • What is ThreadLocal and its real-world use cases?

  • What problems can ThreadLocal cause?

  • What is False Sharing?

  • What is ForkJoinPool?

  • How do parallel streams use threads?

  • Why can parallel streams hurt performance?

  • JVM & Memory Management:

  • How does Java handle memory management (Heap vs Stack, Metaspace, GC types like G1GC / ZGC)?

  • Parallel streams — when to use and when NOT to use them.

  • How would you debug a production thread issue?

  • How would you investigate high CPU caused by Java threads?

  • How would you identify thread pool exhaustion?

  • How would you design a thread-safe cache?

  • Describe a real-world concurrency problem you solved.


4. Spring Framework & Spring Boot

  • Spring Core & DI:
  • What is Dependency Injection (DI) and Inversion of Control (IoC)?

  • Different ways to inject beans in Spring (Constructor, Setter, Field) — which is recommended and why?

  • Lifecycle of a Spring Bean and default bean scope vs other scopes.

  • BeanFactory vs ApplicationContext.

  • Difference between @Component, @Service, @Repository, and @Controller.

  • Why do we use @Service and @Repository, and what does Spring do differently with them internally?

  • What happens if both @Service and @Repository are used on the same class?

  • Explain Spring's three-level singleton cache and its role in resolving circular dependencies during bean creation.

  • Why does constructor injection fail with circular dependencies? (When and why setter injection or proxying may be required.)

  • How does Dependency Injection work internally in Spring?

  • Explain the Spring Bean lifecycle and different bean scopes.

  • Spring Boot Internals & Annotations:

  • What is Spring Boot and how does it differ from Spring Framework?

  • How does Spring Boot Auto-Configuration work internally (@EnableAutoConfiguration, @ComponentScan)?

  • Explain @SpringBootApplication and its composition.

  • What happens internally when @SpringBootApplication is executed?

  • What are Spring Boot Starters?

  • Difference between @Controller and @RestController.

  • Explain @Configuration, @Bean, @Value, @ConfigurationProperties, @Qualifier, and @ConditionalOnProperty.

  • Spring MVC & Features:

  • Spring MVC Architecture and request flow.

  • Internal working of @Autowired and JDK Dynamic Proxy vs CGLIB in Spring AOP.

  • What are Spring AOP concepts (JoinPoint, Advice, Aspect)?

  • Role of CommandLineRunner, ApplicationRunner, Spring Boot DevTools, and Actuator.

  • How to handle multiple-bean conflicts and circular dependencies.

  • How application.properties / application.yml work and profile management across environments.

  • When would you choose Spring MVC vs WebFlux vs Java Virtual Threads? (Use-cases, threading model, blocking vs non-blocking, and performance trade-offs.)

  • Spring @Transactional & Proxy-based Features:

  • How does @Transactional work through Spring proxies?

  • How does @Transactional work internally in Spring Boot?


5. Spring Data JPA, Hibernate & Databases

  • JPA & Hibernate Core:
  • Why do we use Hibernate? Relationship between JPA, Spring Data JPA, and Hibernate.

  • Difference between Hibernate and ORM.

  • End-to-end flow of how an @Entity class becomes a table in DB (JPA → Hibernate → SQL).

  • First-Level Cache vs Second-Level Cache in Hibernate.

  • Why does @Transactional sometimes fail during self-invocation (internal method calls) and how proxy-based transaction management works?

  • What is the JPA N+1 query problem and how would you solve it?

  • Fetching & Performance:

  • LAZY vs EAGER fetching strategies.

  • What is the N+1 query problem in JPA/Hibernate, and how do you solve it?

  • What is dirty checking in JPA?

  • Transactions & Locking:

  • Transaction management in Spring (@Transactional propagation and isolation levels).

  • Optimistic Locking vs Pessimistic Locking.

  • If two requests are trying to update the same row in the database, how would you handle this scenario?

  • Spring Data Repositories & SQL:

  • Difference between CrudRepository, JpaRepository, and PagingAndSortingRepository.

  • JPQL vs Native Queries and @Query usage.

  • Database migrations using Flyway / Liquibase.

  • Types of SQL Joins, Primary Key vs Foreign Key, and Indexing types.

  • Difference between SQL and NoSQL.

  • Connecting MySQL & MongoDB in Spring Boot and MongoDB annotations (@Document, @Id).


6. REST APIs, Web & Security

  • REST API Design:
  • How REST APIs handle different HTTP methods.

  • Can we use POST for updating values instead of PUT? Why or why not?

  • Difference between Path Parameter and Query Parameter.

  • How @RequestBody works internally in Spring Boot.

  • Designing idempotent REST APIs and API Versioning.

  • How would you design idempotent APIs in a distributed system?

  • How would you prevent a duplicate payment when a "POST /payments" request times out after the server completes it and the client retries?

  • Validation & Exception Handling:

  • How to implement Global Exception Handling in REST APIs using @ControllerAdvice / @ExceptionHandler.

  • Request validation JSR-303 and handling file uploads.

  • Security & Auth:

  • How to secure REST APIs using JWT vs OAuth2.

  • How Spring Security filter chain works internally.

  • What is CORS and how do browsers enforce it?

  • Preventing SQL Injection, XSS, and CSRF attacks.

  • How do you secure microservices with OAuth2, JWT, and Spring Security? (Authentication vs Authorization, token validation, token propagation, introspection, and best practices.)

  • A stolen JWT is still valid and is being replayed from another device. What can you do beyond validating its signature and expiry?

  • What is the difference between Session and Cookies?

  • How would you detect and prevent unauthorized access (e.g., user changes "/users/123/orders/456" to "/users/124/orders/456" and sees another user's order)?


7. Microservices Architecture & Spring Cloud

  • Architecture & Migration:
  • Monolith vs Microservices architecture: trade-offs and step-by-step migration patterns.

  • Microservices design patterns and challenges.

  • How do you implement distributed transactions across microservices? (Saga pattern — choreography vs orchestration, two-phase commit alternatives, event-driven compensations.)

  • How would you migrate a Java application from on-premise to Cloud?

  • How would you design microservices for high availability?

  • Communication & Routing:

  • Inter-service communication: REST vs Kafka vs gRPC.

  • API Gateway (Spring Cloud Gateway / Zuul): routing, cross-cutting concerns, and rate-limiting.

  • Service Discovery using Eureka / Consul.

  • Purpose and advantages of Spring Cloud Config Server.

  • How do independent microservices communicate with each other?

  • REST vs messaging-based communication — when would you choose each?

  • API Gateway vs Load Balancer — what is the difference?

  • Resilience & Distributed Systems:

  • Preventing cascading failures: Circuit Breaker pattern, Resilience4j states, Fallback mechanisms, and Bulkhead pattern.

  • Distributed Transaction patterns: Saga Pattern (Choreography vs Orchestration) vs Two-Phase Commit (2PC).

  • Distributed Tracing across microservices (Zipkin, OpenTelemetry, Sleuth).

  • Eventual consistency in distributed microservices.

  • How would you handle failure between two microservices?

  • How would you handle failures between two microservices?

  • Explain Circuit Breaker, Retry and Timeout patterns.

  • How would you manage distributed transactions in Microservices?

  • How would you prevent duplicate processing of Kafka messages?

  • A downstream service starts failing. Your service retries every request three times and makes the outage worse. How should retries work?

  • Monitoring & Troubleshooting:

  • How would you monitor and troubleshoot a production microservices application?

  • How would you monitor and troubleshoot a failed production deployment?


8. Messaging Systems (Apache Kafka & Event-Driven Systems)

  • Kafka Core Concepts:
  • Kafka Topic vs Queue, Partitions, Producers, Consumers, and Consumer Groups.

  • When should you create multiple topics vs multiple partitions?

  • Kafka Producer ACKs (0, 1, all) and message durability.

  • Message Delivery & Scalability:

  • How does Kafka guarantee message ordering for a customer/key?

  • At-least-once, At-most-once, and Exactly-once semantics.

  • How Kafka partitions enable scalability.

  • How do you achieve Kafka producer idempotency and exactly-once processing? (Enable idempotence, set transactional.id, use transactions with consumer/producer to achieve EOS.)

  • Failure & Scenario Handling:

  • Handling duplicate message processing / idempotent consumers.

  • What is a Dead Letter Queue (DLQ) / Dead Letter Topic?

  • Troubleshooting increasing consumer lag or traffic imbalance across partitions.

  • Kafka vs RabbitMQ comparison.


9. Caching, System Design & Architecture

  • Caching Strategies:
  • How caching works, Cache Hit vs Cache Miss, Cache placement strategies, and Eviction algorithms (TTL, LRU).

  • Redis caching strategies and application behavior when Redis crashes.

  • How do you prevent a cache stampede with @Cacheable? (Use cache-aside with mutex/locking, request coalescing, use randomized TTLs, early recompute, or use a dedicated single-flight mechanism.)

  • In what scenarios is caching not recommended?

  • System Design Concepts:

  • How to scale APIs receiving 100,000 requests per minute.

  • What would you do to handle scaling from 500 to 20,000 requests per minute?

  • Rate limiting strategies and designing an API Rate Limiter.

  • CAP Theorem and its real-world applications.

  • Horizontal vs Vertical scaling and Application-level Load Balancing.

  • Database Sharding & Replication.

  • When should you do horizontal scaling of the database?

  • Design Scenarios & LLD:

  • High-level design for Order Management System, URL Shortener, and Notification Service.

  • Low-Level Design (LLD) & Design Patterns (Factory, Observer, Singleton, etc.).

  • Design an order processing system handling 100K+ requests/minute (capacity planning, sharding, async processing, CQRS/event sourcing, caching, batching, back-pressure, and observability).


10. DevOps, Cloud (AWS), Docker & Kubernetes

  • Containerization:
  • Difference between Docker image vs container.

  • Docker volumes and Docker Compose (docker-compose up / down).

  • How would you deploy a Spring Boot application using Docker and Kubernetes?

  • Orchestration & Deployment:

  • Kubernetes pod scaling, Horizontal Pod Autoscaler (HPA), Liveness vs Readiness probes.

  • Blue-green vs Canary deployments for zero-downtime.

  • CI/CD pipeline setup for Spring Boot applications (Jenkins / GitHub Actions).

  • Explain a typical CI/CD pipeline for a Spring Boot Microservice.

  • What happens from git push until the application is deployed to production?

  • Cloud & Observability:

  • Secure EC2 to S3 access without hardcoding credentials (IAM Roles).

  • AWS Shared Responsibility Model.

  • Observability tools: Centralized logging, Prometheus, Grafana, ELK stack.


11. Production Troubleshooting & Debugging Scenarios

  • Memory & CPU Issues:
  • Application throwing OutOfMemoryError — debugging heap, metaspace, and memory leaks.

  • High CPU usage with low traffic.

  • Identifying and resolving Deadlocks or threads stuck in BLOCKED state.

  • Spring Boot application consuming more memory over time.

  • How do you troubleshoot HikariCP connection pool exhaustion? (Check datasource configuration, maxPoolSize, connection leak detection, slow queries, DB-side limits, thread dumps, and metrics from HikariCP.)

  • How would you identify a memory leak in a Java application?

  • Latency & Performance:

  • REST API response time increasing (e.g., from 1s to 10s or 30s downstream calls).

  • Database query optimization (troubleshooting 20–30 second queries, execution plans, indexing).

  • Database connection pool exhaustion under load.

  • Spring Boot app startup time slowness (e.g., 15s to 2min).

  • Your API usually responds in 80ms. P99 jumps to 2 seconds, but CPU and memory look normal. What could cause it?

  • One API depends on three downstream services. Each is fast individually, but the API is slow. Why?

  • Traffic grows and requests start waiting for database connections. Will you increase the connection pool?

  • An endpoint that once returned 100 records now has 100,000. How do you keep it fast as the dataset grows?

  • Your React app is working fine on local but is slow on production. How would you debug it?

  • How would you debug a slow React app on the local machine?

  • Operational Anomalies:

  • Application working locally but failing in production (LazyInitializationException, missing configs).

  • Identifying and solving race conditions causing duplicate payments.

  • Application crashing without any clear error or logs.

  • A "POST /payments" request times out after the server completes it. The client retries. How do you prevent a duplicate payment?

  • A user changes "/users/123/orders/456" to "/users/124/orders/456" and sees another user's order. Authentication is valid. What is missing?

  • A downstream service starts failing. Your service retries every request three times and makes the outage worse. How should retries work?

  • Your API returns "200", but the customer says the operation failed. How do logs, metrics, and traces help you find what happened?

  • Error rate jumps from 0.1% to 3%, but only for one customer segment. How do you make that visible without exploding metric cardinality?

  • What happens when two users try to update the same S3 file at the same time?


12. Coding Problems & Practical Tasks

  • Arrays & Algorithms:
  • Two Sum and Three Sum problems.

  • Find duplicate items in an array using Collections.

  • Find Subsets of a given array.

  • Find the second largest element in an array.

  • Find all unique triplets in an array whose sum equals a given target.

  • Strings & Streams:

  • Reverse a String and move all zeros to the end of a String/Array.

  • Count character frequency in a string and print in ascending order (with/without HashMap).

  • Print all substrings of a given string.

  • Find the first non-repeating character in a string.

  • Longest substring without repeating characters.

  • Java 8 Stream code: Find top 3 frequent words from a string.

  • Reverse the words in a String without reversing the characters inside each word.

  • Move all zeroes to the end of an array while maintaining the order of non-zero elements.

  • Find the first non-repeating character using Java 8 Streams.

  • Flatten a nested array and write a deep copy function.

  • LinkedList & Collections:

  • Reverse a linked list (iteratively & recursively).

  • Sort a list of employees: Salary in descending order; if salary is same, Experience/Name in ascending order.

  • Grouping employees by department using Streams.

  • Sort Employees by salary using Java 8 Streams.

  • Java 8 Streams & Functional Programming:

  • Write a Java program to check whether a number is prime.

  • Find the third-highest salary from a list of Employees using Java 8 Streams.

  • Given a nested List, use flatMap() to flatten it into a single List.

  • Find the first 3 odd numbers from a list using Streams.

  • Find the highest-paid employee from each department using Streams.

  • Write a Java 8 program using flatMap() to flatten a nested list.

  • Process a large ConcurrentHashMap using multiple threads safely.

  • Advanced Coding Problems:

  • Implement Merge Sort and explain its time and space complexity.

  • Implement a thread-safe Singleton using double-checked locking.

  • SQL Queries:

  • Query to find the second highest / second best salary of an employee.

  • Query to find the highest salary for each department.

  • Query to find a customer who has not ordered.