Java Interview Questions for 2 Years Experience: 40 Questions With Answers
Jyoti · 7 Nov 2026 · Career & Interview Prep
Key Takeaways
- Java interview questions for 2 years experience go deeper than fresher rounds: interviewers expect you to explain how things work inside (HashMap, threads, Spring Boot auto-configuration), not just define them.
- Most rounds cover five areas: core Java and OOP, collections, Java 8+ streams, multithreading, and Spring Boot with JPA and SQL. Microservices basics are now common too.
- Expect at least one live coding task, usually a stream or collections problem, plus one SQL query.
- Your own project is the biggest topic. Be ready to draw its flow and explain one bug you fixed in production or testing.
- A focused 4-week plan (one area per week, plus daily coding) is enough for most developers with 2 years of experience.
The most common Java interview questions for 2 years experience are about HashMap internals, equals and hashCode, Java 8 streams, thread safety, Spring Boot annotations and dependency injection, JPA problems like N+1, and SQL joins. Interviewers want short, correct answers backed by an example from your own project.
This guide lists 40 questions with clear answers, the coding problems that show up again and again, a 4-week preparation plan and the mistakes that cost 2-year developers the offer. It is written for Java developers in India moving to their second job, whether at a service company, a product company or a GCC.
Table of Contents
- What Interviewers Expect at 2 Years of Experience
- Core Java and OOP Questions
- Collections and HashMap Questions
- Java 8 and Modern Java Questions
- Multithreading and Concurrency Questions
- Spring Boot and REST API Questions
- JPA, Hibernate and SQL Questions
- Microservices and Project Questions
- Coding Questions You Should Practise
- 4-Week Preparation Plan
- Mistakes That Cost 2-Year Java Developers the Offer
- How My Career Solution Helps
- FAQs
What Do Interviewers Expect from a Java Developer with 2 Years of Experience?
At this level you are no longer judged only on definitions. A fresher can say "HashMap stores key-value pairs". A developer with 2 years of experience is expected to explain buckets, hashing, collisions and why a bad hashCode() slows things down. The interviewer is checking one thing: can you work on a real codebase without close supervision?

The usual interview process for a mid-level Java role in India looks like this:
- Online test or screening call: MCQs on Java and SQL, or a 20-minute call with a recruiter on your stack and notice period.
- Technical round 1: core Java, collections, Java 8, one or two coding problems.
- Technical round 2: Spring Boot, REST, JPA, SQL, your project, sometimes basic microservices and design.
- Managerial or HR round: project ownership, teamwork, reason for change, salary expectations.
Product companies often add a data structures and algorithms round. Service companies and GCCs usually spend more time on Spring Boot and project questions. If the HR round worries you, read our guide to HR interview questions with sample answers; most of those questions are asked to experienced candidates too.
Core Java and OOP Questions
1. Why is String immutable in Java?
Once a String object is created, its value cannot change. This makes Strings safe to share between threads, lets the JVM reuse them from the String pool, keeps the cached hash code valid (important for HashMap keys) and protects values like file paths and URLs from being changed after a security check.
2. String vs StringBuilder vs StringBuffer?
String is immutable. StringBuilder is mutable and not synchronized, so it is the right choice for building strings inside a method. StringBuffer is mutable and synchronized, which makes it slower; it is rarely needed in new code.
3. What is the contract between equals() and hashCode()?
If two objects are equal by equals(), they must return the same hashCode(). The reverse is not required. If you override equals() without hashCode(), HashMap and HashSet will not find your objects correctly.
4. Abstract class vs interface?
An abstract class can have state (fields), constructors and any access modifier. An interface describes a capability; since Java 8 it can have default and static methods, and since Java 9 private methods, but no instance state. A class extends one abstract class but can implement many interfaces.
5. Checked vs unchecked exceptions?
Checked exceptions (like IOException) must be handled or declared. Unchecked exceptions extend RuntimeException (like NullPointerException) and are not checked by the compiler. A good answer adds when you create a custom exception in your project, for example a ResourceNotFoundException mapped to HTTP 404.
6. What is try-with-resources?
A try block that closes any resource implementing AutoCloseable automatically, even when an exception is thrown. It replaces long finally blocks for streams, connections and readers.
7. final vs finally vs finalize?
final stops reassignment, overriding or inheritance. finally runs after try/catch. finalize() was a cleanup hook called by the garbage collector; it is deprecated and should not be used. Mention try-with-resources or Cleaner as the alternatives.
8. Explain the four OOP principles with a project example.
Encapsulation (private fields with getters, setters or validation), inheritance (a base entity class with common audit fields), polymorphism (one PaymentService interface with UPI and card implementations) and abstraction (callers use the interface, not the class). The project example is what makes this answer strong.
Collections and HashMap Questions
Collections is the topic where most 2-year candidates lose marks, because the questions move from "what" to "how it works inside".
9. How does HashMap work internally?
HashMap keeps an array of buckets. For a key, it computes hashCode(), spreads the bits, and finds the bucket index from the array size. Entries with the same index are stored as a linked list in that bucket. On get(), it goes to the bucket and uses equals() to find the right key. The default capacity is 16 and the load factor is 0.75; when the size crosses capacity × load factor, the array doubles and entries are redistributed.

