Skip to main content
Interview Prep

Java Interview Questions 2026: Freshers to 10 Years, Answers, Coding Rounds and Interview Pattern

Java interview guide for freshers to 10-year candidates: the round pattern at service and product companies, core and Java 8 to 21 questions with expected answers, collections, concurrency, JVM, Spring, and coding problems.

Published 45 min read
Share

How to use this guide

This guide covers Java interviews from fresher level to about ten years of experience. It follows the order most interviews use: an aptitude or MCQ round for freshers, core Java, collections and concurrency, Java 8 and later features, the JVM, then Spring, databases and system design for experienced candidates. Each question has the answer an interviewer expects, not just a definition. Read the section for your level, then the sections above it, because senior interviews keep returning to the fresher basics.

The question patterns come from the public Java prep material that candidates use, combined with the standard expectations of service-based and product-based hiring. Most of the public material is generic, so the answers here are written to the depth that interviewers look for. Companies change their processes often, so treat the round structure as typical, not guaranteed.

What the interview pattern usually looks like

Service-based companies (TCS, Infosys, Wipro, HCL, Accenture and similar) often run three stages. The first is an online test with aptitude, reasoning and a set of MCQs, usually with 8 to 12 Java-specific questions out of 20 to 30. The second is a technical interview on core Java, OOP, collections, exceptions and a project. The third is an HR round.

Product companies (Google, Microsoft, Visa and similar) usually ask two to four coding rounds on data structures and algorithms, one or two rounds on Java and object-oriented design, and a system design round for experienced candidates. Java-specific questions are often about collections, concurrency and the JVM, and the coding is written in Java.

Experienced candidates at five to ten years are tested on design decisions, production problems, memory and performance, Spring and REST, databases, and how they lead or review work. Expect "why" questions, not only "what" questions.

Level 1: Core Java for freshers

Q1. What are the four pillars of OOP? Encapsulation, abstraction, inheritance and polymorphism. Encapsulation hides data behind getters and setters. Abstraction shows only what is needed, through abstract classes and interfaces. Inheritance reuses code from a parent class. Polymorphism lets one method name behave differently by object type, through overriding (runtime) or overloading (compile time).

Q2. What is the difference between an abstract class and an interface? An abstract class can have constructors, instance fields, and both abstract and concrete methods. A class can extend only one abstract class. An interface defines a contract. A class can implement many interfaces. Since Java 8 an interface can have default and static methods, and since Java 9 it can have private methods. Use an abstract class when classes share state and behaviour; use an interface when unrelated classes must share a capability.

Q3. What is the difference between == and equals()? == compares references for objects and values for primitives. equals() compares the logical content, if the class overrides it. For String, "abc" == new String("abc") is false, but equals returns true. Always override hashCode() along with equals().

Q4. What is the difference between String, StringBuilder and StringBuffer? String is immutable, so every change creates a new object. StringBuilder is mutable and not thread-safe, and is the default choice for building strings in a single thread. StringBuffer is mutable and synchronised, so it is slower and used only when several threads share the builder.

Q5. Why are strings immutable in Java? Immutability makes strings safe to share, safe as HashMap keys (the hash does not change), and safe for security-sensitive values such as class names and file paths. It also allows the JVM to cache them in the string pool.

Q6. What is the difference between checked and unchecked exceptions? Checked exceptions extend Exception but not RuntimeException. The compiler forces you to handle or declare them, for example IOException. Unchecked exceptions extend RuntimeException, for example NullPointerException or IllegalArgumentException, and are not forced by the compiler.

Q7. What do final, finally and finalize do? final makes a variable a constant, stops a method being overridden, or stops a class being extended. finally is a block that runs after try and catch, whether or not an exception occurred, and is used for cleanup. finalize() is a method the garbage collector may call before reclaiming an object. It is deprecated, so do not use it for cleanup; use try-with-resources instead.

Q8. What is the difference between throw and throws? throw raises an exception inside a method. throws declares, in the method signature, the exceptions the method might raise.

Q9. What is method overloading and method overriding? Overloading means the same method name with different parameter lists in the same class, resolved at compile time. Overriding means a subclass gives its own version of an inherited method with the same signature, resolved at runtime through dynamic dispatch.

Q10. What is the static keyword? A static member belongs to the class, not to an instance. Static fields are shared by all objects. Static methods cannot access instance members directly. Static blocks run once, when the class loads.

Q11. What is the difference between this and super? this refers to the current object. super refers to the parent class, used to call the parent constructor or an overridden method.

