Java is still the language behind most bank, telecom and enterprise back ends in India, and it is the main language for Android and for Spring Boot microservices. That is why Java interview questions come up in campus drives at TCS, Infosys and Wipro just as often as in product company rounds. Freshers get “JDK vs JRE vs JVM” and “== vs equals”. Experienced candidates get HashMap internals, concurrency, garbage collection and Java 21 features.
This page has the 100 Java interview questions asked most often, with clear answers, grouped for freshers, intermediate and experienced candidates. 36 answers include a Java example that was compiled and run on Java 21, so the output you see is real. Four interactive tools let you watch the stack, heap and String pool change line by line, test yourself on tricky “what does this print?” snippets, pick the right collection, and take a quick quiz. Prefer to study offline? Download all 100 questions as a free PDF.
What you will find on this page
- 100 questions with answers in three levels: 40 for freshers, 35 intermediate, 25 for experienced candidates.
- Core Java and Java 8: basics, OOP, strings, exceptions, collections, generics, multithreading, the JVM and memory, streams and lambdas, plus records, sealed classes and virtual threads from Java 17 and 21.
- Four interactive tools: a stack, heap and String pool visualiser, a “guess the output” game, a collection chooser and a quiz.
- 36 Java examples with real output.
- Study tools: filters by level and topic, search, and a “Done” button on every question that remembers your progress.
- A free 54-page PDF of everything.
Also useful (each opens our own guide):
Study these 100 questions your way
Filter the Java interview questions by level or topic, or search them. Press “Mark as done” under each question you have finished; your progress is saved in this browser.
No questions match these filters. Try another topic or clear the search.
How to prepare for a Java interview
- Know the classic comparisons cold: JDK vs JRE vs JVM, == vs equals(), String vs StringBuilder, abstract class vs interface, ArrayList vs LinkedList, HashMap vs ConcurrentHashMap, checked vs unchecked exceptions, Comparable vs Comparator.
- Be ready to explain internals: how HashMap works, why String is immutable, what happens in memory when you create an object, and how garbage collection decides what to free.
- Write Java 8 stream code by hand: group employees by department, find the second highest salary, count word frequencies. Many companies ask for these on a shared editor or on paper.
- For 3+ years of experience, revise concurrency (synchronized, volatile, ExecutorService, CompletableFuture), JVM tuning, and what your project used from Java 17 and 21.
- Expect a coding round as well. Practise arrays, strings, hashing and two pointers in Java; our DSA cheat sheet lists the patterns.
Learn the tricky parts by doing
Three topics trip up more Java candidates than any others: what happens in memory, small snippets with surprising output, and choosing the right collection. These tools let you practise each one before you read the questions.
Stack, heap and String pool visualiser
Step through two short programs and watch where every variable and object lives. The first shows the String pool and why == can be false for equal strings. The second shows why Java is pass by value, even for objects.
Java memory, one line at a time
Code
Stack
Heap
Guess the output: 14 tricky Java snippets
Interviewers love short snippets with a surprising result. Every snippet below was run on Java 21, so the answers are what the JVM really prints.
What does this code print?
14 snippets, about five minutes.
Which collection should I use?
“Which collection would you use for this?” is one of the most common follow-up questions. Answer three questions and see the class to use, its cost, and one line of code.
Collection chooser
Java interview questions for freshers
These 40 core Java interview questions cover what campus placements and first interviews ask: how Java runs, data types, OOP, strings, exceptions, the basic collections, threads, memory and the main Java 8 features.
1. What is Java and what are its main features?
Java is a general-purpose, object-oriented programming language released by Sun Microsystems in 1995 and now owned by Oracle. Java code is compiled into bytecode that runs on the Java Virtual Machine (JVM), which is why the same program runs on Windows, Linux and macOS without changes.
- Platform independent: “write once, run anywhere”, thanks to bytecode and the JVM.
- Object-oriented: code is organised into classes and objects, with encapsulation, inheritance, polymorphism and abstraction.
- Robust and secure: strong typing, no pointer arithmetic, automatic garbage collection and checked exceptions.
- Multithreaded: threads and concurrency utilities are built into the language and the standard library.
- Fast enough for most work: the JIT compiler turns hot bytecode into native machine code at run time.
- Huge ecosystem: Spring Boot, Android, Hadoop, Kafka and most bank and enterprise back ends run on Java.
2. What is the difference between JDK, JRE and JVM?
| What it is | Contains | Who needs it | |
|---|---|---|---|
| JVM | The virtual machine that runs bytecode | Class loader, memory areas, interpreter, JIT compiler, garbage collector | Every Java program, at run time |
| JRE | Java Runtime Environment | JVM + core class libraries (java.lang, java.util and so on) | Users who only run Java programs |
| JDK | Java Development Kit | JRE + development tools: javac, java, jar, javadoc, jdb, jshell | Developers who write and compile Java |
In short: JDK = JRE + tools, and JRE = JVM + libraries. Since Java 11, Oracle no longer ships a separate JRE download; you install a JDK and can build a small custom runtime with jlink if you need one.
3. Why is Java platform independent? Is the JVM platform independent?
The javac compiler does not produce machine code for one processor. It produces bytecode (.class files), an instruction set for the JVM. Each operating system has its own JVM that understands the same bytecode, so one .class file runs everywhere.
So Java the language and its bytecode are platform independent, but the JVM itself is platform dependent: there is a different JVM build for Windows, Linux and macOS, and for x64 and ARM. That is the trade: the JVM vendors handle each platform so your code does not have to.
4. Explain public static void main(String[] args).
public: the JVM must be able to call it from outside the class.static: the JVM calls it without creating an object of the class.void: it returns nothing to the JVM. UseSystem.exit(code)to return an exit status.main: the name the JVM looks for as the entry point.String[] args: command-line arguments, for examplejava Main hello 42gives args[0] = “hello”.
Follow-up questions: you can overload main, but the JVM only calls the version with String[]. String... args also works. Since Java 21 (as a preview, and final in Java 25), simpler instance main methods like void main() are allowed for small programs.
5. What are the primitive data types in Java?
| Type | Size | Default | Range or example |
|---|---|---|---|
byte | 1 byte | 0 | -128 to 127 |
short | 2 bytes | 0 | -32,768 to 32,767 |
int | 4 bytes | 0 | about ±2.1 billion |
long | 8 bytes | 0L | about ±9.2 × 10¹⁸ |
float | 4 bytes | 0.0f | about 7 decimal digits |
double | 8 bytes | 0.0d | about 15 decimal digits |
char | 2 bytes | ‘\u0000’ | one UTF-16 code unit |
boolean | JVM dependent | false | true or false |
Defaults apply to fields only; local variables must be assigned before use. Everything else, including String and arrays, is a reference type. Never use float or double for money; use BigDecimal, because 0.1 + 0.2 is not exactly 0.3 in binary floating point.
6. What are wrapper classes and autoboxing? Why does Integer 127 == 127 give true but 128 == 128 give false?
Each primitive has a wrapper class: Integer, Long, Double, Character, Boolean and so on. Collections and generics only work with objects, so you need wrappers for List<Integer>. Autoboxing converts a primitive to its wrapper automatically, and unboxing does the reverse.
public class Main {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // same cached object
System.out.println(c == d); // two different objects
System.out.println(c.equals(d)); // compares values
int total = a + c; // unboxing happens here
System.out.println(total);
}
}Output:
true
false
true
255Integer.valueOf(), which autoboxing uses, caches the objects from -128 to 127. Inside that range both variables point to the same cached object, so == is true; outside it you get two objects. The lesson: always compare wrapper objects with equals(). Also, unboxing a null wrapper throws a NullPointerException.
7. Is Java pass by value or pass by reference?
Java is always pass by value. For primitives the value is the number itself. For objects, the value that gets copied is the reference (the address of the object). The method can use that copy to change the object, but re-pointing the copy does not affect the caller’s variable.
import java.util.*;
public class Main {
static void change(int x, List<String> list) {
x = 100; // changes only the local copy
list.add("Java"); // changes the object the copy points to
list = new ArrayList<>(); // re-points only the local copy
list.add("Python");
}
public static void main(String[] args) {
int num = 5;
List<String> langs = new ArrayList<>();
change(num, langs);
System.out.println(num);
System.out.println(langs);
}
}Output:
5
[Java]num stays 5. The list shows “Java” because both references pointed to the same object at that moment, but not “Python”, because by then the method had re-pointed only its own copy. This is why a classic swap(a, b) method cannot swap two objects in Java.
8. What does the static keyword mean?
static members belong to the class, not to any one object. A static variable has one copy shared by all objects; a static method can be called with the class name and has no this.
public class Main {
static class Student {
static int count = 0; // one copy, shared by all objects
String name; // one copy per object
Student(String name) {
this.name = name;
count++;
}
static void showCount() {
System.out.println("Students created: " + count);
}
}
public static void main(String[] args) {
new Student("Riya");
new Student("Arjun");
new Student("Meera");
Student.showCount();
}
}Output:
Students created: 3- Static variable: shared data such as a counter or a constant.
- Static method: utility code like
Math.max(). It cannot use instance variables directly. - Static block: runs once when the class is loaded, used to set up static data.
- Static nested class: a nested class that does not need an outer object.
9. What is the difference between final, finally and finalize?
| Keyword | Used for | Meaning |
|---|---|---|
final | Variable, method, class | A final variable cannot be reassigned, a final method cannot be overridden, a final class cannot be extended (for example String) |
finally | Block after try/catch | Runs whether or not an exception happened, used to release resources |
finalize() | Method of Object | Was called by the garbage collector before removing an object. Deprecated since Java 9 and marked for removal; use try-with-resources or Cleaner instead |
import java.util.*;
public class Main {
static final double GST = 0.18; // constant
static class Base {
final void rule() { System.out.println("cannot be overridden"); }
}
public static void main(String[] args) {
final List<String> list = new ArrayList<>();
list.add("Java"); // allowed: the object can change
// list = new ArrayList<>(); // compile error: reference is final
System.out.println(list);
try {
System.out.println("in try");
} finally {
System.out.println("finally always runs");
}
new Base().rule();
System.out.println(1000 * (1 + GST));
}
}Output:
[Java]
in try
finally always runs
cannot be overridden
1180.0A final reference cannot point to a new object, but the object itself can still change, which is why the list above accepts “Java”.
10. What is the difference between this and super?
thisrefers to the current object. Use it to tell a field from a parameter with the same name (this.name = name), to pass the current object to another method, or to call another constructor of the same class withthis(...).superrefers to the parent class part of the object. Use it to call the parent’s constructor withsuper(...)or a method you have overridden withsuper.method().
A call to this(...) or super(...) must be the first statement in a constructor, so a constructor can use only one of them. If you write neither, the compiler inserts super() automatically. Neither keyword can be used in a static method.
11. What is a constructor? Can a constructor be private, static or final?
A constructor is a special block that runs when you create an object with new. It has the same name as the class and no return type. If you write no constructor, the compiler adds a default no-argument one; if you write any constructor, it does not.
- Private: yes. Used in singletons and utility classes so that outside code cannot create objects.
- Static: no. A constructor initialises an object, so it cannot belong to the class.
- Final or abstract: no. Constructors are not inherited, so they can never be overridden anyway.
- Overloaded: yes, with different parameter lists, and one can call another with
this(...)(constructor chaining).
12. What are the four pillars of object-oriented programming in Java?
- Encapsulation: keep fields private and expose them through methods, so an object controls its own state. Example: a BankAccount that only changes its balance through deposit() and withdraw().
- Inheritance: a class reuses and extends another with
extends. Example: Car extends Vehicle. - Polymorphism: one interface, many forms. Overloading is compile-time polymorphism; overriding is runtime polymorphism.
- Abstraction: show what an object does and hide how, using abstract classes and interfaces. Example: you call
list.add()without caring whether it is an ArrayList or a LinkedList.
Our OOPs interview questions post goes deeper into each pillar with examples in several languages.
13. Why does Java not support multiple inheritance of classes?
If class C could extend both A and B, and both had a method show(), C would not know which one to inherit. This is the diamond problem. Java avoids it by allowing a class to extend only one class.
A class can implement many interfaces, though. Before Java 8 that was always safe because interfaces had no method bodies. Since Java 8, interfaces can have default methods, so the diamond problem can appear again, and Java makes you resolve it yourself (see question 69). Java supports single, multilevel and hierarchical inheritance with classes.
14. What is the difference between method overloading and method overriding?
| Point | Overloading | Overriding |
|---|---|---|
| Where | Same class (or subclass) | Subclass redefines a parent method |
| Signature | Same name, different parameters | Same name and same parameters |
| Return type | Can be anything | Same or a subtype (covariant) |
| Decided at | Compile time (static binding) | Run time (dynamic binding) |
| Access | Any | Cannot be more restrictive than the parent |
| static / private | Can be overloaded | Cannot be overridden |
public class Main {
static class Shape {
double area() { return 0; }
String describe() { return "Shape with area " + area(); }
}
static class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
@Override
double area() { return Math.round(Math.PI * r * r * 100) / 100.0; }
}
// overloading: same name, different parameters
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
static int add(int a, int b, int c) { return a + b + c; }
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.5, 3.5));
System.out.println(add(1, 2, 3));
Shape s = new Circle(2); // reference type Shape, object Circle
System.out.println(s.describe()); // Circle's area() runs: overriding
}
}Output:
5
6.0
6
Shape with area 12.57The last line is the key point: the variable type is Shape, but the object is a Circle, so the JVM calls Circle’s area() at run time. Changing only the return type is not overloading and does not compile.
15. What is the difference between an abstract class and an interface?
| Point | Abstract class | Interface |
|---|---|---|
| Methods | Abstract and concrete | Abstract, plus default and static (Java 8) and private (Java 9) |
| Fields | Any instance or static fields | Only public static final constants |
| Constructor | Yes | No |
| Inheritance | A class extends only one | A class implements many |
| Access | Any access modifier | Methods are public by default |
| Use when | Related classes share state and code | Unrelated classes share a capability (Comparable, Runnable) |
public class Main {
interface Payment {
double FEE = 0.02; // public static final
void pay(double amount); // abstract
default String receipt(double amount) { // default method (Java 8)
return "Paid Rs " + amount + " + fee Rs " + amount * FEE;
}
}
static abstract class Account {
protected double balance; // state is allowed
Account(double balance) { this.balance = balance; }
abstract String type();
String summary() { return type() + " balance: " + balance; }
}
static class Savings extends Account implements Payment {
Savings(double b) { super(b); }
String type() { return "Savings"; }
public void pay(double amount) { balance -= amount; }
}
public static void main(String[] args) {
Savings s = new Savings(5000);
s.pay(1200);
System.out.println(s.summary());
System.out.println(s.receipt(1200));
}
}Output:
Savings balance: 3800.0
Paid Rs 1200.0 + fee Rs 24.0Rule of thumb: start with an interface to define what something can do, and add an abstract class when several implementations share real code and fields.
16. What are the access modifiers in Java?
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
private | Yes | No | No | No |
| default (no keyword) | Yes | Yes | No | No |
protected | Yes | Yes | Yes | No |
public | Yes | Yes | Yes | Yes |
A top-level class can only be public or default. Good encapsulation means making fields private and opening up only what other code needs. When overriding, you can keep or widen access (protected to public) but never narrow it.
17. What is polymorphism? Explain compile-time and runtime polymorphism.
Compile-time (static) polymorphism is method overloading: the compiler picks the method from the argument types. Runtime (dynamic) polymorphism is method overriding: a parent reference can hold a child object, and the JVM calls the child’s version of the method through dynamic method dispatch.
Example: List<String> list = new ArrayList<>(); Your code talks to List, and you can switch to LinkedList by changing one line. This “program to an interface” idea is why polymorphism matters in real projects, not just in theory.
18. Can we override static or private methods?
No. Private methods are not visible to subclasses, so a method with the same name in a child class is a brand-new method. Static methods belong to the class; if a child declares the same static method, it hides the parent’s method instead of overriding it. Which one runs depends on the reference type, not the object.
Final methods also cannot be overridden. You can, however, overload static and private methods. Adding @Override to a method that does not actually override anything gives a compile error, which is why using that annotation is good practice.
19. Why is String immutable in Java?
- String pool: many variables share one pooled “java” object. That is only safe if no one can change it.
- Security: file paths, URLs, class names and database credentials are passed as strings. If they could change after a security check, the check would be useless.
- Thread safety: immutable objects can be shared between threads without locks.
- Hash code caching: a String computes its hash once and reuses it, which makes it a fast and safe HashMap key.
Methods like concat(), toUpperCase() and replace() never change the original; they return a new String. The String class is also final, so no subclass can break this guarantee.
20. What is the String pool? What is the difference between == and equals() for strings?
The String pool is a special area in the heap where Java keeps one copy of each string literal. == checks whether two references point to the same object; equals() checks whether the characters are the same.
public class Main {
public static void main(String[] args) {
String a = "java"; // goes to the string pool
String b = "java"; // reuses the same pooled object
String c = new String("java"); // new object on the heap
String d = c.intern(); // pooled version of c
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
System.out.println(a == d);
String e = "ja" + "va"; // joined at compile time
String part = "ja";
String f = part + "va"; // joined at run time
System.out.println(a == e);
System.out.println(a == f);
}
}Output:
true
false
true
true
true
falsenew String("java") always creates a new object, so a == c is false. intern() returns the pooled copy. Literals joined at compile time (“ja” + “va”) are pooled; strings built at run time are not. In real code, always compare strings with equals() (or equalsIgnoreCase()).
21. What is the difference between String, StringBuilder and StringBuffer?
| Point | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread safe | Yes (immutable) | No | Yes (synchronized methods) |
| Speed for many changes | Slow, new object each time | Fastest | Slower than StringBuilder |
| Use when | Text that does not change | Building text in one thread (most cases) | Legacy code shared across threads |
public class Main {
public static void main(String[] args) {
String s = "Code";
s.concat(" and Debug"); // result thrown away
System.out.println(s); // s is unchanged
s = s.concat(" and Debug"); // assign the new String
System.out.println(s);
StringBuilder sb = new StringBuilder("Code");
sb.append(" and").append(" Debug"); // changes the same object
sb.insert(0, "Learn at ");
System.out.println(sb);
System.out.println(sb.reverse());
}
}Output:
Code
Code and Debug
Learn at Code and Debug
gubeD dna edoC ta nraeLJoining strings with + inside a loop creates a new String each time, which is O(n²) work for n pieces. Use StringBuilder in loops. A single line like "Hi " + name is fine; the compiler optimises it.
22. How many objects are created by String s = new String(“hello”)?
One or two. If “hello” is not already in the String pool, the literal creates one pooled object when the class is loaded, and new creates a second object on the heap. If the literal is already in the pool, only the heap object is created.
This is why new String("...") is almost never needed in real code; it only wastes memory. The answer interviewers want is “two, if the literal is not already in the pool”, along with the reason.
23. What is the exception hierarchy? What is the difference between checked and unchecked exceptions?
Everything that can be thrown extends Throwable, which has two branches: Error (serious JVM problems such as OutOfMemoryError, which you normally do not catch) and Exception. Under Exception, RuntimeException and its subclasses are unchecked; everything else is checked.
| Checked | Unchecked | |
|---|---|---|
| Checked by | Compiler: you must catch or declare with throws | Not checked at compile time |
| Typical cause | Things outside your control | Bugs in the code |
| Examples | IOException, SQLException, ClassNotFoundException | NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException |
24. What is the difference between throw and throws?
| throw | throws | |
|---|---|---|
| What it does | Actually throws one exception object | Declares which exceptions a method may throw |
| Where | Inside a method body | In the method signature |
| Followed by | An instance: throw new IllegalArgumentException(“age”) | Class names: throws IOException, SQLException |
| How many | One at a time | Several, comma separated |
You need throws for checked exceptions that you do not handle inside the method. For unchecked exceptions it is optional and mostly used for documentation.
25. How do try, catch and finally work? Does finally always run?
public class Main {
static int test() {
try {
System.out.println("try");
int x = 10 / 0;
return 1;
} catch (ArithmeticException e) {
System.out.println("catch: " + e.getMessage());
return 2;
} finally {
System.out.println("finally runs before the method returns");
}
}
public static void main(String[] args) {
System.out.println("returned " + test());
}
}Output:
try
catch: / by zero
finally runs before the method returns
returned 2The exception jumps from the division straight to the matching catch block. The catch block prepares to return 2, but finally runs first, and only then does the method return. Finally runs whether the try block completes normally, throws, or returns.
It does not run if the JVM stops: System.exit(), a JVM crash, or the thread being killed. Avoid return inside finally; it silently overrides the value from try or catch and swallows any exception.
26. How do you create a custom exception?
Extend Exception for a checked exception or RuntimeException for an unchecked one, and pass the message (and optionally the cause) to the parent constructor.
public class Main {
static class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String msg) { super(msg); }
}
static double balance = 3000;
static void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance)
throw new InsufficientBalanceException(
"Need Rs " + amount + " but balance is Rs " + balance);
balance -= amount;
System.out.println("Withdrawn Rs " + amount);
}
public static void main(String[] args) {
try {
withdraw(1000);
withdraw(5000);
} catch (InsufficientBalanceException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Output:
Withdrawn Rs 1000.0
Error: Need Rs 5000.0 but balance is Rs 2000.0Custom exceptions make errors self-explaining. Name them after the problem, not the code location: InsufficientBalanceException says more than WithdrawException. Most modern code, Spring included, prefers unchecked custom exceptions.
27. What is the Java Collections Framework?
It is the set of interfaces and classes in java.util for storing and working with groups of objects. The main interfaces are Collection (with List, Set and Queue/Deque under it) and Map, which is separate because it stores key-value pairs.
| Interface | Main classes | Key property |
|---|---|---|
| List | ArrayList, LinkedList | Ordered, allows duplicates, index access |
| Set | HashSet, LinkedHashSet, TreeSet | No duplicates |
| Queue / Deque | ArrayDeque, PriorityQueue, LinkedList | Process in FIFO, LIFO or priority order |
| Map | HashMap, LinkedHashMap, TreeMap | Unique keys mapped to values |
The Collections class (with an s) is a different thing: a utility class with static methods like sort(), reverse() and unmodifiableList().
28. What is the difference between an array and an ArrayList?
| Point | Array | ArrayList |
|---|---|---|
| Size | Fixed when created | Grows automatically (by about 1.5 times when full) |
| Element types | Primitives and objects | Objects only (int is autoboxed to Integer) |
| Length | arr.length (field) | list.size() (method) |
| Features | Basic indexing | add, remove, contains, sort, iterators |
| Performance | Slightly faster, less memory | Small overhead from boxing and resizing |
Use arrays for fixed-size data and performance-critical code with primitives, such as DSA problems. Use ArrayList for most application code. Convert with Arrays.asList() or List.of() and list.toArray().
29. What is the difference between ArrayList and LinkedList?
| Operation | ArrayList | LinkedList |
|---|---|---|
| Internal structure | Resizable array | Doubly linked list |
| get(index) | O(1) | O(n) |
| Add at end | O(1) amortised | O(1) |
| Add or remove in the middle | O(n), shifts elements | O(1) once you are at the node, but O(n) to get there |
| Memory | Compact | Extra two pointers per element |
| Also implements | List | List and Deque |
In practice ArrayList wins almost every time because arrays are cache friendly. For a queue or stack, use ArrayDeque rather than LinkedList. See our time complexity guide for what O(1) and O(n) mean.
30. What is the difference between List, Set and Map? Compare HashSet, LinkedHashSet and TreeSet.
A List keeps insertion order and allows duplicates. A Set rejects duplicates. A Map stores unique keys with a value each. The three Set classes differ in ordering:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> cities = List.of("Pune", "Delhi", "Surat", "Delhi", "Agra");
System.out.println("HashSet: " + new HashSet<>(cities));
System.out.println("LinkedHashSet: " + new LinkedHashSet<>(cities));
System.out.println("TreeSet: " + new TreeSet<>(cities));
}
}Output:
HashSet: [Delhi, Pune, Agra, Surat]
LinkedHashSet: [Pune, Delhi, Surat, Agra]
TreeSet: [Agra, Delhi, Pune, Surat]| HashSet | LinkedHashSet | TreeSet | |
|---|---|---|---|
| Order | No guaranteed order | Insertion order | Sorted |
| add / contains | O(1) | O(1) | O(log n) |
| Backed by | HashMap | LinkedHashMap | TreeMap (red-black tree) |
| null | One null allowed | One null allowed | Not allowed |
The same three choices exist for maps: HashMap, LinkedHashMap and TreeMap.
31. What is the difference between Comparable and Comparator?
| Comparable | Comparator | |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T other) | compare(T a, T b) |
| Where it lives | Inside the class itself | A separate object or lambda |
| How many orders | One natural order | As many as you need |
| Used by | Collections.sort(list), TreeSet | list.sort(comparator), Comparator.comparing(…) |
import java.util.*;
public class Main {
record Student(String name, int marks, int age) implements Comparable<Student> {
public int compareTo(Student o) { // natural order: by name
return name.compareTo(o.name);
}
}
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Riya", 88, 21), new Student("Arjun", 92, 22),
new Student("Meera", 88, 20), new Student("Kabir", 75, 21)));
Collections.sort(list); // uses Comparable
list.forEach(s -> System.out.print(s.name() + " "));
System.out.println();
// Comparator: marks high to low, then age low to high
list.sort(Comparator.comparingInt(Student::marks).reversed()
.thenComparingInt(Student::age));
list.forEach(s -> System.out.print(s.name() + " "));
System.out.println();
}
}Output:
Arjun Kabir Meera Riya
Arjun Meera Riya Kabir Kabir is last in the second line because his marks are lowest; Meera comes before Riya because they tie on 88 marks and Meera is younger.
32. What is a thread? How do you create one in Java?
A thread is a separate path of execution inside a program. Threads share the same heap memory, which makes them cheaper than processes but also means they can interfere with each other. There are two classic ways to create one: extend Thread, or implement Runnable and pass it to a Thread.
public class Main {
public static void main(String[] args) throws InterruptedException {
// 1. extend Thread
Thread t1 = new Thread() {
public void run() { System.out.println("Thread 1 running"); }
};
// 2. implement Runnable (preferred), here with a lambda
Thread t2 = new Thread(() -> System.out.println("Thread 2 running"));
t1.start();
t1.join(); // wait for t1 to finish
t2.start();
t2.join();
System.out.println("Both done, main thread ends");
}
}Output:
Thread 1 running
Thread 2 running
Both done, main thread endsImplementing Runnable is preferred because your class can still extend another class, and the task is separated from the thread that runs it. Always call start(), not run(): run() just executes the code in the current thread. In real projects, you usually submit tasks to an ExecutorService instead of creating threads by hand (question 61).
33. What is the difference between a process and a thread?
| Process | Thread | |
|---|---|---|
| What it is | A running program with its own memory | A unit of execution inside a process |
| Memory | Separate address space | Shares heap with other threads; has its own stack |
| Cost to create and switch | High | Low |
| Communication | Needs IPC: pipes, sockets, files | Through shared objects, so needs synchronisation |
| If one crashes | Others are unaffected | Can bring down the whole process |
A JVM is one process; your main method runs on the “main” thread, and the JVM runs others in the background, such as garbage collector threads.
34. What is garbage collection in Java?
Garbage collection (GC) automatically frees heap memory used by objects that are no longer reachable. An object is reachable if a chain of references leads to it from a GC root: local variables on thread stacks, static fields, and a few others. Anything unreachable is garbage.
- You cannot force GC.
System.gc()is only a request the JVM may ignore. - An object becomes eligible when you set its last reference to null, the reference goes out of scope, or it is only reachable from other garbage (cycles are fine for the GC).
- The heap is split into a young generation (new objects, collected often and cheaply) and an old generation (long-lived objects), because most objects die young.
- The default collector since Java 9 is G1. Question 79 covers the different collectors.
35. What is the difference between stack and heap memory?
| Stack | Heap | |
|---|---|---|
| Stores | Method calls (frames), local primitives, references | All objects and arrays, and their instance fields |
| Owned by | One stack per thread | Shared by all threads |
| Lifetime | Freed automatically when the method returns | Freed by the garbage collector |
| Size | Small (set with -Xss) | Large (set with -Xms and -Xmx) |
| Error when full | StackOverflowError (often deep recursion) | OutOfMemoryError: Java heap space |
In Student s = new Student(); inside a method, the reference s lives on the stack and the Student object lives on the heap.
36. What is the difference between == and equals()?
== compares primitive values, or for objects it checks whether two references point to the same object. equals() compares the content of two objects, as defined by the class. The version in Object is the same as ==, so classes like String, Integer and the collections override it.
Practical rules: use == for primitives and enums; use equals() for strings, wrappers and your own objects; use Objects.equals(a, b) when either side might be null. If you override equals(), you must also override hashCode() (question 41).
37. What are the differences between break, continue and return?
breakexits the nearest loop or switch immediately.continueskips the rest of the current iteration and moves to the next one.returnexits the whole method, optionally with a value.
Java also has labelled break and continue for nested loops, for example outer: for (...) { for (...) { if (found) break outer; } }. They are handy in search problems but use them sparingly, because they make the flow harder to follow.
38. What is a package? Why do we use import?
A package is a namespace that groups related classes, such as java.util or com.codeanddebug.payments. Packages avoid name clashes (you can have two classes called Date in different packages), control access through the default and protected modifiers, and match the folder structure of your code.
import lets you use a class by its short name instead of the full name. java.lang (String, Math, System) is imported automatically. import java.util.*; imports all classes in that package but not sub-packages, and has no run-time cost; it is only a compile-time shortcut.
39. What is type casting? Explain widening and narrowing.
Widening (implicit) converts a smaller type to a larger one with no data loss, so Java does it automatically: byte → short → int → long → float → double. Narrowing (explicit) goes the other way and needs a cast, because data can be lost: int x = (int) 9.99; gives 9, and (byte) 130 gives -126 because the value wraps around.
For objects, upcasting (child to parent reference) is automatic and always safe. Downcasting (parent to child) needs a cast and throws ClassCastException at run time if the object is not really that type, so check with instanceof first, or use pattern matching: if (obj instanceof String s).
40. What are the main features introduced in Java 8?
- Lambda expressions and functional interfaces (Predicate, Function, Supplier, Consumer).
- Stream API for filter, map, reduce and collect on collections.
- Default and static methods in interfaces.
- Method references such as
String::length. - Optional to represent a value that may be missing.
- New date and time API (
java.time: LocalDate, LocalDateTime, ZonedDateTime, Duration). - CompletableFuture for asynchronous programming.
- Metaspace replaced PermGen, and ConcurrentHashMap was redesigned.
Java 8 is still the most asked-about version in Indian interviews because many companies moved from it to Java 11, 17 or 21 only recently. Questions 63 to 72 cover these features with code.
Intermediate Java interview questions
These 35 questions are for candidates with one to three years of experience: HashMap internals, iterators, generics, immutability, serialization, multithreading, and the Java 8 stream and lambda questions that almost every company asks.
41. What is the contract between equals() and hashCode()? What happens if you override only equals()?
- If two objects are equal according to
equals(), they must have the samehashCode(). - Two objects with the same hash code do not have to be equal (that is a collision).
- Both methods must be consistent: calling them again without changing the object gives the same result.
import java.util.*;
public class Main {
static class NoHash {
String id;
NoHash(String id) { this.id = id; }
@Override public boolean equals(Object o) {
return o instanceof NoHash n && id.equals(n.id);
}
// hashCode() NOT overridden
}
static class WithHash {
String id;
WithHash(String id) { this.id = id; }
@Override public boolean equals(Object o) {
return o instanceof WithHash w && id.equals(w.id);
}
@Override public int hashCode() { return Objects.hash(id); }
}
public static void main(String[] args) {
Set<NoHash> a = new HashSet<>();
a.add(new NoHash("E101"));
a.add(new NoHash("E101"));
System.out.println("Without hashCode: " + a.size());
Set<WithHash> b = new HashSet<>();
b.add(new WithHash("E101"));
b.add(new WithHash("E101"));
System.out.println("With hashCode: " + b.size());
}
}Output:
Without hashCode: 2
With hashCode: 1HashSet and HashMap first use the hash code to pick a bucket, and only then call equals() inside it. Without hashCode(), the two “equal” objects get different default hash codes, land in different buckets, and both are stored. Generate both methods together, use Objects.hash(), or use a record, which does it for you.
42. How does HashMap work internally?
A HashMap is an array of buckets (16 by default). To store a key, it calls key.hashCode(), mixes the high bits into the low bits, and uses hash & (n - 1) to pick a bucket. Each bucket holds a linked list of entries (key, value, hash, next).
- put: find the bucket; if a key there is
equals()to the new key, replace its value, otherwise add a new entry. - get: find the bucket, then walk it comparing hashes and keys with equals().
- Collisions: different keys in one bucket. Since Java 8, a bucket with more than 8 entries (when the table has at least 64 buckets) turns into a red-black tree, so the worst case drops from O(n) to O(log n).
- Resizing: when size exceeds capacity × load factor (0.75), the table doubles and entries are redistributed.
- One null key is allowed (it goes to bucket 0), and any number of null values.
Average put and get are O(1). This is why mutable keys are dangerous: if a key’s fields change after you insert it, its hash changes and you can no longer find the entry.
43. What is the difference between HashMap, Hashtable and ConcurrentHashMap?
| Point | HashMap | Hashtable | ConcurrentHashMap |
|---|---|---|---|
| Thread safe | No | Yes, every method is synchronized | Yes, with fine-grained locking and CAS |
| Performance with many threads | Not safe to share | Slow: one lock for the whole table | Fast: reads mostly lock-free |
| null keys or values | One null key, many null values | Not allowed | Not allowed |
| Iterator | Fail-fast | Fail-fast (Enumeration is not) | Weakly consistent, never throws ConcurrentModificationException |
| Status | Default choice | Legacy, avoid | Use for shared maps |
Collections.synchronizedMap() is another option, but it also uses one lock for everything. Question 87 explains how ConcurrentHashMap achieves its speed.
44. What are fail-fast and fail-safe iterators?
A fail-fast iterator (ArrayList, HashMap and most java.util collections) keeps a modification count. If the collection is changed structurally while you iterate, other than through the iterator itself, the next call throws ConcurrentModificationException. A fail-safe iterator (CopyOnWriteArrayList, ConcurrentHashMap) works on a snapshot or tolerates changes, so it never throws.
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
try {
for (Integer n : nums)
if (n % 2 == 0) nums.remove(n); // modifying while looping
} catch (ConcurrentModificationException e) {
System.out.println("Fail-fast: " + e.getClass().getSimpleName());
}
nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
nums.removeIf(n -> n % 2 == 0); // the safe way
System.out.println("removeIf: " + nums);
List<Integer> safe = new CopyOnWriteArrayList<>(List.of(1, 2, 3));
for (Integer n : safe) safe.add(n * 10); // fail-safe: loops over a snapshot
System.out.println("CopyOnWriteArrayList: " + safe);
}
}Output:
Fail-fast: ConcurrentModificationException
removeIf: [1, 3, 5]
CopyOnWriteArrayList: [1, 2, 3, 10, 20, 30]To remove while looping, use iterator.remove() or removeIf(). Fail-fast is a best-effort bug detector, not a guarantee; do not rely on it for thread safety.
45. What is the difference between Iterator and ListIterator?
| Iterator | ListIterator | |
|---|---|---|
| Works on | Any Collection | Lists only |
| Direction | Forward only | Forward and backward (hasPrevious, previous) |
| Modify | remove() | remove(), set(), add() |
| Index | No | nextIndex(), previousIndex() |
The for-each loop uses an Iterator behind the scenes, which is why removing inside a for-each loop triggers the fail-fast check from the previous question.
46. When would you use a PriorityQueue, ArrayDeque or TreeMap?
PriorityQueue: a binary heap that always gives you the smallest element (or the largest with a reversed comparator) in O(log n). Use it for “top K”, scheduling and Dijkstra’s algorithm.ArrayDeque: a resizable circular array that works as both a stack and a queue, faster than Stack and LinkedList. Use it for BFS, undo history and sliding window problems.TreeMap: a red-black tree that keeps keys sorted and supports range queries likefloorKey(),ceilingKey()andsubMap()in O(log n). Use it for leaderboards, time-based lookups and booking slots.
These three show up again and again in coding rounds. Our DSA interview cheat sheet lists which data structure fits each problem pattern.
47. What are generics? What is type erasure, and what do ? extends and ? super mean?
Generics let you write classes and methods that work with any type while keeping compile-time type safety: List<String> will not accept an Integer, and you never need a cast when reading from it.
import java.util.*;
public class Main {
// generic method: works for any type that can be compared
static <T extends Comparable<T>> T max(List<T> list) {
T best = list.get(0);
for (T x : list) if (x.compareTo(best) > 0) best = x;
return best;
}
// upper-bounded wildcard: read numbers of any subtype
static double sum(List<? extends Number> list) {
double s = 0;
for (Number n : list) s += n.doubleValue();
return s;
}
public static void main(String[] args) {
System.out.println(max(List.of(4, 19, 7)));
System.out.println(max(List.of("pear", "apple", "mango")));
System.out.println(sum(List.of(1, 2, 3)));
System.out.println(sum(List.of(1.5, 2.5)));
List<String> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
System.out.println(a.getClass() == b.getClass()); // type erasure
}
}Output:
19
pear
6.0
4.0
true- Type erasure: generic types exist only at compile time. The compiler checks them, inserts casts and removes them, so at run time both lists are plain ArrayList. That is why you cannot write
new T()orList<int>. ? extends Number: accepts a list of Number or any subtype. You can read Numbers from it but not add to it.? super Integer: accepts a list of Integer or any supertype. You can add Integers but reads only give you Object.- Memory aid PECS: Producer Extends, Consumer Super.
48. How do you create an immutable class in Java?
- Make the class
finalso no subclass can add mutable behaviour. - Make all fields
private final. - Set every field in the constructor and provide no setters.
- For mutable fields such as lists or dates, store a defensive copy in the constructor and return a copy or an unmodifiable view from getters.
import java.util.*;
public class Main {
static final class Employee { // 1. final class
private final String name; // 2. private final fields
private final List<String> skills;
Employee(String name, List<String> skills) {
this.name = name;
this.skills = List.copyOf(skills); // 3. defensive copy in
}
String getName() { return name; } // 4. no setters
List<String> getSkills() { return skills; } // already unmodifiable
}
public static void main(String[] args) {
List<String> s = new ArrayList<>(List.of("Java", "SQL"));
Employee e = new Employee("Riya", s);
s.add("Python"); // caller changes its own list
System.out.println(e.getSkills()); // object is unaffected
try {
e.getSkills().add("Go");
} catch (UnsupportedOperationException ex) {
System.out.println("Cannot modify skills");
}
}
}Output:
[Java, SQL]
Cannot modify skillsImmutable objects are thread safe, can be cached and shared freely, and make good HashMap keys. Since Java 16, a record gives you most of this in one line, though you still need the defensive copy for mutable fields.
49. What is the difference between a shallow copy and a deep copy?
A shallow copy copies the fields of an object, so any referenced objects (like a list) are shared between the original and the copy. A deep copy also copies the referenced objects, so the two are fully independent.
import java.util.*;
public class Main {
static class Team implements Cloneable {
String name;
List<String> members;
Team(String name, List<String> members) { this.name = name; this.members = members; }
Team shallowCopy() throws CloneNotSupportedException {
return (Team) super.clone(); // copies the reference to the list
}
Team deepCopy() {
return new Team(name, new ArrayList<>(members)); // new list
}
}
public static void main(String[] args) throws Exception {
Team original = new Team("Backend", new ArrayList<>(List.of("Riya")));
Team shallow = original.shallowCopy();
Team deep = original.deepCopy();
original.members.add("Arjun");
System.out.println("Shallow copy sees: " + shallow.members);
System.out.println("Deep copy sees: " + deep.members);
}
}Output:
Shallow copy sees: [Riya, Arjun]
Deep copy sees: [Riya]Object.clone() makes a shallow copy and needs the Cloneable marker interface. Many developers avoid clone() because it is awkward and easy to get wrong, and use a copy constructor or a static factory method instead, as deepCopy() does here.
50. What is serialization? What does the transient keyword do?
Serialization converts an object into a stream of bytes so it can be saved to a file or sent over the network; deserialization rebuilds it. A class opts in by implementing the Serializable marker interface, and you write and read objects with ObjectOutputStream and ObjectInputStream.
transientfields are skipped. Use it for passwords, caches and fields that cannot be serialized, such as a database connection. They come back as default values (null, 0, false).- Static fields are not serialized because they belong to the class.
serialVersionUIDis a version number. If the class changes and the UIDs do not match, deserialization fails withInvalidClassException. Declare it explicitly.- Java’s built-in serialization has a long history of security problems. Modern systems usually send JSON (Jackson, Gson) or Protocol Buffers instead.
51. What are the types of nested classes in Java?
| Type | Declared | Needs an outer object? | Typical use |
|---|---|---|---|
| Static nested class | Inside a class, with static | No | Helpers like Map.Entry, the Builder pattern |
| Inner class | Inside a class, without static | Yes, and it can use the outer object’s fields | An iterator that reads its list’s data |
| Local class | Inside a method | Yes | Rare, a helper used in one method |
| Anonymous class | Inline, with no name | Depends on where | One-off implementations; mostly replaced by lambdas |
An inner class holds a hidden reference to its outer object. If the inner object lives longer, for example a listener that is never removed, it keeps the outer object in memory. Prefer static nested classes unless you need that reference.
52. What is a marker interface? Give examples.
A marker interface has no methods. Implementing it only “tags” a class so that the JVM or a library treats it differently. Examples: Serializable (allows serialization), Cloneable (allows Object.clone()) and RandomAccess (tells algorithms that get(index) is fast, as in ArrayList).
Since Java 5, annotations such as @FunctionalInterface or @Entity do the same job more flexibly, so new code rarely defines marker interfaces. One advantage of a marker interface is that it is a type, so the compiler can check it.
53. What is try-with-resources?
Introduced in Java 7, it closes resources automatically. Any object that implements AutoCloseable (files, streams, JDBC connections, sockets) can be declared in the brackets after try, and its close() method runs when the block ends, even if an exception is thrown.
public class Main {
static class Resource implements AutoCloseable {
String name;
Resource(String name) { this.name = name; System.out.println("open " + name); }
public void close() { System.out.println("close " + name); }
}
public static void main(String[] args) {
try (Resource db = new Resource("database");
Resource file = new Resource("file")) {
System.out.println("working");
throw new IllegalStateException("something failed");
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
}
}
}Output:
open database
open file
working
close file
close database
caught: something failedResources close in reverse order of opening. If close() itself throws while another exception is already in flight, the close exception is added to the main one as a suppressed exception (getSuppressed()) instead of replacing it. This removes the need for long, error-prone finally blocks.
54. What is the difference between Error and Exception? When do you get StackOverflowError and OutOfMemoryError?
An Exception is a condition your program can reasonably handle: a missing file, bad input, a network timeout. An Error is a serious problem in the JVM environment that an application usually cannot recover from, so you should not catch it.
StackOverflowError: the thread stack is full, almost always from recursion without a proper base case, or recursion that is simply too deep.OutOfMemoryError: Java heap space: objects keep piling up, from a memory leak or a heap that is too small for the data.OutOfMemoryError: Metaspace: too many classes loaded, often from class loader leaks in application servers.
Debug OOM by running with -XX:+HeapDumpOnOutOfMemoryError and opening the dump in Eclipse MAT or VisualVM (question 80).
55. What are multi-catch and exception chaining?
Multi-catch (Java 7) handles several unrelated exception types in one block: catch (IOException | SQLException e). The types cannot be parent and child of each other, and e is implicitly final.
Exception chaining wraps a low-level exception in a higher-level one without losing the original: throw new ServiceException("Could not load user", e); The original is available through getCause() and appears as “Caused by” in the stack trace. Always pass the cause; throwing a new exception without it hides the real error.
56. What are the states in a thread’s life cycle?
| State | Meaning |
|---|---|
NEW | Created but start() not yet called |
RUNNABLE | Running or ready to run, waiting for the CPU |
BLOCKED | Waiting to get a monitor lock to enter a synchronized block |
WAITING | Waiting with no timeout: wait(), join(), LockSupport.park() |
TIMED_WAITING | Waiting with a timeout: sleep(ms), wait(ms), join(ms) |
TERMINATED | run() has finished, normally or with an exception |
You can read the state with thread.getState(). A thread dump (question 98) shows every thread with its state, which is the first thing to look at when an application hangs.
57. What is synchronization? What is a race condition?
A race condition happens when two threads read and update shared data at the same time and the result depends on timing. count++ looks like one step but is three: read, add, write. Two threads can both read 5 and both write 6, losing an update.
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static int syncCount = 0;
static AtomicInteger atomicCount = new AtomicInteger();
static synchronized void increment() { syncCount++; }
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
increment();
atomicCount.incrementAndGet();
}
};
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("synchronized: " + syncCount);
System.out.println("AtomicInteger: " + atomicCount.get());
}
}Output:
synchronized: 200000
AtomicInteger: 200000synchronized makes a method or block run in one thread at a time, using the object’s monitor lock (or the class’s, for static methods). It also guarantees that changes made inside are visible to the next thread that takes the lock. For a simple counter, AtomicInteger is faster because it uses a lock-free compare-and-swap. Without either, the count above would usually come out below 200,000.
58. What does the volatile keyword do? Is it enough for thread safety?
Each CPU core may keep its own cached copy of a variable. volatile guarantees visibility: every write goes straight to main memory and every read sees the latest value. It also stops the compiler and CPU from reordering instructions around it.
It does not make compound actions atomic. volatile int count; count++; is still a race. Use volatile for simple flags written by one thread and read by others, like volatile boolean running = false; to stop a worker, and in double-checked locking. Use synchronized or atomic classes for read-modify-write.
59. What is the difference between wait(), sleep() and join()?
| wait() | sleep() | join() | |
|---|---|---|---|
| Defined in | Object | Thread (static) | Thread |
| Releases the lock? | Yes | No | Not applicable |
| Must hold the lock? | Yes, call inside synchronized | No | No |
| Wakes up when | notify() / notifyAll(), or timeout | Time passes | The other thread finishes |
| Use for | Coordination between threads | Pausing | Waiting for a thread to complete |
Always call wait() in a loop that rechecks the condition, because threads can wake up spuriously. In modern code, prefer higher-level tools like BlockingQueue, CountDownLatch or CompletableFuture over raw wait and notify.
60. What is a deadlock? How do you prevent it?
A deadlock is when two or more threads wait for each other forever. Thread 1 holds lock A and wants lock B; thread 2 holds lock B and wants lock A. Neither can continue. Four conditions must all hold: mutual exclusion, hold and wait, no pre-emption, and circular wait.
- Lock ordering: always take locks in the same global order (for example by account ID in a money transfer). This breaks the circular wait and is the most common fix.
- Timeouts: use
ReentrantLock.tryLock(timeout)and back off if you cannot get the second lock. - Hold locks briefly: never call unknown code or do I/O while holding a lock.
- Detect: a thread dump (jstack) reports “Found one Java-level deadlock” with the threads involved.
61. What is ExecutorService? Why use a thread pool? What is the difference between Runnable and Callable?
Creating a thread for every task is expensive and can exhaust memory under load. A thread pool keeps a fixed set of threads that pick up tasks from a queue. ExecutorService is the Java API for this.
import java.util.*;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
List<Callable<Integer>> tasks = new ArrayList<>();
for (int n = 1; n <= 5; n++) {
final int x = n;
tasks.add(() -> x * x); // Callable returns a value
}
List<Future<Integer>> results = pool.invokeAll(tasks);
int total = 0;
for (Future<Integer> f : results) total += f.get(); // get() waits for the result
System.out.println("Sum of squares: " + total);
pool.shutdown();
System.out.println("Terminated: " + pool.awaitTermination(1, TimeUnit.SECONDS));
}
}Output:
Sum of squares: 55
Terminated: true| Runnable | Callable | |
|---|---|---|
| Method | void run() | V call() throws Exception |
| Returns a value | No | Yes, through a Future |
| Checked exceptions | Cannot throw them | Can throw them |
Future.get() blocks until the result is ready. Always shut a pool down, or the JVM will not exit. In production, create a ThreadPoolExecutor with a bounded queue rather than newFixedThreadPool, whose queue is unbounded.
62. What are atomic classes? What is compare-and-swap (CAS)?
java.util.concurrent.atomic has classes like AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Their operations, such as incrementAndGet() and compareAndSet(), are atomic without using locks.
They rely on compare-and-swap, a single CPU instruction: “if the value is still 5, set it to 6, otherwise fail”. On failure the code simply reads the new value and retries. With little contention, this is much faster than locking. With very heavy contention on one counter, LongAdder is faster still, because it spreads updates across several cells and adds them up when you read.
63. What is a lambda expression? What is a functional interface?
A functional interface has exactly one abstract method (it can still have default and static methods). A lambda is a short way to write an implementation of that one method: (params) -> expression or (params) -> { statements }.
import java.util.*;
import java.util.function.*;
public class Main {
@FunctionalInterface
interface Discount { double apply(double price); } // one abstract method
public static void main(String[] args) {
Discount festive = p -> p * 0.8;
System.out.println(festive.apply(1000));
Predicate<Integer> isEven = n -> n % 2 == 0;
Function<String, Integer> length = String::length;
Supplier<List<String>> newList = ArrayList::new;
BiFunction<Integer, Integer, Integer> add = Integer::sum;
Consumer<String> greet = name -> System.out.println("Hi " + name);
System.out.println(isEven.test(10));
System.out.println(length.apply("Code and Debug"));
System.out.println(newList.get().size());
System.out.println(add.apply(7, 8));
greet.accept("Riya");
}
}Output:
800.0
true
14
0
15
Hi Riya| Built-in interface | Method | Use |
|---|---|---|
| Predicate<T> | boolean test(T) | Conditions, filter() |
| Function<T, R> | R apply(T) | Transformations, map() |
| Consumer<T> | void accept(T) | Side effects, forEach() |
| Supplier<T> | T get() | Lazy creation, orElseGet() |
| BiFunction<T, U, R> | R apply(T, U) | Two inputs, one output |
A lambda can use local variables from its surrounding method only if they are effectively final (never reassigned).
64. What is the Stream API? What are intermediate and terminal operations?
A stream is a pipeline that processes data from a source (a collection, an array, a file) through a series of operations. It does not store data and does not change the source.
- Intermediate operations such as
filter,map,sorted,distinctandlimitreturn a new stream and are lazy: nothing runs until a terminal operation is called. - Terminal operations such as
collect,forEach,reduce,countandfindFirststart the processing and produce a result.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(5, 12, 8, 3, 20, 7, 12);
List<Integer> result = nums.stream()
.filter(n -> { // intermediate (lazy)
System.out.println("checking " + n);
return n > 6;
})
.map(n -> n * 10) // intermediate (lazy)
.limit(2) // stop after two results
.collect(Collectors.toList()); // terminal: starts the work
System.out.println(result);
System.out.println(nums.stream().distinct().sorted().toList());
System.out.println(nums.stream().mapToInt(Integer::intValue).sum());
}
}Output:
checking 5
checking 12
checking 8
[120, 80]
[3, 5, 7, 8, 12, 20]
67Look at the output: only 5, 12 and 8 were checked. Because of laziness and limit(2), the stream stopped as soon as it had two results. A stream can be used only once; calling a second terminal operation throws IllegalStateException.
65. What is the difference between map() and flatMap()?
map() turns each element into exactly one new element. flatMap() turns each element into a stream of elements and then flattens all those streams into one.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<String> lines = List.of("java is fun", "streams are fun");
List<String[]> mapped = lines.stream()
.map(l -> l.split(" ")) // one array per line
.toList();
System.out.println("map gives " + mapped.size() + " arrays");
List<String> words = lines.stream()
.flatMap(l -> Arrays.stream(l.split(" "))) // flatten into one stream
.distinct()
.toList();
System.out.println("flatMap gives " + words);
}
}Output:
map gives 2 arrays
flatMap gives [java, is, fun, streams, are]Use flatMap whenever each item expands into several: the words in each line, the orders of each customer, the elements of a list of lists. The same idea exists in Optional: flatMap avoids ending up with Optional<Optional<T>>.
66. How do you use Collectors.groupingBy, partitioningBy and joining?
import java.util.*;
import java.util.stream.*;
public class Main {
record Employee(String name, String dept, int salary) {}
public static void main(String[] args) {
List<Employee> emps = List.of(
new Employee("Riya", "Tech", 90000), new Employee("Arjun", "Sales", 45000),
new Employee("Meera", "Tech", 120000), new Employee("Kabir", "HR", 50000),
new Employee("Isha", "Sales", 60000));
Map<String, Long> countByDept = emps.stream()
.collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.counting()));
System.out.println(countByDept);
Map<String, Double> avgSalary = emps.stream()
.collect(Collectors.groupingBy(Employee::dept, TreeMap::new,
Collectors.averagingInt(Employee::salary)));
System.out.println(avgSalary);
Map<Boolean, List<String>> highPaid = emps.stream()
.collect(Collectors.partitioningBy(e -> e.salary() > 55000,
Collectors.mapping(Employee::name, Collectors.toList())));
System.out.println(highPaid);
String names = emps.stream().map(Employee::name).collect(Collectors.joining(", ", "[", "]"));
System.out.println(names);
}
}Output:
{HR=1, Sales=2, Tech=2}
{HR=50000.0, Sales=52500.0, Tech=105000.0}
{false=[Arjun, Kabir], true=[Riya, Meera, Isha]}
[Riya, Arjun, Meera, Kabir, Isha]groupingBy(classifier)builds a Map from key to a List of elements. Add a downstream collector such ascounting(),averagingInt(),summingInt()ormapping()to summarise each group, and a map factory such asTreeMap::newfor sorted keys.partitioningBy(predicate)always gives a map with exactly two keys, false and true.joining(", ")concatenates strings, with an optional prefix and suffix.
This is the Java version of SQL’s GROUP BY, and “group employees by department and find the average salary” is one of the most common Java 8 coding questions. Compare it with our SQL GROUP BY examples.
67. What is Optional and how should you use it?
Optional<T> is a container that either holds a value or is empty. It makes “this might be missing” visible in a method’s return type, so callers handle it instead of getting a NullPointerException.
import java.util.*;
public class Main {
static Map<Integer, String> users = Map.of(1, "Riya", 2, "Arjun");
static Optional<String> findUser(int id) {
return Optional.ofNullable(users.get(id));
}
public static void main(String[] args) {
System.out.println(findUser(1).map(String::toUpperCase).orElse("Guest"));
System.out.println(findUser(9).map(String::toUpperCase).orElse("Guest"));
findUser(2).ifPresent(n -> System.out.println("Found " + n));
System.out.println(findUser(9).isPresent());
try {
findUser(9).orElseThrow(() -> new NoSuchElementException("No user 9"));
} catch (NoSuchElementException e) {
System.out.println(e.getMessage());
}
}
}Output:
RIYA
Guest
Found Arjun
false
No user 9- Create with
Optional.of(x)(x must not be null),Optional.ofNullable(x)orOptional.empty(). - Use it as a return type. Do not use it for fields, method parameters or collections (return an empty list instead).
- Avoid
get()without checking; preferorElse,orElseGet(lazy),orElseThrow,mapandifPresent.
68. What are method references? What are the different kinds?
A method reference is a shorter lambda when the lambda only calls an existing method. s -> s.length() becomes String::length.
| Kind | Syntax | Lambda it replaces |
|---|---|---|
| Static method | Integer::parseInt | s -> Integer.parseInt(s) |
| Instance method of a particular object | System.out::println | x -> System.out.println(x) |
| Instance method of an arbitrary object of a type | String::toUpperCase | s -> s.toUpperCase() |
| Constructor | ArrayList::new | () -> new ArrayList<>() |
69. Why were default methods added to interfaces? How is the diamond problem resolved?
Default methods let library authors add new methods to existing interfaces without breaking every class that implements them. That is how Java 8 added forEach() to Iterable, stream() to Collection and sort() to List.
If a class implements two interfaces with the same default method, it will not compile until the class overrides the method. Inside, it can call a specific version with InterfaceName.super.method(). A method from a superclass always wins over an interface default.
public class Main {
interface Camera { default String start() { return "Camera ready"; } }
interface Phone { default String start() { return "Phone ready"; } }
static class SmartPhone implements Camera, Phone {
@Override
public String start() { // must resolve the conflict
return Camera.super.start() + " and " + Phone.super.start();
}
}
public static void main(String[] args) {
System.out.println(new SmartPhone().start());
}
}Output:
Camera ready and Phone ready70. What is the Java 8 date and time API? Why was it needed?
The old java.util.Date and Calendar were mutable, not thread safe, used months starting at 0, and mixed dates with times and time zones. SimpleDateFormat was not thread safe either. The java.time package fixed all of this with immutable, clear classes.
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate joined = LocalDate.of(2024, 7, 15);
LocalDate review = joined.plusMonths(6);
System.out.println(review);
System.out.println(review.getDayOfWeek());
LocalDate today = LocalDate.of(2026, 11, 30);
System.out.println(ChronoUnit.DAYS.between(joined, today) + " days");
Period p = Period.between(joined, today);
System.out.println(p.getYears() + " years " + p.getMonths() + " months");
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");
LocalDateTime meeting = LocalDateTime.of(2026, 12, 1, 15, 30);
System.out.println(meeting.format(f));
ZonedDateTime ist = meeting.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(ist.withZoneSameInstant(ZoneId.of("America/New_York")).format(f));
}
}Output:
2025-01-15
WEDNESDAY
868 days
2 years 4 months
01 Dec 2026, 03:30 PM
01 Dec 2026, 05:00 AMLocalDate,LocalTime,LocalDateTime: no time zone, for birthdays and schedules.ZonedDateTimeandInstant: an exact moment, for timestamps and converting between zones.Period(years, months, days) andDuration(hours, minutes, seconds).DateTimeFormatter: immutable and thread safe.
71. What do reduce(), findFirst() and anyMatch() do?
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(4, 9, 2, 7);
int sum = nums.stream().reduce(0, Integer::sum);
int product = nums.stream().reduce(1, (a, b) -> a * b);
Optional<Integer> max = nums.stream().reduce(Integer::max);
System.out.println(sum + " " + product + " " + max.get());
System.out.println(nums.stream().filter(n -> n > 3).findFirst().get());
System.out.println(nums.stream().anyMatch(n -> n > 8));
System.out.println(nums.stream().allMatch(n -> n > 1));
}
}Output:
22 504 9
4
true
truereduce(identity, accumulator)combines all elements into one value; without an identity it returns an Optional, because the stream could be empty.findFirst()returns the first element in encounter order.findAny()may return any element and can be faster on parallel streams.anyMatch,allMatchandnoneMatchare short-circuiting: they stop as soon as the answer is known.
For sums and averages of numbers, mapToInt(...).sum() or summaryStatistics() avoid boxing and are clearer than reduce.
72. What is the difference between a Collection and a Stream? When should you use parallel streams?
| Collection | Stream | |
|---|---|---|
| Purpose | Stores data | Computes on data |
| Evaluation | Eager | Lazy |
| Reusable | Yes | No, one terminal operation only |
| Iteration | External (you write the loop) | Internal (the library loops) |
| Size | Finite | Can be infinite (Stream.iterate, generate) |
parallelStream() splits work across the common ForkJoinPool. It helps only for large data, CPU-heavy work and sources that split well (arrays, ArrayList). It hurts for small lists, I/O work, LinkedList sources, ordered operations like limit, and code with shared mutable state. Measure before using it, and never block inside one in a server application.
73. What can enums do in Java beyond simple constants?
A Java enum is a full class: it can have fields, constructors (always private), methods and even abstract methods that each constant implements. Each constant is a single instance created when the enum class loads.
public class Main {
enum Plan {
FREE(0), PRO(2499), TEAM(9999);
private final int price;
Plan(int price) { this.price = price; } // constructor is private
int price() { return price; }
boolean isPaid() { return price > 0; }
}
public static void main(String[] args) {
for (Plan p : Plan.values())
System.out.println(p + " " + p.ordinal() + " Rs " + p.price() + " paid=" + p.isPaid());
Plan chosen = Plan.valueOf("PRO");
switch (chosen) {
case FREE -> System.out.println("Start learning");
case PRO, TEAM -> System.out.println("Unlock all courses");
}
}
}Output:
FREE 0 Rs 0 paid=false
PRO 1 Rs 2499 paid=true
TEAM 2 Rs 9999 paid=true
Unlock all coursesEnums can be used in switch statements, compared safely with ==, and stored efficiently in EnumSet and EnumMap. values() lists all constants and valueOf() converts a string (and throws IllegalArgumentException for an unknown name).
74. How do you write a thread-safe singleton?
A singleton ensures only one object of a class exists. The naive lazy version (if (instance == null) instance = new X();) can create two objects when two threads arrive at once.
public class Main {
// Bill Pugh singleton: lazy and thread-safe without synchronized
static class Config {
private Config() { System.out.println("Config created"); }
private static class Holder { static final Config INSTANCE = new Config(); }
static Config getInstance() { return Holder.INSTANCE; }
}
// Enum singleton: also safe against reflection and serialization
enum Logger {
INSTANCE;
void log(String m) { System.out.println("LOG: " + m); }
}
public static void main(String[] args) {
System.out.println("Before first use");
Config a = Config.getInstance();
Config b = Config.getInstance();
System.out.println(a == b);
Logger.INSTANCE.log("app started");
}
}Output:
Before first use
Config created
true
LOG: app started- Bill Pugh (holder class): the inner class is loaded only on first use, and class loading is thread safe, so you get laziness with no synchronization cost.
- Enum: the simplest and the safest. Joshua Bloch recommends it because it also resists reflection and serialization attacks.
- Double-checked locking: works only if the field is
volatile; interviewers like to ask why (without it, another thread may see a half-constructed object).
In Spring applications you rarely write singletons by hand; beans are singletons by default.
75. What is the difference between Arrays.asList(), List.of() and Collections.unmodifiableList()?
| Arrays.asList(arr) | List.of(…) (Java 9) | Collections.unmodifiableList(list) | |
|---|---|---|---|
| add / remove | UnsupportedOperationException (fixed size) | UnsupportedOperationException | UnsupportedOperationException |
| set(i, x) | Allowed, and it changes the original array | Not allowed | Not allowed |
| null elements | Allowed | NullPointerException | Allowed |
| Linked to the source | Yes, it is a view of the array | No, independent copy | Yes, a read-only view: changes to the original list show through |
A classic trap: Arrays.asList(1, 2, 3).add(4) compiles but throws at run time. For a list you can change, wrap it: new ArrayList<>(List.of(1, 2, 3)). For a truly immutable snapshot of an existing list, use List.copyOf(list).
Java interview questions for experienced candidates
These 25 questions are for senior developers: JVM internals, garbage collection, memory leaks, the Java Memory Model, advanced concurrency, ConcurrentHashMap, virtual threads, modern Java features and production debugging.
76. Explain the architecture of the JVM.
- Class loader subsystem: loads .class files, then links them (verifies the bytecode, prepares static fields, resolves references) and initialises them (runs static blocks).
- Runtime data areas: the heap and metaspace, shared by all threads; and per thread, a JVM stack, a program counter register and a native method stack.
- Execution engine: an interpreter that runs bytecode right away, a JIT compiler (C1 and C2) that compiles hot methods to native code, and the garbage collector.
- Native interface (JNI) and native libraries, for calling C and C++ code.
A good answer walks through what happens on java Main: the class loader loads Main, the bytecode verifier checks it, main() is interpreted at first, and the hot paths are JIT-compiled as the program runs.
77. How does class loading work? What is the parent delegation model?
Java has a hierarchy of class loaders: the Bootstrap loader (core classes from java.base, written in native code), the Platform loader (other JDK modules; it was called the Extension loader before Java 9), and the Application (system) loader (your classpath).
Under parent delegation, a loader first asks its parent to load a class and only tries itself if the parent cannot. This stops anyone from replacing core classes like java.lang.String with their own version, and ensures each class is loaded once per loader. A class is identified by its name plus its loader, so the same class loaded by two loaders gives two different types; app servers and plugin systems use custom loaders for exactly this kind of isolation, and it is also the source of confusing ClassCastExceptions and Metaspace leaks.
78. What are the JVM memory areas? What replaced PermGen?
| Area | Shared? | Holds | Error |
|---|---|---|---|
| Heap: young generation (Eden + 2 survivor spaces) | Yes | New objects | OutOfMemoryError |
| Heap: old generation | Yes | Objects that survived several minor GCs | OutOfMemoryError |
| Metaspace (native memory) | Yes | Class metadata, method bytecode, constant pools | OutOfMemoryError: Metaspace |
| JVM stack | Per thread | Frames with local variables and partial results | StackOverflowError |
| PC register and native stack | Per thread | Current instruction, native calls |
Java 8 removed PermGen, a fixed-size part of the heap for class metadata that often caused “OutOfMemoryError: PermGen space”. Metaspace lives in native memory and grows automatically; cap it with -XX:MaxMetaspaceSize. The String pool moved from PermGen to the main heap in Java 7.
79. What garbage collectors does the JVM offer, and how do you choose?
| Collector | Flag | Best for |
|---|---|---|
| Serial | -XX:+UseSerialGC | Small heaps, single-core containers, simple tools |
| Parallel | -XX:+UseParallelGC | Batch jobs where total throughput matters more than pauses |
| G1 (default since Java 9) | -XX:+UseG1GC | General purpose; splits the heap into regions and aims for a pause target (-XX:MaxGCPauseMillis, 200 ms by default) |
| ZGC | -XX:+UseZGC | Large heaps and low-latency services; pauses under a millisecond, generational since Java 21 |
| Shenandoah | -XX:+UseShenandoahGC | Low latency, similar goals to ZGC |
Most GC work happens in two kinds of collections: frequent, cheap minor GCs in the young generation, and rarer major or full GCs of the old generation. Choose by your goal (throughput or latency), then tune heap size first; that fixes more problems than any flag. Measure with GC logs (-Xlog:gc*) rather than guessing.
80. Can Java have memory leaks? How do you find one?
Yes. GC frees only unreachable objects, so a leak in Java is an object that is still referenced but no longer needed. Common causes:
- Static collections and caches that only grow. Use a bounded cache (Caffeine) or eviction.
- Listeners and callbacks that are registered and never removed.
ThreadLocalvalues in pooled threads that are never removed (question 88).- Inner classes and lambdas that capture a large outer object.
- Unclosed resources such as streams, connections and result sets.
- Keys whose hashCode changes after being added to a HashMap.
To find one: watch the heap after each full GC in your monitoring; if the floor keeps rising, you have a leak. Take a heap dump (jcmd <pid> GC.heap_dump file.hprof, or automatically with -XX:+HeapDumpOnOutOfMemoryError), open it in Eclipse MAT, and follow the “dominator tree” and “path to GC roots” to see who is holding the memory.
81. What is the JIT compiler? How does it make Java fast?
The JVM starts by interpreting bytecode, which is slow but starts instantly. It counts how often each method and loop runs. Once code is “hot”, the Just-In-Time compiler compiles it to native machine code. HotSpot uses tiered compilation: C1 compiles quickly with light optimisation, and C2 later recompiles the hottest code with aggressive optimisation based on real profiling data.
Key optimisations: inlining small methods, escape analysis (an object that never leaves a method can live on the stack or be eliminated entirely), loop unrolling, removing bounds checks, and deoptimisation when an assumption turns out wrong. This is why benchmarks need a warm-up phase (use JMH), and why projects like GraalVM native image and CDS exist to cut start-up time.
82. What are strong, soft, weak and phantom references?
| Reference | Collected when | Use |
|---|---|---|
| Strong (normal) | Never while reachable | Everyday code |
SoftReference | Only when memory is running low | Memory-sensitive caches |
WeakReference | At the next GC once no strong reference remains | WeakHashMap, canonical maps, listener lists |
PhantomReference | After finalization; get() always returns null | Clean-up actions after an object is gone (Cleaner) |
A WeakHashMap entry disappears when nothing else references its key, which makes it useful for attaching metadata to objects without keeping them alive. For real caches, a library like Caffeine with size or time limits is usually more predictable than soft references.
83. What is the Java Memory Model? What does happens-before mean?
The Java Memory Model defines when a write by one thread is guaranteed to be visible to another. Without it, compilers and CPUs are free to cache values and reorder instructions, so another thread might see stale or half-written data.
The key idea is the happens-before relation: if action A happens-before B, then B sees everything A did. Rules that create it:
- Unlocking a monitor happens-before every later lock of the same monitor.
- A write to a
volatilefield happens-before every later read of it. Thread.start()happens-before any action in the started thread, and all actions in a thread happen-before another thread returns fromjoin()on it.- Final fields set in a constructor are visible to any thread that sees the object, if
thisdid not escape during construction. - Actions in one thread happen in program order, and the relation is transitive.
84. What is the difference between synchronized and ReentrantLock?
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Release | Automatic at the end of the block | Manual: unlock() in finally |
| Try without waiting | No | tryLock(), tryLock(timeout) |
| Interruptible wait | No | lockInterruptibly() |
| Fairness | No | Optional fair mode |
| Conditions | One wait set (wait/notify) | Many Condition objects |
| Read/write split | No | ReentrantReadWriteLock, StampedLock |
Both are reentrant: a thread that holds the lock can take it again. Use synchronized by default because it is simpler and cannot be forgotten. Reach for ReentrantLock when you need timeouts, interruptible waits, several conditions or a read-write lock. Before Java 24, synchronized could also “pin” virtual threads during blocking calls, which was another reason to prefer ReentrantLock in virtual-thread code.
85. Explain CountDownLatch, CyclicBarrier and Semaphore.
| Class | What it does | Reusable? | Example |
|---|---|---|---|
| CountDownLatch | Threads wait until a count reaches zero | No | Main thread waits until 5 services have started |
| CyclicBarrier | A fixed number of threads wait for each other at a barrier point | Yes | Parallel simulation steps that must finish together |
| Semaphore | Limits how many threads can use a resource at once | Yes | At most 10 concurrent calls to a payment API |
| Phaser | A flexible barrier where parties can register and leave | Yes | Multi-phase tasks with a changing number of workers |
All of these are in java.util.concurrent and are built on AbstractQueuedSynchronizer (AQS), the same framework behind ReentrantLock.
86. What is CompletableFuture? How is it better than Future?
A plain Future can only be checked or blocked on with get(). CompletableFuture (Java 8) lets you chain steps, combine several async results and handle errors without blocking, much like promises in JavaScript.
import java.util.concurrent.*;
public class Main {
static int price(String item) { return item.equals("laptop") ? 55000 : 1200; }
public static void main(String[] args) {
CompletableFuture<Integer> laptop = CompletableFuture.supplyAsync(() -> price("laptop"));
CompletableFuture<Integer> mouse = CompletableFuture.supplyAsync(() -> price("mouse"));
int total = laptop.thenCombine(mouse, Integer::sum) // both run in parallel
.thenApply(t -> (int) (t * 1.18)) // add GST
.join();
System.out.println("Total with GST: " + total);
String r = CompletableFuture.supplyAsync(() -> 10 / 0)
.thenApply(x -> "result " + x)
.exceptionally(ex -> "failed: " + ex.getCause().getMessage())
.join();
System.out.println(r);
}
}Output:
Total with GST: 66316
failed: / by zerosupplyAsyncandrunAsyncstart work, by default on the common ForkJoinPool. Pass your own executor for I/O work.thenApplytransforms a result,thenComposechains another async call,thenCombinejoins two independent results, andallOfandanyOfwait for groups.exceptionallyandhandlerecover from errors; the original exception arrives wrapped in a CompletionException.
87. How does ConcurrentHashMap work internally in Java 8 and later?
Before Java 8, it split the table into 16 segments, each with its own lock. Java 8 dropped segments. Now it uses a single array of bins like HashMap, and:
- Reads take no lock; nodes use volatile fields, so a reader always sees a consistent value.
- Inserting into an empty bin uses a lock-free CAS.
- Updating a non-empty bin synchronizes only on that bin’s first node, so writers to different bins never block each other.
- Long bins turn into trees, as in HashMap.
- Resizing is done cooperatively: threads that arrive during a resize help move bins.
size()is an estimate built from counter cells, similar to LongAdder.
For atomic updates, use compute(), merge() or computeIfAbsent(). A “check then put” with containsKey followed by put is still a race, even on a ConcurrentHashMap.
88. What is ThreadLocal? What is the risk of using it in a thread pool?
ThreadLocal gives each thread its own copy of a variable. It is used for per-request data such as the logged-in user, a transaction or a database connection, and to make non-thread-safe objects (like the old SimpleDateFormat) safe by giving each thread one.
The risk: in a thread pool, threads live for the life of the application. If you set a value and never call remove(), it stays attached to that thread. The next request on that thread may see the previous user’s data, and large values leak memory, especially in app servers where they also pin the class loader. Always clean up in a finally block. With virtual threads, prefer ScopedValue (final in Java 25) for passing context.
89. What are virtual threads (Java 21)? When should you use them?
Platform threads map one to one to OS threads, which cost about 1 MB of stack each, so a server can only hold a few thousand. Virtual threads (Project Loom, final in Java 21) are managed by the JVM. When one blocks on I/O, the JVM parks it and frees the OS carrier thread for another. You can have millions.
import java.util.concurrent.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i ->
ex.submit(() -> {
Thread.sleep(1000); // blocking call, but cheap on a virtual thread
return i;
}));
} // close() waits for all tasks
long secs = (System.currentTimeMillis() - start) / 1000;
System.out.println("10,000 tasks that each sleep 1 second finished in about " + secs + " s");
System.out.println(Thread.ofVirtual().unstarted(() -> {}).isVirtual());
}
}Output:
10,000 tasks that each sleep 1 second finished in about 1 s
true- Use them for many concurrent, I/O-bound tasks such as HTTP calls and database queries, keeping simple blocking code instead of reactive callbacks. Spring Boot 3.2+ enables them with one property.
- They do not make CPU-bound work faster.
- Do not pool them; create one per task.
- Watch for pinning: before Java 24, blocking inside synchronized kept the carrier thread busy. Also be careful with large ThreadLocal values.
90. What is the Fork/Join framework?
Fork/Join (Java 7) runs divide-and-conquer tasks in parallel. A RecursiveTask (returns a value) or RecursiveAction (no value) splits its work in half with fork() until pieces are small enough to compute directly, then combines the results with join().
Its ForkJoinPool uses work stealing: each worker has its own deque of tasks, and an idle worker steals from the tail of a busy one, which keeps all cores busy with little locking. Parallel streams and the default CompletableFuture executor both use the shared ForkJoinPool.commonPool(), which is why blocking calls inside them can starve the whole application.
91. What are records? When would you not use one?
A record (final in Java 16) is a concise, immutable data carrier. From one line, the compiler generates private final fields, a constructor, accessors, equals(), hashCode() and toString().
public class Main {
record Point(int x, int y) {
Point { // compact constructor for validation
if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
}
double distance() { return Math.sqrt(x * x + y * y); }
}
public static void main(String[] args) {
Point p = new Point(3, 4);
Point q = new Point(3, 4);
System.out.println(p); // toString generated
System.out.println(p.x() + ", " + p.y()); // accessors, not getX()
System.out.println(p.equals(q)); // equals and hashCode generated
System.out.println(p.distance());
}
}Output:
Point[x=3, y=4]
3, 4
true
5.0- A compact constructor validates or normalises input.
- Records can implement interfaces and have static fields and extra methods, but cannot extend a class or declare instance fields beyond the components.
- Good for DTOs, API responses, map keys and multiple return values.
- Not suitable for JPA entities (they need a no-argument constructor and mutable fields) or any class that needs to change after creation.
92. What are sealed classes and pattern matching for switch?
A sealed class or interface (Java 17) lists exactly which classes may extend it with permits. Subclasses must be final, sealed or non-sealed. Pattern matching for switch (Java 21) lets a switch test types, deconstruct records and add when guards.
public class Main {
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
static double area(Shape s) {
return switch (s) { // no default needed: compiler knows all cases
case Circle c -> Math.round(Math.PI * c.r() * c.r() * 100) / 100.0;
case Square sq -> sq.side() * sq.side();
case Rectangle(double w, double h) when w == h -> w * w; // record pattern + guard
case Rectangle(double w, double h) -> w * h;
};
}
public static void main(String[] args) {
System.out.println(area(new Circle(1)));
System.out.println(area(new Square(3)));
System.out.println(area(new Rectangle(2, 5)));
Object o = "Code and Debug";
if (o instanceof String str && str.length() > 5) // pattern matching for instanceof
System.out.println(str.toUpperCase());
}
}Output:
3.14
9.0
10.0
CODE AND DEBUGTogether they give you algebraic data types: because the compiler knows every possible Shape, the switch needs no default branch, and if someone adds a new Shape, every switch that does not handle it fails to compile. That is safer than the classic Visitor pattern.
93. Explain var, switch expressions and text blocks.
import java.util.*;
public class Main {
public static void main(String[] args) {
var marks = new HashMap<String, Integer>(); // var: type inferred
marks.put("Riya", 91);
marks.put("Arjun", 67);
for (var e : marks.entrySet()) {
String grade = switch (e.getValue() / 10) { // switch expression
case 10, 9 -> "A";
case 8, 7 -> "B";
default -> {
String g = e.getValue() >= 40 ? "C" : "F";
yield g;
}
};
System.out.println(e.getKey() + ": " + grade);
}
String json = """
{
"course": "Java",
"level": "beginner"
}"""; // text block
System.out.println(json);
}
}Output:
Riya: A
Arjun: C
{
"course": "Java",
"level": "beginner"
}var(Java 10) infers the type of a local variable from its initialiser. It is still static typing; it cannot be used for fields, parameters or with null. Use it when the type is obvious from the right-hand side.- Switch expressions (Java 14) return a value, use arrows with no fall-through, allow several labels per case, and use
yieldto return from a block. - Text blocks (Java 15) are multi-line strings between triple quotes, handy for JSON, SQL and HTML. Common indentation is removed automatically.
94. What is reflection? What are its uses and drawbacks?
Reflection lets code inspect and use classes at run time: list fields and methods, read annotations, create objects and call methods by name, even private ones (with setAccessible(true)). The entry point is the Class object, from obj.getClass() or Class.forName("...").
- Used by: Spring dependency injection, Hibernate and JPA, Jackson, JUnit, and IDE tools.
- Drawbacks: slower than direct calls, no compile-time checking, breaks encapsulation, and since Java 16 the module system blocks reflective access to JDK internals unless you open them with flags.
- Modern frameworks increasingly generate code at compile time (annotation processing) or use
MethodHandleto avoid the cost.
95. How do you create a custom annotation?
Declare it with @interface and add meta-annotations: @Retention (SOURCE, CLASS or RUNTIME) decides how long it is kept, and @Target decides where it can be placed (TYPE, METHOD, FIELD and so on). Elements look like methods and can have defaults: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Audit { String action() default "read"; }.
An annotation does nothing on its own. Something has to read it: reflection at run time (method.getAnnotation(Audit.class)), an annotation processor at compile time (as Lombok and MapStruct do), or a framework such as Spring AOP that applies logic around annotated methods.
96. Which design patterns are used inside the JDK?
| Pattern | Example in the JDK |
|---|---|
| Singleton | Runtime.getRuntime() |
| Factory method | Calendar.getInstance(), List.of(), NumberFormat.getInstance() |
| Builder | StringBuilder, HttpRequest.newBuilder(), Stream.builder() |
| Decorator | new BufferedReader(new InputStreamReader(in)), Collections.synchronizedList() |
| Adapter | Arrays.asList(), InputStreamReader (bytes to characters) |
| Iterator | Iterator in every collection |
| Strategy | Comparator passed to sort() |
| Observer | Event listeners in Swing, Flow.Subscriber |
| Template method | AbstractList, InputStream.read(byte[]) |
| Proxy | java.lang.reflect.Proxy, used by Spring AOP |
97. Explain the SOLID principles with Java examples.
- Single responsibility: a class has one reason to change. Split an InvoiceService that calculates, saves and emails into three classes.
- Open/closed: open for extension, closed for modification. Add a new PaymentMethod class instead of another if-else in checkout().
- Liskov substitution: a subclass must work wherever its parent does. A Square that breaks Rectangle’s setWidth/setHeight behaviour violates it.
- Interface segregation: many small interfaces beat one large one. Do not force a Printer class to implement scan() and fax().
- Dependency inversion: depend on abstractions. OrderService should take a PaymentGateway interface in its constructor, not create a RazorpayClient itself. This is what Spring’s dependency injection is built on.
Interviewers usually follow up with “show me where you applied this in your project”, so prepare one real example. Our OOPs interview questions cover these principles in more depth.
98. A Java service in production has high CPU usage or hangs. How do you investigate?
- Find the busy threads:
top -H -p <pid>shows CPU per thread. Convert the busiest thread ID to hex. - Take thread dumps:
jstack <pid>orjcmd <pid> Thread.print, three or four of them a few seconds apart. Search for the hex ID (nid) to see exactly what that thread is running. Threads stuck in the same frame across dumps are your suspects. - Check GC:
jstat -gcutil <pid> 1000or GC logs. High CPU with an old generation that is always full means the JVM is spending its time collecting garbage, which usually points to a leak or a heap that is too small. - Look for deadlocks and lock contention: many threads BLOCKED on the same lock, or a deadlock report at the end of the dump.
- Profile: Java Flight Recorder (
jcmd <pid> JFR.start) and JDK Mission Control, or async-profiler for flame graphs, with very low overhead in production.
Common culprits: an infinite loop, catastrophic regex backtracking, a HashMap corrupted by concurrent writes (in old Java versions this caused infinite loops), GC thrashing, or a thread pool exhausted by slow downstream calls.
99. What are some practical ways to improve Java performance?
- Measure first with a profiler or JMH. Guessing is usually wrong.
- Pick the right data structure and algorithm; an O(n²) loop over a list dwarfs every micro-optimisation. See our time complexity guide.
- Avoid unnecessary objects: StringBuilder in loops, primitives instead of wrappers in hot code, primitive streams (
IntStream). - Size collections up front when you know the size:
new ArrayList<>(n),new HashMap<>(capacity). - Cache expensive results, and use connection pools (HikariCP) and thread pools.
- Batch database writes and fetch only the columns you need; most “Java is slow” problems are really database or network problems.
- Tune the heap and GC from data, and use virtual threads for I/O-bound concurrency.
100. What changed from Java 8 to Java 21? Which features should every developer know?
| Version | Year | Key features |
|---|---|---|
| Java 8 (LTS) | 2014 | Lambdas, streams, Optional, java.time, default methods, CompletableFuture |
| Java 9 | 2017 | Module system (JPMS), JShell, List.of / Set.of / Map.of, private interface methods |
| Java 10 | 2018 | var for local variables |
| Java 11 (LTS) | 2018 | HttpClient, String methods (isBlank, strip, lines, repeat), run single-file programs with java File.java |
| Java 14 to 16 | 2020 to 2021 | Switch expressions, text blocks, records, pattern matching for instanceof, helpful NullPointerException messages |
| Java 17 (LTS) | 2021 | Sealed classes; Spring Boot 3 requires Java 17 or later |
| Java 21 (LTS) | 2023 | Virtual threads, pattern matching for switch, record patterns, sequenced collections (getFirst, getLast, reversed), generational ZGC |
LTS (long-term support) versions are what companies actually run. Java 25 (September 2025) is the newest LTS, with features such as scoped values and compact source files. In an interview, say which version your project used and one feature from it that you relied on.
Java quiz: test yourself
Ten multiple-choice questions from across this page. Eight or more right means you are in good shape for a Java interview.
10 Java MCQs
About three minutes.
Download all 100 Java interview questions as a PDF
The PDF has the same 100 Java interview questions and answers, with every code example and its output, in a clean 54-page printable format with a clickable table of contents. Use it to revise offline, on your phone, or on paper before the interview. It is free, with no sign-up.
100 Java Interview Questions and Answers
54 pages · Freshers, intermediate and experienced · 36 Java examples
Frequently asked questions
What Java questions are asked in interviews for freshers?
Freshers are most often asked about JDK, JRE and JVM, OOP concepts, == vs equals(), String immutability and the String pool, String vs StringBuilder, exception handling, ArrayList vs LinkedList, HashMap basics, static and final, and the main Java 8 features. Questions 1 to 40 on this page cover them.
Which Java topics are most important for interviews?
Collections (especially HashMap), OOP, String handling, exceptions, multithreading and Java 8 streams come up in almost every interview. For experienced roles, add JVM memory and garbage collection, concurrency utilities, ConcurrentHashMap internals and features from Java 17 and 21.
Which Java version should I prepare for?
Know Java 8 thoroughly, because most interview questions still use its features. Then learn what Java 11, 17 and 21 added, mainly records, sealed classes, switch expressions, pattern matching and virtual threads. Many companies now run Java 17 or 21, and Spring Boot 3 needs at least Java 17.
How should I prepare for a Java interview with 3 to 5 years of experience?
Expect deeper questions on HashMap and ConcurrentHashMap internals, thread safety, ExecutorService and CompletableFuture, JVM memory and GC tuning, design patterns and SOLID, plus questions about your own project. Practise explaining a production issue you debugged, and write stream code without an IDE.
Are Spring Boot questions asked in a core Java interview?
For back-end developer roles, usually yes, in a separate round. This page covers core Java and Java 8+; Spring Boot interview questions (dependency injection, beans, REST controllers, JPA, transactions) are a separate topic.
Can I download these Java interview questions as a PDF?
Yes. All 100 questions and answers, with every code example and its output, are in a free 54-page PDF. Use the Download PDF button at the top of this page; no sign-up is needed.
Next steps
Work through one level at a time and press “Mark as done” on each of the Java interview questions once you can answer it out loud without looking. Most Java interviews also include a coding round and questions on databases, so continue with our DSA interview cheat sheet, SQL interview questions, DBMS interview questions and OOPs interview questions. All the best for your interview!
