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 (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 or Masai's shorter Common Spring Boot Interview Questions and Tips. For language gaps, start with 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
javacandjcmd. 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.
==versusequals(), and the Integer cache?==compares primitives by value and references by identity.equals()compares content where overridden, as inString.Integer.valueOfalways caches -128 to 127, so two boxed 1000s can fail==. - Q4. What do
final,finallyandfinalizemean?finalblocks reassignment, overriding or subclassing.finallyruns aftertryandcatch, even onreturn, 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
defaultandstaticmethods in Java 8 and private methods in Java 9. - Q7. What is the
equals()andhashCode()contract? Equal objects must have equal hash codes, andequals()must be reflexive, symmetric, transitive and consistent. Override both, orHashMapcannot find your keys. - Q8. How do you make a class immutable? Make it
finalwithprivate finalfields, no setters, and defensive copies of mutable inputs and outputs.StringandLocalDatework this way. Arecord(Java 16) does it in one line, but aListcomponent stays mutable. See the OOP explainer.
Collections
- Q9. ArrayList or LinkedList?
ArrayListis a resizable array: O(1) reads, amortised O(1) append, O(n) middle insert.LinkedListis doubly linked: O(1) at the ends, O(n) to reach an element. Default toArrayList. - Q10. How does
HashMapwork? 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. - Q11.
HashMap,HashtableorConcurrentHashMap?HashMapis unsynchronised and permits one null key.Hashtableis a legacy class with synchronised methods.ConcurrentHashMapallows concurrent updates without locking the whole map and rejects null keys and values. - Q12.
HashMap,LinkedHashMaporTreeMap, 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 throwsConcurrentModificationException, on a best-effort basis. Use the iterator'sremoveorremoveIf.
Strings
- Q13. Why is
Stringimmutable, 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, whilenew String("a")makes a separate object. - Q14.
String,StringBuilderorStringBuffer? UseStringBuilderto build text in a loop on one thread.StringBufferis the older synchronised version. Since Java 9, plain+compiles toinvokedynamic(JEP 280). - Q15. Which
Stringfeatures came after Java 8? Java 11 addedisBlank(),strip(),lines()andrepeat(int). Java 15 made text blocks final and addedformatted().strip()followsCharacter.isWhitespace, so prefer it totrim().
Exceptions
- Q16. Checked or unchecked exceptions? Unchecked ones are
RuntimeException,Errorand their subclasses. Every otherThrowableis 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
AutoCloseabledeclared in the parentheses is closed automatically, in reverse order, even after an exception. If the body andclose()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
RunnableversusCallable?Thread.StatehasNEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITINGandTERMINATED.Runnable.run()returns nothing;Callable.call()returns a value and may throw. Callstart(), notrun(). - Q20. What do
synchronized,volatileandReentrantLockdo?synchronizedgives mutual exclusion and visibility.volatilegives visibility and ordering for one variable, not atomicity, socount++is still unsafe.ReentrantLockadds 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
tryLockwith a timeout. Diagnose withjcmd <pid> Thread.print. - Q22. Why use
ExecutorService, and what isCompletableFuture? Pools reuse threads and bound concurrency, and needshutdown().CompletableFuture(Java 8) chains asynchronous steps withthenApply,thenComposeandthenCombineand handles errors withexceptionally. - 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 lighterThreadLocal.
// 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 tasksJava 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
@FunctionalInterfacemakes the compiler check that. Core types areFunction,Predicate,ConsumerandSupplier. Captured locals must be effectively final. - Q25. How do streams work? A stream (Java 8) is a lazy pipeline:
filterandmaprun only when a terminal step such ascollectstarts, and a stream is consumed once. Avoid side effects and measure beforeparallel().Stream.toList()(Java 16) is unmodifiable. - Q26. How should you use
Optional? As a return type for 'no result', not a field or parameter. Prefermap,orElseGetandorElseThrow()(Java 10) toget(). Java 9 addedifPresentOrElse,orandstream(), and Java 11 addedisEmpty(). - Q27. What replaced
DateandCalendar? Thejava.timepackage (Java 8, JEP 150):LocalDate,ZonedDateTime,InstantandDuration. 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,hashCodeandtoString. Sealed classes (Java 17) list permitted subclasses. Pattern matching:instanceofin Java 16,switchand 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-previewand 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:+HeapDumpOnOutOfMemoryErrororjcmd <pid> GC.heap_dump, open the dump in Eclipse Memory Analyzer 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.
- Q34. Find the second-highest distinct salary.
distinct(), sort in reverse order,skip(1),findFirst(). The result is anOptionalbecause there may be fewer than two distinct values. - Q35. Group employees by department, then count, average and find the highest paid.
groupingBywithcounting(),averagingInt()ormaxBy().maxBygives anOptional<Employee>per group. - Q36. Find the first non-repeated character. Count in a
LinkedHashMapto 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.HashMaporder 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 underparallel(). - Q39. Flatten nested lists, join strings and print Fibonacci numbers.
flatMap(List::stream),Collectors.joining, andStream.iterateover a pair withlimit(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 anint[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 and data structures and algorithms path 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 |
No company publishes its rubric, so this table is our reading, not survey data. The SDE levels guide 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,LinkedHashMapin access order withremoveEldestEntrygives 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
-Xmxdeliberately, 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).
jdepsfinds 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 and the 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
- OpenJDK release list: Java 27 GA 15 Sep 2026, Java 28 in development
- JDK 27 feature list
- JDK 25 feature list and LTS note
- Virtual threads, Java 21
- Virtual threads without pinning, Java 24
- Scoped values, Java 25
- G1 default in all environments, Java 27
- JLS boxing and cached values
- Optional API and @since tags
Learn this with mentors
Programmes for builders and engineers with admissions open: live classes, mentors and project work.


