Interview guides / Java interview questions for 3 to 5 years experience
Top Java Interview Questions for 3-5 Years Experience 2026
Welcome to the ultimate Java interview guide for 3 to 5 years experience levels in 2026. Designed specifically for developers aiming for mid-level roles, this guide covers core Java, advanced multithreading, microservices, frameworks, and practical troubleshooting scenarios to help you crack your next technical interview with confidence.
Try Jawab AI freeCore Java and Advanced OOPs
1. What is the difference between fail-fast and fail-safe iterators?
Fail-fast iterators throw a ConcurrentModificationException if the collection is structurally modified while iterating over it, like ArrayList or HashMap. Fail-safe iterators work on a clone of the collection, so they do not throw an exception, as seen in CopyOnWriteArrayList. In an interview, I would say: Fail-fast checks for modifications immediately using a modCount variable and throws an exception, whereas fail-safe operates on a separate copy to avoid disruptions.
2. Explain the internal working of HashMap in Java.
HashMap stores key-value pairs as Node objects inside an array of buckets. When you put a key, Java calculates its hashcode, applies a hash function to find the array index, and handles collisions using linked lists or balanced trees (from Java 8 onwards when threshold exceeds 8). If I am asked this, I explain the hashCode and equals contract, bucket index calculation, and how treeification improves worst-case lookup from O(n) to O(log n).
3. How does the Java Memory Model handle visibility and atomicity?
The Java Memory Model defines how threads interact through memory. Variables can be cached in thread-local CPU caches, leading to visibility issues. Using the 'volatile' keyword ensures reads and writes go directly to main memory. Atomicity is handled using synchronized blocks or java.util.concurrent.atomic classes like AtomicInteger for thread-safe operations without locking.
4. What are functional interfaces and how do lambda expressions work under the hood?
A functional interface has exactly one abstract method, annotated with @FunctionalInterface. Under the hood, Java uses invokedynamic bytecode instruction introduced in Java 7 to defer the creation of the class implementation until runtime, rather than generating a physical .class file for every lambda during compilation.
5. Explain how String pool works and why Strings are immutable.
The String pool is a special storage area in the heap where Java stores literal strings to save memory. Strings are immutable for security, synchronization, and caching hashcodes. If I explain this, I mention that once created, a String object's state cannot change, making it safe to share across multiple threads without explicit synchronization.
Multithreading and Concurrency
6. What is the difference between ExecutorService and standard Thread creation?
Creating a new Thread for every task is expensive in terms of memory and CPU overhead due to thread creation and destruction cycles. ExecutorService manages a pool of worker threads, reusing them for multiple tasks. I usually say: ExecutorService handles task queuing, thread reuse, and lifecycle management efficiently using ThreadPoolExecutor.
7. Explain the difference between ReentrantLock and synchronized keyword.
Both provide mutual exclusion, but ReentrantLock offers advanced features like timed lock waits, interruptible lock acquisitions, and fairness policies. Synchronized is implicit and block-structured, released automatically when the block exits, whereas ReentrantLock requires manual unlock in a finally block.
8. How does ThreadLocal work and what are the memory leak risks?
ThreadLocal provides thread-local variables, where each thread has its own independently initialized copy. Memory leaks happen in application servers where threads are pooled. If a ThreadLocal reference is not removed using threadLocal.get().remove(), the value remains attached to the thread, preventing garbage collection of large objects.
9. What is a CompletableFuture and how is it used for asynchronous programming?
CompletableFuture represents a future result of an asynchronous computation, allowing you to chain callbacks and combine multiple futures. For example, CompletableFuture.supplyAsync(() -> fetchUserData()).thenApply(user -> enrichData(user)); helps write non-blocking, declarative asynchronous pipelines.
10. Explain the concept of CAS (Compare-And-Swap) in concurrency.
CAS is an optimistic locking mechanism used in atomic classes. It compares the current value in memory with an expected value and updates it only if they match. If another thread modified it, the operation retries. This avoids thread blocking and context-switching overhead.
Spring Boot and Microservices
11. How does Spring Boot autoconfiguration work internally?
Spring Boot scans classpath dependencies and automatically configures beans using @EnableAutoConfiguration, which relies on spring.factories or META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Conditional annotations like @ConditionalOnClass ensure beans are only created if specific libraries are present.
12. Explain the difference between @Controller and @RestController.
@Controller is used for traditional MVC controllers that return views like JSP or Thymeleaf templates. @RestController is a convenience annotation that combines @Controller and @ResponseBody, meaning every method automatically serializes return objects directly into JSON or XML for REST APIs.
13. How do you handle distributed transactions in microservices?
Distributed transactions are hard because ACID properties span multiple services. Instead of traditional two-phase commit (2PC) which hurts availability, we use the Saga pattern (orchestration or choreography) with compensating transactions, or eventual consistency via message queues like Kafka or RabbitMQ.
14. What are Spring Bean scopes and what is the default scope?
Spring bean scopes define the lifecycle and visibility of beans. The default scope is Singleton, where a single instance is created per Spring IoC container. Other scopes include Prototype (new instance every time requested), Request, Session, and Application for web-aware applications.
15. How do you implement global exception handling in Spring Boot?
We use a class annotated with @ControllerAdvice or @RestControllerAdvice, containing methods annotated with @ExceptionHandler(SpecificException.class). This centralizes error handling, prevents repetitive try-catch blocks in controllers, and ensures consistent error response payloads.
Database, Performance, and Troubleshooting
16. How do you identify and fix the N+1 select problem in JPA/Hibernate?
The N+1 problem occurs when Hibernate executes one query to fetch the parent list and N separate queries to fetch children for each parent. To fix this, I use JOIN FETCH in JPQL queries, entity graph annotations (@EntityGraph), or configure batch fetching using @BatchSize.
17. What is connection pooling and why is it important?
Opening a new database connection for every request is slow and resource-intensive. A connection pool like HikariCP maintains a cache of open database connections, leasing them out to incoming requests and recycling them afterward, drastically improving application throughput.
18. How do you analyze a memory leak in a production Java application?
First, monitor JVM metrics like heap usage trends. When a memory leak is suspected, capture a heap dump using tools like jmap or JVM flags on OutOfMemoryError. Then, analyze the heap dump using Eclipse Memory Analyzer Tool (MAT) to find dominating objects and GC roots holding onto references.
19. Explain database indexing and how it improves query performance.
Indexes are data structures like B-Trees that allow the database to locate rows quickly without scanning the entire table. In an interview, I mention that while indexes speed up read operations (SELECT), they can slow down write operations (INSERT, UPDATE) because the index tree must be updated.
20. What is the difference between optimistic and pessimistic locking in JPA?
Optimistic locking assumes conflicts are rare and uses a version column (@Version) to detect concurrent updates, throwing an exception if a conflict occurs. Pessimistic locking locks the database rows immediately using SELECT ... FOR UPDATE, preventing other transactions from modifying the data until the lock is released.
Tips for the interview
- Always explain the 'why' behind architectural choices rather than just quoting definitions.
- Practice writing clean SQL queries and inline Java snippets on paper or whiteboard.
- Relate technical answers to real production scenarios you have faced or can visualize.
- Be clear and concise; mid-level interviews test depth of understanding over length of speech.
Blank on a question? Not anymore.
Jawab AI listens to your interview and shows a clear answer on your screen in seconds, based on your resume. The desktop app stays invisible when you share your screen. Your first 3 sessions of 10 minutes are free.
Try Jawab AI freeMore interview guides
- Meta Software Engineer Interview Questions 2026 Guide
- Tech Mahindra Interview Questions for Freshers 2026
- Google Software Engineer Interview Questions 2026 Guide
- HCL Tech Interview Questions and Answers for Freshers 2026
- Behavioral Interview Questions and STAR Method Answers 2026
- Selenium Automation Testing Interview Questions and Answers 2026
- Amazon Leadership Principles Interview Questions & STAR Answers 2026
- Manual Testing Interview Questions for Freshers 2026
These are commonly asked questions with sample answers, not an official list. Hiring processes change, so check the company's careers page for the current one. Jawab AI is not affiliated with any company named here.