Interviews

Java Interview Questions with Answers (2026)

Java interview questions for 2026: 18 real questions with concise answers and code on OOP, collections, the JVM, concurrency, and streams for SDE prep.

O OnJob Editorial· June 4, 2026·11 min read

Java is still the backbone of enterprise backends, Android, and large-scale systems, so it remains one of the most-tested languages in 2026 SDE interviews. The questions reward people who understand how the JVM behaves — memory model, garbage collection, equals/hashCode contracts, concurrency — not just public static void main. Below are 18 real questions, ordered beginner to advanced, each with a concise answer or snippet you can rehearse out loud.

Beginner Java questions

1. What are the four pillars of OOP, and how does Java express each?

  • Encapsulation — private fields plus getters/setters.
  • Inheritanceextends (classes) and implements (interfaces).
  • Polymorphism — method overriding and overloading; one interface, many implementations.
  • Abstraction — abstract classes and interfaces that hide implementation detail.

2. What’s the difference between == and .equals()? == compares references (same object) for objects, and raw values for primitives. .equals() compares logical content, as overridden by the class. new String("a") == new String("a") is false, but .equals() is true.

3. What’s the difference between an abstract class and an interface? An abstract class can hold state (fields), constructors, and a mix of concrete and abstract methods; a class extends only one. An interface declares a contract; a class can implement many. Since Java 8, interfaces can have default and static methods, narrowing the gap — but state still lives in abstract classes.

4. Explain String, StringBuilder and StringBuffer. String is immutable — every modification creates a new object. StringBuilder is mutable and fast but not thread-safe. StringBuffer is mutable and synchronized (thread-safe, slightly slower). Use StringBuilder for loops that build text in a single thread.

5. What is autoboxing? Automatic conversion between primitives and their wrapper objects (intInteger). Convenient, but watch the cache trap: Integer caches −128 to 127, so Integer a = 127, b = 127; a == b is true, but at 128 it’s false. Compare wrappers with .equals().

Intermediate Java questions

6. Walk through the Java Collections hierarchy. Collection splits into List (ordered, duplicates — ArrayList, LinkedList), Set (unique — HashSet, TreeSet, LinkedHashSet), and Queue (ArrayDeque, PriorityQueue). Map (HashMap, TreeMap, LinkedHashMap) is separate — it stores key-value pairs and isn’t a Collection.

7. How does a HashMap work internally? Keys are hashed to a bucket index. Each bucket holds entries; collisions form a linked list, which converts to a balanced tree once a bucket exceeds 8 entries (Java 8+) for O(log n) worst-case lookup. Average get/put is O(1). This is why your key’s hashCode() and equals() must be correct and consistent.

8. Explain the equals() / hashCode() contract. If two objects are equals(), they must return the same hashCode(). Break this and HashMap/HashSet lose entries — an object goes into one bucket but is searched for in another. Always override both together.

9. What’s the difference between checked and unchecked exceptions? Checked exceptions (e.g. IOException) extend Exception and must be declared or caught — the compiler enforces it. Unchecked exceptions (RuntimeException subclasses like NullPointerException) signal programming bugs and aren’t enforced. Error (e.g. OutOfMemoryError) shouldn’t be caught.

10. What does final, finally and finalize each mean? final makes a variable constant, a method non-overridable, or a class non-extendable. finally is the block that always runs after try/catch. finalize() was a deprecated GC hook — don’t use it; prefer try-with-resources.

11. What is try-with-resources?

try (BufferedReader r = new BufferedReader(new FileReader("f.txt"))) {
    return r.readLine();
}   // r.close() called automatically

Any resource implementing AutoCloseable is closed automatically, even on exception — no manual finally needed.

Advanced Java questions

12. Explain the JVM memory model. The heap holds objects (split into young and old generations for GC). Each thread has its own stack for method frames and local variables. The metaspace holds class metadata. OutOfMemoryError usually points to the heap; StackOverflowError to deep/infinite recursion on the stack.

13. How does garbage collection work? The GC reclaims objects no longer reachable from GC roots. Modern collectors (G1, the default since Java 9; ZGC and Shenandoah for low-pause) work generationally — short-lived objects die in the young generation (cheap minor GC), survivors get promoted to the old generation. You never call free(); you make objects unreachable.

14. What’s the difference between Runnable and Callable? Runnable.run() returns nothing and can’t throw checked exceptions. Callable.call() returns a value and can throw checked exceptions; submit it to an ExecutorService and get a Future back to retrieve the result.

15. How do you make a class thread-safe? Options, from coarse to fine: synchronized methods/blocks (mutual exclusion), volatile for visibility of a single flag, java.util.concurrent.atomic classes for lock-free counters, concurrent collections (ConcurrentHashMap), and immutability (the simplest — no shared mutable state means no synchronization).

16. What does volatile guarantee — and not guarantee? volatile guarantees visibility: a write is immediately seen by other threads, preventing stale cached reads. It does not guarantee atomicity — count++ on a volatile is still a race (read-modify-write). For atomic increments use AtomicInteger.

17. Explain Java Streams with an example. The Streams API (Java 8+) processes collections declaratively:

List<String> names = people.stream()
    .filter(p -> p.getAge() > 18)
    .map(Person::getName)
    .sorted()
    .collect(Collectors.toList());

Streams are lazy until a terminal operation (collect, forEach, reduce) runs, and can go parallel with .parallelStream().

18. What’s the difference between HashMap and ConcurrentHashMap? HashMap is not thread-safe — concurrent modification can corrupt it or throw ConcurrentModificationException. ConcurrentHashMap allows concurrent reads and segmented/striped writes without locking the whole map, making it the right choice for shared maps under load. Avoid the old fully-synchronized Hashtable.

How to stand out in a Java interview

The differentiator is JVM-level reasoning. When asked about HashMap, mention the treeify threshold and the equals/hashCode contract. When asked about thread safety, rank the options and pick immutability first. Name trade-offs — StringBuffer is thread-safe but slower; volatile gives visibility but not atomicity. That depth is what earns senior-level scores.

Rehearse out loud, because explaining the JVM memory model is far harder than recognizing it. Practice full Java rounds with OnJob’s AI mock interviews and get a confidence score on your explanations, then create a free account to find matched backend and SDE roles. Pair this with our system design interview guide and data structures interview questions for a full SDE prep loop.

FAQ

What Java topics are most asked in interviews in 2026? OOP principles, collections (especially HashMap internals), the equals/hashCode contract, exception handling, the JVM memory model and garbage collection, concurrency (synchronized, volatile, ConcurrentHashMap, executors), and the Streams API. Backend roles lean harder on concurrency and the JVM.

Which Java version should I prepare against? Know the Java 8 baseline (lambdas, streams, Optional, default interface methods) cold — it’s still the most-referenced feature set. Then be aware of newer LTS additions like records, sealed classes, pattern matching, and virtual threads (Project Loom), which interviewers increasingly probe in 2026.

How do I answer JVM and garbage collection questions well? Explain reachability from GC roots, the generational model (young vs old generation, minor vs major GC), and name a modern collector like G1 or ZGC with its trade-off. Tie it back to symptoms — heap OutOfMemoryError vs stack StackOverflowError — to show you’ve debugged real issues.

Ready to put this into action?

Create your free OnJob profile and let AI match you to jobs you can actually win.

Create my free profile

Free OnJob tools & guides

Related reading

Create my free profile — free