Q12. Can a constructor be private? Yes. A private constructor stops other classes creating instances. It is used in singletons and in utility classes.

Level 2: Collections framework

Collections are the most common Java topic at every level, especially in service-based MCQ rounds and product interviews.

Q13. What is the difference between List, Set and Map? A List is ordered and allows duplicates. A Set has no duplicates. A Map stores key-value pairs with unique keys.

Q14. What is the difference between ArrayList and LinkedList? ArrayList is backed by an array. Reading by index is O(1), and adding at the end is usually O(1), but inserting in the middle needs shifting. LinkedList is a doubly linked list. Inserting or removing at a known node is O(1), but reading by index is O(n). In practice ArrayList is faster for most workloads because of memory locality.

Q15. How does HashMap work internally? The map keeps an array of buckets. The key's hashCode() is spread and used to pick a bucket index. Each bucket holds a linked list of entries. When two keys land in the same bucket, that is a collision, and equals() decides whether a key is already present. Since Java 8, when a bucket has eight or more entries and the table has at least 64 buckets, the bucket becomes a balanced tree, which keeps the worst case at O(log n). The default load factor is 0.75: when the map is 75 percent full, it doubles its size and rehashes.

Expect a follow-up: "What happens if two keys have the same hash code?" The answer is that they share a bucket, and equals() tells them apart.

Q16. What is the difference between HashMap and Hashtable? Hashtable is synchronised on every method, so it is slow and considered legacy. It also does not allow null keys or values. HashMap is not synchronised and allows one null key and many null values. For concurrent use, prefer ConcurrentHashMap.

Q17. What is ConcurrentHashMap? A thread-safe map that locks only part of the table, so many threads can read and write at once. Since Java 8, it uses compare-and-swap for most updates and synchronises only the bucket that is being changed.

Q18. What is the difference between HashSet and TreeSet? HashSet uses a hash table, so it has no order and O(1) average operations. TreeSet uses a red-black tree, so it keeps elements sorted, with O(log n) operations.

Q19. How do you make a collection immutable? Use Collections.unmodifiableList for a view of an existing list, or List.of, Set.of and Map.of from Java 9 onwards for true immutable collections. Immutable collections reject null elements in the List.of and Set.of factories.

Q20. What is the difference between Comparable and Comparator? Comparable gives a class its natural order by implementing compareTo. Comparator is a separate object that defines an order, and it can be passed to sort. Use Comparator when you need several orders for the same class.

Q21. Why should hashCode() be overridden with equals()? If two objects are equal by equals(), they must return the same hashCode(). If not, a HashSet or HashMap can store two "equal" objects in different buckets, which breaks the contract.

Level 3: Java 8 and later

Q22. What are lambda expressions? A short way to write an implementation of a functional interface, an interface with one abstract method. Example: list.forEach(x -> System.out.println(x));.

Q23. What is the Stream API? A pipeline for processing sequences of data: source, zero or more intermediate operations such as filter and map, then a terminal operation such as collect or count. Streams are lazy: nothing runs until the terminal operation starts.

Q24. What is Optional? A container that may or may not hold a value. It is used to avoid returning null from methods. Call orElse, orElseGet or orElseThrow rather than get() without a check.

Q25. What is the difference between map and flatMap in streams? map transforms each element one to one. flatMap transforms each element into a stream and then flattens the result into a single stream.

Q26. What are records and sealed classes? A record (Java 16 onwards) is a concise class for immutable data, with a constructor, getters, equals, hashCode and toString generated. A sealed class (Java 17 onwards) restricts which classes can extend it, which helps with exhaustive switch expressions.

Q27. What is a functional interface? An interface with exactly one abstract method. Examples are Runnable, Comparator, Predicate and Function. The @FunctionalInterface annotation checks this at compile time.

Level 4: Multithreading and concurrency

Q28. What is the difference between a process and a thread? A process has its own memory space. Threads inside the same process share memory and resources, so switching between threads is cheaper.

Q29. How do you create a thread in Java? Extend Thread or implement Runnable and pass it to a Thread. Prefer Runnable, or Callable when a result is needed, since Java does not allow multiple inheritance of classes.

Q30. What is the difference between start() and run()? start() creates a new thread and calls run() on it. Calling run() directly just runs the method on the current thread, with no concurrency.

Q31. What is synchronized? A keyword that makes a method or block thread-safe by locking on an object's monitor, so only one thread can enter at a time. It guarantees visibility of changes as well as mutual exclusion.