10. What changed in HashMap in Java 8?
When one bucket gets too many entries (8 by default) and the table has at least 64 buckets, the linked list is converted into a balanced red-black tree. That keeps lookups fast even with many collisions. Below 64 buckets, HashMap resizes instead.
11. HashMap vs ConcurrentHashMap vs Hashtable?
HashMap is not thread-safe and allows one null key. Hashtable is synchronized on the whole object, so it is slow, and it does not allow null. ConcurrentHashMap is thread-safe with fine-grained locking (in Java 8, CAS operations and locks on individual bins), so reads and writes from many threads scale well. It also does not allow null keys or values.
12. ArrayList vs LinkedList?
ArrayList is backed by an array: fast random access, and adding at the end is usually fast. LinkedList is a doubly linked list: no fast index access. In practice ArrayList is the better default in almost every case.
13. Fail-fast vs fail-safe iterators?
Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is changed structurally while you iterate, except through the iterator's own remove(). Concurrent collections like CopyOnWriteArrayList and ConcurrentHashMap give weakly consistent iterators that do not throw.
14. Comparable vs Comparator?
Comparable defines the natural order inside the class (compareTo). Comparator defines an order from outside, so you can have many. In Java 8 style: employees.sort(Comparator.comparing(Employee::getSalary).reversed());
Java 8 and Modern Java Questions
15. What is a functional interface?
An interface with exactly one abstract method, such as Runnable, Predicate, Function or Supplier. Lambdas and method references can be used wherever a functional interface is expected. @FunctionalInterface makes the compiler check the rule.
16. Intermediate vs terminal operations in streams?
Intermediate operations (filter, map, sorted) return a new stream and are lazy. Nothing runs until a terminal operation (collect, forEach, count, reduce) is called. A stream can be consumed only once.
17. map vs flatMap?
map converts each element into one element. flatMap converts each element into a stream and flattens all of them into one stream, for example turning a list of orders into a stream of all their items.
18. Write a stream to group employees by department and count them.
Map<String, Long> count = employees.stream().collect(Collectors.groupingBy(Employee::getDept, Collectors.counting())); Be ready for follow-ups: highest salary per department (Collectors.maxBy), or sorting the result.
19. What is Optional and how should you use it?
Optional is a container that may or may not hold a value, mainly for method return types, so callers handle the empty case. Use orElse, orElseThrow or map; avoid calling get() without a check, and do not use Optional for fields or method parameters.
20. What is new in Java 17 and Java 21?
Both are long-term support releases. Java 17 brought records, sealed classes, switch expressions and text blocks as standard features. Java 21 added virtual threads, pattern matching for switch, record patterns and sequenced collections. You do not need every detail, but you should know which version your project runs on and one feature you have used.
Multithreading and Concurrency Questions
21. Runnable vs Callable?
Runnable.run() returns nothing and cannot throw checked exceptions. Callable.call() returns a value and can throw. Submitting a Callable to an ExecutorService gives you a Future to read the result.
22. What does volatile do? Is it enough for a counter?
volatile makes every read see the latest write from other threads (visibility). It does not make count++ atomic, because that is a read, an add and a write. Use AtomicInteger or a lock for counters.
23. synchronized vs ReentrantLock?
synchronized is simpler and releases the lock automatically. ReentrantLock adds tryLock() with a timeout, interruptible locking and fairness options, but you must unlock in a finally block.
24. What is a deadlock and how do you avoid it?
Two threads each hold one lock and wait forever for the other's lock. Avoid it by always taking locks in the same order, using tryLock with timeouts and keeping locked sections small. A thread dump (jstack) shows a deadlock clearly.
25. Why use ExecutorService instead of creating threads?
Thread pools reuse threads, limit how many run at once and give you clean shutdown and result handling. In a Spring Boot project you may also mention @Async with a configured executor, or CompletableFuture to call two services in parallel and combine the results.
Spring Boot and REST API Questions
26. What is dependency injection, and which type do you prefer?
The Spring container creates objects (beans) and gives them their dependencies, so classes do not create them with new. Constructor injection is preferred: dependencies can be final, the class is easy to test, and missing dependencies fail at startup.
27. What does @SpringBootApplication do?
It combines @Configuration, @EnableAutoConfiguration and @ComponentScan. Auto-configuration looks at the classpath and your properties and sets up beans for you, for example a DataSource when a database driver and URL are present.
28. @Component vs @Service vs @Repository vs @Controller?
All register a bean. @Service and @Controller mark the layer for readability. @Repository also translates database exceptions into Spring's DataAccessException. @RestController is @Controller plus @ResponseBody.
29. How do you handle exceptions globally in a REST API?
Use a class with @RestControllerAdvice and methods with @ExceptionHandler that return a consistent error body and the right HTTP status (400 for validation, 404 for not found, 409 for conflicts). Pair it with @Valid on request bodies.
30. How does @Transactional work, and when does it not work?
Spring wraps the bean in a proxy that starts and commits or rolls back a transaction around the method. By default it rolls back on unchecked exceptions only. It does not apply when a method calls another @Transactional method in the same class (self-invocation skips the proxy), and with the default proxy setup it is meant for public methods.
31. What are bean scopes?
Singleton (default, one per container), prototype (new object each time), and web scopes such as request and session. A good follow-up point: singleton beans must not keep per-request state in fields.
32. How do you manage config for dev, QA and prod?
Spring profiles (application-dev.yml, application-prod.yml), environment variables for secrets, and @ConfigurationProperties for typed config. Never commit passwords to the repository.
JPA, Hibernate and SQL Questions
33. What is the N+1 query problem?
You load a list of N parent rows with one query, then a lazy collection on each parent fires one more query per row, so you run N+1 queries. Fix it with a fetch join (JOIN FETCH), @EntityGraph or batch fetching, and check the SQL logs to prove it.
34. Lazy vs eager loading?
Lazy loads related data only when you access it; eager loads it with the parent. In JPA, @OneToMany is lazy by default and @ManyToOne is eager by default. Accessing a lazy field after the session is closed gives LazyInitializationException.
35. Write a query for the second highest salary.
SELECT MAX(salary) FROM employee WHERE salary < (SELECT MAX(salary) FROM employee); Also know the window function version with DENSE_RANK(), which handles "Nth highest" and ties cleanly.
36. When does an index help, and when does it hurt?
An index speeds up searches, joins and sorting on the indexed columns. It slows down inserts and updates, takes space, and is often not used when you wrap the column in a function or start a LIKE pattern with a wildcard. Mention EXPLAIN to check the query plan.
Microservices and Project Questions
Not every 2-year role uses microservices, but many interviewers ask the basics. If you have only worked on a monolith, say so and show you understand the ideas.
37. How do microservices talk to each other?
Synchronously over REST (with RestTemplate, WebClient or Feign) or asynchronously with a message broker such as Kafka or RabbitMQ. An API gateway sits in front, and service discovery or Kubernetes services help one service find another.
38. What is a circuit breaker?
When a downstream service keeps failing, the circuit breaker stops calling it for a while and returns a fallback, so failures do not spread. Resilience4j is the common library in Spring Boot projects.
39. Explain your current project.
Use a 2-minute structure: what the product does and who uses it, the tech stack, your modules, one problem you solved and the result. Draw the request flow (client, controller, service, repository, database, other services) if a whiteboard or screen share is available.
40. Tell us about a production bug you fixed.
Pick a real one: the symptom, how you found it (logs, thread dump, SQL log, a failing test), the fix and what you changed so it would not happen again. This answer shows the experience a 2-year developer is hired for.
Coding Questions You Should Practise
Live coding for 2-year Java roles is usually practical, not puzzle-heavy. Practise these until you can write them cleanly in 10 to 15 minutes, using both loops and streams where it fits:

