---
title: Java Interview Questions: 40 Answers for Java 8 to 27
url: https://www.masaischool.com/resources/java-interview-questions
description: 40 Java interview questions with model answers: OOP, collections, concurrency, Java 8 coding, records, virtual threads, JVM. LTS table checked 11 Nov 2026.
updated: 2026-11-17
publisher: Masai (https://www.masaischool.com)
---

# Java Interview Questions and Answers: 40 Model Answers from Java 8 to Java 27

> **Short answer**
>
> Java interviews test language basics, object-oriented design, collections, strings, exceptions, concurrency, Java 8 and later features, the JVM and coding problems. As of 11 November 2026 the LTS releases are Java 8, 11, 17, 21 and 25, and Java 27 is the newest release. These 40 answers name the Java version behind each feature.

This page is for students, freshers and working developers in India preparing for Java rounds. Each answer names the release that introduced a feature, shown as **Java N**. Facts were checked on 11 November 2026 against the [Oracle Java SE Support Roadmap](https://www.oracle.com/java/technologies/java-se-support-roadmap.html) (updated 20 October 2026), openjdk.org JEP and release pages, the Java Language Specification and the Java 25 documentation.

Java snippets were proofread by eye, not compiled, because no Java compiler was available when this page was written. For a framework round, use the [40 Spring Boot interview questions](https://www.masaischool.com/resources/spring-boot-interview-questions) or Masai's shorter [Common Spring Boot Interview Questions and Tips](https://www.masaischool.com/blog/common-spring-boot-interview-questions-tips/). For language gaps, start with [Java syntax basics](https://www.masaischool.com/resources/java-syntax-basics).

## Which Java version to prepare for

| Release | Type and date | Oracle Premier Support | What to know for interviews |
|---|---|---|---|
| Java 8 | LTS, March 2014 | Ended March 2022 (Extended to December 2030) | Lambdas, streams, Optional, default methods, java.time. Common in older codebases |
| Java 11 | LTS, September 2018 | Ended September 2023 (Extended to January 2032) | String helpers such as isBlank(), the standard HttpClient |
| Java 17 | LTS, September 2021 | Ended September 2026 (Extended to September 2029) | Records, sealed classes, text blocks, switch expressions |
| Java 21 | LTS, September 2023 | Until September 2028 (Extended to September 2031) | Virtual threads, pattern matching for switch, record patterns |
| Java 25 | LTS, September 2025 | Until September 2030 (Extended to September 2033) | Scoped values, flexible constructor bodies, compact object headers |
| Java 26 and 27 | Non-LTS, March and September 2026 | Six months each | Java 27 (released 15 September 2026) is the newest and makes G1 the default collector everywhere |

These are Oracle's commercial support dates; other vendors publish their own. The next LTS is Java 29 (September 2027), and Java 28 is in development. With no named version, prepare on Java 17 or 21 and know Java 8 features cold.

## Language, OOP, collections, strings and exceptions (Q1 to Q18)

### Language basics

- **Q1. What are the JDK, JRE and JVM?** The JVM runs bytecode. The JRE is the JVM plus the standard libraries. The JDK adds tools such as javac and jcmd. Install a JDK to build and run.
- **Q2. Is Java pass by value or by reference?** Always by value (JLS 8.4.1). For an object the value is a reference, so a method can change the object's fields but cannot repoint the caller's variable.
- **Q3. == versus equals(), and the Integer cache?**== compares primitives by value and references by identity. equals() compares content where overridden, as in String. Integer.valueOf always caches -128 to 127, so two boxed 1000s can fail ==.
- **Q4. What do final, finally and finalize mean?**final blocks reassignment, overriding or subclassing. finally runs after try and catch, even on return, unless the JVM exits. finalize() was deprecated for removal in **Java 18** (JEP 421).

### Object-oriented programming

- **Q5. Overloading or overriding?** Overloading is the same name with different parameters, resolved at compile time. Overriding is a subclass replacing an inherited instance method, resolved at run time from the real class. Static methods are hidden, not overridden.
- **Q6. Abstract class or interface?** A class extends one class but implements many interfaces. Abstract classes can hold state and constructors. Interfaces gained default and static methods in **Java 8** and private methods in **Java 9**.
- **Q7. What is the equals() and hashCode() contract?** Equal objects must have equal hash codes, and equals() must be reflexive, symmetric, transitive and consistent. Override both, or HashMap cannot find your keys.
- **Q8. How do you make a class immutable?** Make it final with private final fields, no setters, and defensive copies of mutable inputs and outputs. String and LocalDate work this way. A record (**Java 16**) does it in one line, but a List component stays mutable. See the [OOP explainer](https://www.masaischool.com/resources/object-oriented-programming-explained).

### Collections

- **Q9. ArrayList or LinkedList?**ArrayList is a resizable array: O(1) reads, amortised O(1) append, O(n) middle insert. LinkedList is doubly linked: O(1) at the ends, O(n) to reach an element. Default to ArrayList.
- **Q10. How does HashMap work?** An array of buckets, 16 by default. hashCode() picks the bucket, equals() finds the entry, and the table doubles past a 0.75 load factor. Since **Java 8**, adding to a bucket that already holds 8 or more nodes converts it to a red-black tree if the table has 64 or more buckets, otherwise the table resizes. See [HashMap explained](https://www.masaischool.com/resources/hashmap-explained).
- **Q11. HashMap, Hashtable or ConcurrentHashMap?**HashMap is unsynchronised and permits one null key. Hashtable is a legacy class with synchronised methods. ConcurrentHashMap allows concurrent updates without locking the whole map and rejects null keys and values.
- **Q12. HashMap, LinkedHashMap or TreeMap, and what is fail-fast?** They give no order, insertion order and sorted keys (O(log n)). Their iterators are fail-fast: changing the structure mid-iteration throws ConcurrentModificationException, on a best-effort basis. Use the iterator's remove or removeIf.

### Strings

- **Q13. Why is String immutable, and what is the string pool?** Immutability makes strings safe as map keys and across threads. Literals are interned, so equal literals share one instance, while new String("a") makes a separate object.
- **Q14. String, StringBuilder or StringBuffer?** Use StringBuilder to build text in a loop on one thread. StringBuffer is the older synchronised version. Since **Java 9**, plain + compiles to invokedynamic (JEP 280).
- **Q15. Which String features came after Java 8?Java 11** added isBlank(), strip(), lines() and repeat(int). **Java 15** made text blocks final and added formatted(). strip() follows Character.isWhitespace, so prefer it to trim().

### Exceptions

- **Q16. Checked or unchecked exceptions?** Unchecked ones are RuntimeException, Error and their subclasses. Every other Throwable is checked, and the compiler makes you catch or declare it. Use checked exceptions for failures a caller can recover from.
- **Q17. How does try-with-resources work?** An AutoCloseable declared in the parentheses is closed automatically, in reverse order, even after an exception. If the body and close() both throw, the body's exception wins and the other is suppressed.
- **Q18. What are good exception-handling habits?** Catch the most specific type, never swallow an exception silently, wrap with the cause, and do not catch Throwable. Since **Java 15**, NullPointerException messages name the null part, such as 'because "a.b" is null'.

## Concurrency, modern Java and the JVM (Q19 to Q33)

### Multithreading and concurrency

- **Q19. What are the thread states, and Runnable versus Callable?**Thread.State has NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED. Runnable.run() returns nothing; Callable.call() returns a value and may throw. Call start(), not run().
- **Q20. What do synchronized, volatile and ReentrantLock do?**synchronized gives mutual exclusion and visibility. volatile gives visibility and ordering for one variable, not atomicity, so count++ is still unsafe. ReentrantLock adds timed and interruptible locking.
- **Q21. What is a deadlock?** Each of two or more threads holds a lock another needs, so none proceeds. Prevent it by locking in one global order or using tryLock with a timeout. Diagnose with jcmd <pid> Thread.print.
- **Q22. Why use ExecutorService, and what is CompletableFuture?** Pools reuse threads and bound concurrency, and need shutdown(). CompletableFuture (**Java 8**) chains asynchronous steps with thenApply, thenCompose and thenCombine and handles errors with exceptionally.
- **Q23. What are virtual threads?** Cheap threads (JEP 444, final in **Java 21**) that the JDK schedules onto a few platform threads. Use one per task for blocking I/O, never pool them, and expect no gain for CPU-bound work. **Java 24** (JEP 491) removed most pinning of the carrier thread by synchronized. ScopedValue (**Java 25**) is a lighter ThreadLocal.
// Java 21 and later: one virtual thread per task (from JEP 444) try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { IntStream.range(0, 10_000).forEach(i -> { executor.submit(() -> { Thread.sleep(Duration.ofSeconds(1)); return i; }); }); } // close() waits for the submitted tasks

### Java 8 and later features

- **Q24. What are lambdas and functional interfaces?** A lambda (**Java 8**) is a short function for any interface with one abstract method, and @FunctionalInterface makes the compiler check that. Core types are Function, Predicate, Consumer and Supplier. Captured locals must be effectively final.
- **Q25. How do streams work?** A stream (**Java 8**) is a lazy pipeline: filter and map run only when a terminal step such as collect starts, and a stream is consumed once. Avoid side effects and measure before parallel(). Stream.toList() (**Java 16**) is unmodifiable.
- **Q26. How should you use Optional?** As a return type for 'no result', not a field or parameter. Prefer map, orElseGet and orElseThrow() (**Java 10**) to get(). **Java 9** added ifPresentOrElse, or and stream(), and **Java 11** added isEmpty().
- **Q27. What replaced Date and Calendar?** The java.time package (**Java 8**, JEP 150): LocalDate, ZonedDateTime, Instant and Duration. Its classes are immutable and thread-safe.
- **Q28. What are records, sealed classes and pattern matching?** A record (**Java 16**) is a final data carrier with generated accessors, equals, hashCode and toString. Sealed classes (**Java 17**) list permitted subclasses. Pattern matching: instanceof in **Java 16**, switch and record patterns in **Java 21**.
// Java 21: sealed type, records, pattern matching for switch and a record pattern sealed interface Shape permits Circle, Rect { } record Circle(double r) implements Shape { } record Rect(double w, double h) implements Shape { } static double area(Shape s) { return switch (s) { // exhaustive: no default needed case Circle c -> Math.PI * c.r() * c.r(); case Rect(double w, double h) -> w * h; }; }

- **Q29. What are var, switch expressions and preview features?**var (**Java 10**) infers local types, and switch expressions (**Java 14**) return a value. Preview features need --enable-preview and may change. In Java 27, structured concurrency, lazy constants and primitive patterns are still previews.

### JVM and memory

- **Q30. What are the JVM memory areas?** The heap (shared, holds all objects), a stack per thread, the method area (class data), program counters and native stacks. Since **Java 8**, class metadata lives in native-memory Metaspace, not the permanent generation (JEP 122).
- **Q31. How does garbage collection work, and which collectors exist?** The JVM frees objects not reachable from roots such as thread stacks and static fields. HotSpot offers Serial, Parallel, G1 and ZGC. G1 has been the server default since **Java 9** and is the default everywhere in **Java 27** (JEP 523).
- **Q32. How do you find a memory leak?** A leak is an object still reachable but no longer needed, often in a static map, cache or ThreadLocal. Use -XX:+HeapDumpOnOutOfMemoryError or jcmd <pid> GC.heap_dump, open the dump in [Eclipse Memory Analyzer](https://eclipse.dev/mat/) and follow the path to the GC root.
- **Q33. What do class loading and the JIT compiler do?** Class loaders load, link and initialise classes on first use, asking a parent loader first. The JVM starts by interpreting bytecode and compiles hot methods to machine code while the program runs.

## Java 8 coding interview questions (Q34 to Q40)

Interviewers use these to see whether you can write streams instead of loops and explain the cost. Say the complexity and follow a fixed routine such as Masai's [7-step approach to coding problems](https://www.masaischool.com/blog/7-step-approach-to-solve-any-coding-problem-important-for-interviews/).

- **Q34. Find the second-highest distinct salary.**distinct(), sort in reverse order, skip(1), findFirst(). The result is an Optional because there may be fewer than two distinct values.
- **Q35. Group employees by department, then count, average and find the highest paid.**groupingBy with counting(), averagingInt() or maxBy(). maxBy gives an Optional<Employee> per group.
- **Q36. Find the first non-repeated character.** Count in a LinkedHashMap to keep order, then take the first entry with count 1. For 'swiss' the answer is 'w'. Time is O(n).
- **Q37. Count word frequency and list the top 3.** Split on non-word characters, group with counting(), then sort by value descending and word ascending. HashMap order is not specified, so sort before printing.
- **Q38. Find duplicates in a list.** Group by value and keep counts above 1. The shortcut filter(n -> !seen.add(n)) works sequentially but mutates shared state, so it breaks under parallel().
- **Q39. Flatten nested lists, join strings and print Fibonacci numbers.**flatMap(List::stream), Collectors.joining, and Stream.iterate over a pair with limit(10), which gives 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
- **Q40. Check a palindrome and an anagram.** Normalise case, drop non-alphanumerics and compare mirrored characters. For anagrams, sort both arrays and use Arrays.equals (O(n log n)), or count letters in an int[26] (O(n)).
// Imports omitted: java.util.*, java.util.function.Function, java.util.stream.* // Java 8 style: a plain class (on Java 16 and later, a record does the same in one line). class Employee { private final String name; private final String dept; private final int salary; Employee(String name, String dept, int salary) { this.name = name; this.dept = dept; this.salary = salary; } String getName() { return name; } String getDept() { return dept; } int getSalary() { return salary; } } // Q34: second-highest distinct salary (Optional, because there may be fewer than two values) Optional<Integer> second = emps.stream() .map(Employee::getSalary) .distinct() .sorted(Comparator.reverseOrder()) .skip(1) .findFirst(); // Q35: headcount, average salary and highest paid per department Map<String, Long> headcount = emps.stream() .collect(Collectors.groupingBy(Employee::getDept, Collectors.counting())); Map<String, Double> average = emps.stream() .collect(Collectors.groupingBy(Employee::getDept, Collectors.averagingInt(Employee::getSalary))); Map<String, Optional<Employee>> top = emps.stream() .collect(Collectors.groupingBy(Employee::getDept, Collectors.maxBy(Comparator.comparingInt(Employee::getSalary))));// Assumes: String text; List<Integer> nums; List<List<Integer>> lists; List<String> names; // Q36: first non-repeated character ("swiss" gives 'w') static Optional<Character> firstUnique(String s) { Map<Character, Long> counts = s.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())); return counts.entrySet().stream() .filter(e -> e.getValue() == 1) .map(Map.Entry::getKey) .findFirst(); } // Q37: top 3 words by frequency, ties broken alphabetically Map<String, Long> freq = Arrays.stream(text.toLowerCase().split("\\W+")) .filter(w -> !w.isEmpty()) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); List<Map.Entry<String, Long>> top3 = freq.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed() .thenComparing(Map.Entry.comparingByKey())) .limit(3) .collect(Collectors.toList()); // Q38: values that occur more than once List<Integer> dups = nums.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet().stream() .filter(e -> e.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toList()); // Q39: flatten, join, and the first ten Fibonacci numbers List<Integer> flat = lists.stream().flatMap(List::stream).collect(Collectors.toList()); String csv = names.stream().map(String::toUpperCase).collect(Collectors.joining(", ", "[", "]")); List<Long> fib = Stream.iterate(new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]}) .limit(10) .map(f -> f[0]) .collect(Collectors.toList()); // Q40: palindrome and anagram static boolean isPalindrome(String s) { String t = s.toLowerCase().replaceAll("[^a-z0-9]", ""); return IntStream.range(0, t.length() / 2) .allMatch(i -> t.charAt(i) == t.charAt(t.length() - 1 - i)); } static boolean isAnagram(String a, String b) { char[] x = a.replace(" ", "").toLowerCase().toCharArray(); char[] y = b.replace(" ", "").toLowerCase().toCharArray(); Arrays.sort(x); Arrays.sort(y); return Arrays.equals(x, y); }

Expect a follow-up such as 'now do it without streams'. The [DSA interview questions](https://www.masaischool.com/resources/dsa-interview-questions) and [data structures and algorithms path](https://www.masaischool.com/resources/data-structures-and-algorithms) cover the algorithm side.

## What interviewers expect from freshers to 10 years

| Level | What to be ready for | Focus on this page |
|---|---|---|
| Fresher (0 to 1 year) | Syntax, OOP, collections, strings, exceptions, lambdas, streams, a coding problem or two and a project you can explain | Q1 to Q18, Q24 to Q26, Q34 to Q40 |
| 2 to 5 years | HashMap and concurrency internals, streams in real code, JVM memory and GC basics, Java 17 and 21 features, a production bug story | Q9 to Q12, Q19 to Q33 |
| 5 to 10 years | Design under load, thread-safety, performance, GC tuning, upgrading from Java 8, mentoring | The questions below and [system design preparation](https://www.masaischool.com/resources/system-design-interview-preparation) |

No company publishes its rubric, so this table is our reading, not survey data. The [SDE levels guide](https://www.masaischool.com/resources/sde-full-form-and-sde-levels) explains how titles map to experience.

### For 10 years of experience: design and performance questions

- **Design a thread-safe in-memory cache.** Start with ConcurrentHashMap. For eviction, LinkedHashMap in access order with removeEldestEntry gives an LRU but needs external locking. Discuss expiry, stampedes (computeIfAbsent) and metrics.
- **A service shows latency spikes. What do you do?** Take thread dumps seconds apart with jcmd <pid> Thread.print, record with JFR, read GC logs (-Xlog:gc) and compare allocation rate and pauses before touching flags.
- **How do you choose a garbage collector?** OpenJDK's summary: ZGC prioritises latency, Parallel prioritises throughput and G1 balances both. Set -Xmx deliberately, change one flag at a time and judge by a load test.
- **How do you migrate a Java 8 service to 17, 21 or 25?** Move in LTS steps with tests. Strong encapsulation of JDK internals (**Java 17**, JEP 403) breaks reflective access, Nashorn was removed in **Java 15** (JEP 372) and the Security Manager was deprecated for removal in **Java 17** (JEP 411). jdeps finds internal API use.
- **Virtual threads, reactive code or a thread pool?** Virtual threads for blocking, thread-per-request code. A bounded platform pool for CPU-bound work, since more threads than cores cannot raise throughput.

For the framework side of senior rounds, see [Spring Boot interview questions](https://www.masaischool.com/resources/spring-boot-interview-questions) and the [backend developer roadmap](https://www.masaischool.com/resources/backend-developer-roadmap).

## Frequently asked questions

### What are the most asked Java interview questions?

Expect HashMap internals, equals and hashCode, String immutability, ArrayList versus LinkedList, checked versus unchecked exceptions, synchronized versus volatile, streams, Optional and garbage collection. Master Q3, Q7, Q10, Q13, Q20 and Q25 first. No company publishes its question bank, so this is our reading.

### Which Java version should I learn for interviews in 2026?

As of 11 November 2026 the LTS releases are Java 8, 11, 17, 21 and 25, and Java 27 is the newest. Learn on Java 21 or 25, know the Java 17 features, and keep Java 8 ready because older codebases use it.

### Are Java 8 questions still asked?

In our reading, yes. Lambdas, streams, Optional, default methods and java.time remain the most common topics, and coding rounds often want stream-based answers. Interviewers then add records or virtual threads to test how current you are. See Q24 to Q27 and Q34 to Q40.

### How should a fresher prepare for a Java interview?

Learn the basics, OOP, collections, strings and exceptions, then explain each answer in your own words and run small programs to check it. Practise array, string and hash map problems and build one project you can explain. Start with Q1 to Q18.

### What is asked in Java interviews for 10 years of experience?

Expect design and performance questions: thread-safe components, memory leaks, collector choice, latency spikes and migrating from Java 8, plus how you led reviews or releases. The last section above lists five such questions, and a system design round often follows.

## Sources checked

- [Oracle Java SE Support Roadmap, updated 20 Oct 2026: LTS releases, support dates, next LTS](https://www.oracle.com/java/technologies/java-se-support-roadmap.html)
- [OpenJDK release list: Java 27 GA 15 Sep 2026, Java 28 in development](https://openjdk.org/projects/jdk/)
- [JDK 27 feature list](https://openjdk.org/projects/jdk/27/)
- [JDK 25 feature list and LTS note](https://openjdk.org/projects/jdk/25/)
- [Virtual threads, Java 21](https://openjdk.org/jeps/444)
- [Virtual threads without pinning, Java 24](https://openjdk.org/jeps/491)
- [Scoped values, Java 25](https://openjdk.org/jeps/506)
- [G1 default in all environments, Java 27](https://openjdk.org/jeps/523)
- [JLS boxing and cached values](https://docs.oracle.com/javase/specs/jls/se25/html/jls-5.html)
- [Optional API and @since tags](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Optional.html)