Q32. What is the difference between volatile and synchronized? volatile makes writes visible to all threads, but does not make compound actions such as count++ atomic. synchronized gives both visibility and atomicity for the block it guards.

Q33. What is a deadlock, and how do you avoid it? A deadlock is when two or more threads each hold a lock the other needs, so none can continue. Avoid it by acquiring locks in a fixed order, by using timeouts with tryLock, or by keeping locked sections short.

Q34. What is the ExecutorService? A framework for managing a pool of threads, so you submit tasks rather than create threads by hand. Creating a fixed thread pool, submitting tasks and calling shutdown is the usual pattern.

Q35. What are virtual threads? Introduced as a stable feature in Java 21, virtual threads are lightweight threads managed by the JVM. They make it practical to run many blocking tasks, such as one per request, without a large thread pool.

Level 5: JVM and memory

Q36. Explain the JVM memory areas. The heap holds objects and is shared by all threads, and garbage collection works here. The stack holds method frames and local variables for each thread. The metaspace holds class metadata, and since Java 8 it lives outside the heap. The program counter register and the native method stack are the other areas.

Q37. What is garbage collection? An automatic process that frees heap memory used by objects with no live references. Common collectors include G1, which is the default since Java 9, and ZGC, which aims for very short pauses.

Q38. What causes a StackOverflowError and an OutOfMemoryError? A StackOverflowError usually comes from deep or infinite recursion. An OutOfMemoryError means the heap or metaspace is full, often because of a memory leak, such as objects kept in a static collection that is never cleared.

Q39. What is the difference between JDK, JRE and JVM? The JVM runs bytecode. The JRE is the JVM plus the standard libraries needed to run a program. The JDK is the JRE plus development tools such as the compiler.

Q40. What is class loading? The JVM loads classes on demand through class loaders: bootstrap, platform and application. A parent-first delegation model is used, which is why you cannot replace core classes such as String by putting a class with the same name on the classpath.

Level 6: Spring, REST and databases (2 to 6 years)

Q41. What is dependency injection? A design pattern where an object receives its dependencies from outside rather than creating them. In Spring the container creates beans and injects them, usually through constructor injection, which is the recommended style because it makes dependencies explicit and easier to test.

Q42. What is the difference between @Component, @Service and @Repository? All three register a bean. @Service marks business logic, @Repository marks data access and translates database exceptions, and @Component is the generic form.

Q43. What is the difference between @RestController and @Controller? @RestController combines @Controller and @ResponseBody, so return values are written directly to the response body, usually as JSON.

Q44. What is Spring Boot? A layer over Spring that sets up configuration automatically, provides embedded servers and starter dependencies, so that a service can run with little setup.

Q45. What is the difference between REST and SOAP? REST uses HTTP methods and resources, with JSON as the common format, and it is stateless. SOAP is a protocol with a strict XML contract and its own standards for security and transactions.

Q46. What is the N+1 query problem in JPA? Loading a list of parents and then lazily loading a child collection for each parent runs one query for the list and one more per parent. Fix it with a fetch join, an entity graph, or batch fetching.

Q47. What is the difference between get() and load() in Hibernate? get() returns null if the entity is not found and hits the database immediately. load() returns a proxy and throws an exception when a missing entity is first accessed.

Q48. What is the difference between a clustered and a non-clustered index? A clustered index sets the physical order of rows in the table, and a table has only one. A non-clustered index is a separate structure that points to the rows, and a table can have many.

Q49. What are ACID properties? Atomicity, consistency, isolation and durability: a transaction completes fully or not at all, keeps the data valid, does not interfere with other transactions, and survives a crash once committed.

Level 7: Experienced design and production questions (6 to 10 years)

Q50. How would you investigate a Java service that is slowing down in production? Start with metrics: CPU, heap, GC pause times, thread count and response times. Take a thread dump with jstack to find blocked or waiting threads, a heap dump with jmap if memory grows, and use a profiler or APM to see slow calls. Check connection pool usage and slow queries. Change one thing at a time and measure.

Q51. How do you design a service to handle a large spike in traffic? Describe the path: a load balancer, horizontally scaled stateless instances, caching for hot reads, asynchronous queues for work that can wait, rate limiting, connection pool sizing, and autoscaling with a clear limit. Name the trade-offs: consistency against latency, and cost against headroom.

Q52. How would you avoid a memory leak in a long-running Java application? Look for objects held by static fields, unbounded caches, listeners that are never removed, and thread-local values that are not cleared. Use weak references or a bounded cache where the lifetime is not clear.