- Find duplicate elements in a list, and the frequency of each character in a string, using streams.
- First non-repeated character in a string.
- Reverse each word of a sentence, and check whether two strings are anagrams.
- Group employees by department and find the highest-paid employee in each.
- Two-sum and checking balanced brackets with a stack.
- Implement an LRU cache (a
LinkedHashMapwith access order andremoveEldestEntryis an accepted answer; know the HashMap plus doubly linked list version too). - A thread-safe singleton, and a producer-consumer with a
BlockingQueue. - A small REST endpoint: a controller, a service and a repository for one entity, with validation and an error handler.
Speak while you code: state the approach, the time complexity and the edge cases (empty input, nulls, duplicates) before you start typing.
4-Week Preparation Plan
If you are working full time, 1.5 to 2 hours a day is enough. Keep one area per week and solve 2 coding problems every day.

| Week | Focus | Output by end of week |
|---|---|---|
| Week 1 | Core Java, OOP, exceptions, collections, HashMap internals | You can explain HashMap and equals/hashCode without notes |
| Week 2 | Java 8 streams, Optional, Java 17/21 features, multithreading | 10 stream programs written from memory |
| Week 3 | Spring Boot, REST, @Transactional, JPA, SQL queries | A small CRUD API with global error handling, plus 15 SQL queries |
| Week 4 | Your project, microservices basics, 2-3 mock interviews | A 2-minute project pitch and one bug story you can tell clearly |
Before you start applying, update your resume so it shows your Java and Spring Boot work with results, not just a list of tools. Our resume format guide for software developers and the ATS-friendly resume checklist both apply to 2-year developers too.
Mistakes That Cost 2-Year Java Developers the Offer
- Textbook answers with no example. "Dependency injection means loose coupling" is not enough. Add how your project wires a service.
- Listing tools you cannot explain. If Kafka, Docker or Redis is on your resume, expect deep questions on it.
- Weak SQL. Many Java developers rely on JPA and forget joins, GROUP BY and window functions.
- Not knowing your own project. You should know the database tables you touched, the main APIs and how the app is deployed.
- Silent coding. Interviewers score your thinking. Explain before and while you write code.
- Vague reason for change. Keep it positive: better tech stack, more ownership, product work. Do not criticise your current company.
If you are preparing well but still not getting calls for Java roles, the problem is usually earlier in the funnel. Read why you are not getting interview calls for the 10 common reasons and fixes.
How My Career Solution Helps
Preparation matters only when you have interviews lined up. My Career Solution (MCS) works on that part:
- Free start: when you sign up, MCS applies for you to 5 companies for free, so your profile reaches recruiters straight away.
- Guaranteed interview calls: our MCS packages come with a guaranteed number of interview calls based on the package you choose.
- Real openings: browse current Java and other IT jobs and see which companies are hiring, with ratings and open roles.
Targeting product companies for your next switch? See our list of product based companies in India and their hiring process. You can also read what other candidates say on the MCS reviews page.
FAQs
What Java topics are asked for 2 years experience?
Core Java and OOP, collections (especially HashMap internals), Java 8 streams and Optional, multithreading basics, Spring Boot (dependency injection, annotations, REST, exception handling, @Transactional), JPA and Hibernate (N+1, lazy loading), SQL queries and your own project. Microservices basics are asked in many companies too.
Is DSA asked for a Java developer with 2 years of experience?
Product companies usually have a DSA round with arrays, strings, hashing, linked lists and trees. Service companies and many GCCs ask simpler coding problems on strings, collections and streams. Prepare easy to medium problems either way.
How should I explain my project in a Java interview?
Give a 2-minute overview: what the product does, the tech stack, the modules you owned, one hard problem you solved and the result. Then be ready to go deeper into any API, table or bug you mention.
Which Java version should I prepare for?
Know Java 8 features very well because streams and lambdas are asked everywhere, and learn the main features of Java 17 and Java 21, which are the recent long-term support versions. Say clearly which version your current project uses.
How long does it take to prepare for a Java interview with 2 years of experience?
Around 4 weeks of steady preparation (1.5 to 2 hours a day) is enough for most developers who already work in Java daily. Spend the most time on collections, streams, Spring Boot and your project, and do a few mock interviews in the last week.
Ready for your next Java role? Check MCS packages for guaranteed interview calls, or sign up on My Career Solution and get your first 5 applications sent free. More guides on the MCS blog.
Frequently asked questions
What Java topics are asked for 2 years experience?
Core Java and OOP, collections (especially HashMap internals), Java 8 streams and Optional, multithreading basics, Spring Boot (dependency injection, annotations, REST, exception handling, @Transactional), JPA and Hibernate (N+1, lazy loading), SQL queries and your own project. Microservices basics are asked in many companies too.
Is DSA asked for a Java developer with 2 years of experience?
Product companies usually have a DSA round with arrays, strings, hashing, linked lists and trees. Service companies and many GCCs ask simpler coding problems on strings, collections and streams. Prepare easy to medium problems either way.
How should I explain my project in a Java interview?
Give a 2-minute overview: what the product does, the tech stack, the modules you owned, one hard problem you solved and the result. Then be ready to go deeper into any API, table or bug you mention.
Which Java version should I prepare for?
Know Java 8 features very well because streams and lambdas are asked everywhere, and learn the main features of Java 17 and Java 21, which are the recent long-term support versions. Say clearly which version your current project uses.
How long does it take to prepare for a Java interview with 2 years of experience?
Around 4 weeks of steady preparation (1.5 to 2 hours a day) is enough for most developers who already work in Java daily. Spend the most time on collections, streams, Spring Boot and your project, and do a few mock interviews in the last week.