Q53. When would you choose microservices over a monolith? When teams need to deploy independently, parts of the system scale very differently, or domains are clearly separate. Otherwise a well-structured monolith is simpler to run. Interviewers want a reasoned answer, not a default one.

Q54. How do you make an API backward compatible? Add fields rather than remove them, version the API when a change breaks clients, keep old endpoints for a deprecation period, and write contract tests against the consumers.

Q55. What is the difference between optimistic and pessimistic locking? Optimistic locking assumes conflicts are rare and checks a version field on update. Pessimistic locking locks the row at read time, which is safer under heavy contention but reduces throughput.

Coding questions asked in Java rounds

These are the kinds of problems asked in fresher and experienced rounds. Write each in a clean method, explain the approach, and state the time complexity.

C1. Check whether a string is a palindrome. Use two pointers from each end, or compare with a reversed StringBuilder. Time O(n), space O(1) for the two-pointer version.

C2. Find the factorial of a number. An iterative loop is safer than recursion for large inputs, because recursion can overflow the stack. Use long and mention that long overflows past 20!.

C3. Find the first non-repeating character in a string. Count characters in a LinkedHashMap or an array of 256, then scan the string for the first count of one. Time O(n).

C4. Find the two numbers in an array that add to a target. Use a HashMap from value to index. Time O(n), space O(n).

C5. Reverse a linked list. Iterate with three pointers: previous, current and next. Time O(n), space O(1).

C6. Find the top K frequent elements. Count with a HashMap, then use a min-heap of size K with PriorityQueue. Time O(n log k).

How to answer 'explain a project'

Interviewers at every level ask about your project. Structure the answer as: the problem, your role, the design, one hard problem and how you solved it, and the measurable result. Name the Java version, the frameworks and the database. If you used a pattern such as a factory or a strategy, say why it fitted the problem, not only that you used it.

Common mistakes

  • Memorising definitions without examples. Interviewers follow up with "show me where you used it".
  • Confusing equals with ==. Fix this before any interview.
  • Ignoring the JVM. Mid-level and senior roles test memory and GC basics.
  • Not stating complexity. Say the Big O for each answer you give.
  • Skipping tests. Mention unit tests with JUnit and Mockito in your project answers.

A four-week preparation plan

  • Week 1: Core Java, OOP, strings, exceptions and the MCQ patterns. Practise 30 MCQs a day.
  • Week 2: Collections, HashMap internals and Java 8 streams. Solve 10 coding problems.
  • Week 3: Concurrency, the JVM and memory. Explain each topic aloud, as if to a colleague.
  • Week 4: Spring Boot, REST, JPA, and two mock interviews. Write a two-minute project summary.

Frequently asked questions

Is Java still a good choice for freshers? Yes. Java is used widely in enterprise, banking and large product companies, and the core concepts in this guide carry over to most backend roles.

Which version of Java should I know? Know Java 8 features well, because they are the most common, and be able to name the main features of Java 17 and Java 21, such as records, sealed classes and virtual threads.

Do I need to know Spring for a fresher role? Often you need the basics: what dependency injection is, what a REST controller does, and how a simple Spring Boot project runs. Deep Spring knowledge is more often expected at three years and above.

How many coding problems should I practise? For fresher product roles, 100 to 150 problems across arrays, strings, linked lists, trees and hashing is a realistic target. For service-based roles, focus on the Java basics and MCQs.

Can I rely on questions from one website? No. Use this guide for structure and depth, then check the current process for each company, because test formats and question banks change.

Frequently Asked Questions

Yes. Java is used widely in enterprise, banking and large product companies, and the core concepts carry over to most backend roles.

Know Java 8 features well, and be able to name the main features of Java 17 and Java 21, such as records, sealed classes and virtual threads.

Often you need the basics: dependency injection, a REST controller and a simple Spring Boot project. Deep Spring knowledge is more often expected from three years and above.

For fresher product roles, 100 to 150 problems across arrays, strings, linked lists, trees and hashing is a realistic target. For service-based roles, focus on Java basics and MCQs.

No. Use this guide for structure and depth, then check the current process for each company, because formats and question banks change.

KS
· Founder and Editor

Keshav founded StudentUpdate.in and edits every recruitment notice, syllabus page and practice set the site publishes. Each notice is read from the issuing body's PDF or portal before it goes live; dates, fees, vacancy tables and eligibility rules are copied from that document, not from other websites.

Share