Java continues to be one of the most powerful programming languages in enterprise application development. For experienced developers, interviews often go beyond the basics, focusing on multithreading, JVM internals, functional programming, and modern Java features.
Here are the top 20 advanced Java interview questions explained in detail, with examples that help you understand the concept practically.
1. What is the difference between HashMap and ConcurrentHashMap?
Answer:HashMap is not thread-safe and can lead to data inconsistency when multiple threads access or modify it concurrently. It allows only one thread at a time to modify the map, but synchronization must be handled manually.ConcurrentHashMap, introduced in Java 5, is thread-safe and allows concurrent reads and segmented writes. It internally divides the map into segments, which enables multiple threads to operate simultaneously on different parts of the map.
Example:
Map<Integer, String> map = new ConcurrentHashMap<>();
map.put(1, "Java");
map.put(2, "Spring");
System.out.println(map.get(1));
Key Point:
Use ConcurrentHashMap when working in multithreaded environments to avoid ConcurrentModificationException.
2. What is the role of the volatile keyword in Java?
Answer:volatile ensures that a variable’s value is always read from and written to the main memory, not from a thread’s local cache. This guarantees visibility of updates to variables across threads.
Without volatile, one thread might not see the updated value made by another thread.
Example:
volatile boolean running = true;
public void runTask() {
while (running) {
// Task execution
}
}
Key Point:volatile ensures visibility but not atomicity. For compound operations (like increment), use synchronization or Atomic classes.
3. What’s the difference between wait() and sleep() methods?
Answer:
wait()releases the lock on the object and pauses the thread until another thread callsnotify()ornotifyAll().sleep()just pauses the thread for a specified time but does not release the lock.
Example:
synchronized(obj) {
obj.wait(); // releases lock
}
Thread.sleep(1000); // does not release lock
Key Point:
Use wait() for inter-thread communication and sleep() for time delays.
4. What are Streams in Java 8?
Answer:
Streams introduced in Java 8 allow functional-style operations on collections. Instead of using loops, you can use declarative methods like map(), filter(), and reduce() to process data efficiently.
Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.forEach(System.out::println);
Key Point:
Streams don’t store data; they operate on existing data sources like lists or arrays.
5. Explain Lambda Expressions in Java.
Answer:
Lambda expressions provide a concise way to represent anonymous functions (functional interfaces). They simplify code, especially when using APIs like Streams or Runnable.
Example:
Runnable r = () -> System.out.println("Running in a thread");
new Thread(r).start();
Key Point:
Lambdas can only be used with functional interfaces (interfaces having exactly one abstract method).
6. What is the purpose of the Optional class in Java 8?
Answer:Optional helps avoid NullPointerException by providing a container that may or may not hold a non-null value. It encourages better handling of null references.
Example:
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Default Name"));
Key Point:Optional is best used for return types, not for class fields or parameters.
7. What’s the difference between StringBuilder and StringBuffer?
Answer:
StringBuilderis non-synchronized and faster.StringBufferis synchronized and thread-safe.
Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java");
System.out.println(sb);
Key Point:
Use StringBuilder for single-threaded environments and StringBuffer for multithreaded ones.
8. Explain Future and CompletableFuture.
Answer:Future represents the result of an asynchronous computation. You can check if it’s done or cancel it.CompletableFuture, introduced in Java 8, extends Future by allowing callback chaining and combining multiple async tasks.
Example:
CompletableFuture.supplyAsync(() -> "Data loaded")
.thenApply(data -> data.toUpperCase())
.thenAccept(System.out::println);
Key Point:CompletableFuture provides non-blocking programming capabilities, making asynchronous code cleaner.
9. What is ForkJoinPool?
Answer:ForkJoinPool is a special thread pool optimized for tasks that can be divided into smaller subtasks (divide and conquer). It uses the work-stealing algorithm where idle threads “steal” tasks from busy threads.
Example:
ForkJoinPool pool = new ForkJoinPool();
pool.submit(() -> System.out.println("Parallel Task"));
pool.shutdown();
Key Point:
It’s often used with the ForkJoinTask and RecursiveTask classes for parallelism.
10. What are Functional Interfaces?
Answer:
A functional interface contains exactly one abstract method. Java 8 introduced annotations like @FunctionalInterface to enforce this rule.
Example:
@FunctionalInterface
interface Calculator {
int add(int a, int b);
}
Key Point:
Functional interfaces can be implemented using Lambda expressions.
11. Explain the difference between Comparable and Comparator.
Answer:
Comparabledefines a natural ordering usingcompareTo().Comparatordefines custom ordering usingcompare().
Example:
list.sort(Comparator.comparing(Employee::getSalary));
Key Point:
Use Comparable when default sorting is needed; Comparator when sorting logic varies.
12. What is Reflection API in Java?
Answer:
Reflection allows inspecting or modifying classes, methods, and fields at runtime, even if they are private. It’s widely used in frameworks like Spring and Hibernate.
Example:
Method m = MyClass.class.getMethod("display");
m.invoke(myObject);
Key Point:
Use reflection carefully; it breaks encapsulation and impacts performance.
13. What is Serialization in Java?
Answer:
Serialization converts an object into a byte stream to store or transfer it. Deserialization reconstructs the object from that stream.
Example:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(obj);
Key Point:
Mark fields as transient to skip them during serialization.
14. What are Annotations in Java?
Answer:
Annotations provide metadata that can be used by compilers and frameworks for processing code. Examples include @Override, @Deprecated, and custom annotations.
Example:
@Override
public void run() { }
Key Point:
Annotations are heavily used in frameworks like Spring for dependency injection.
15. What is ExecutorService?
Answer:ExecutorService simplifies thread management by providing a pool of threads that can execute tasks concurrently. It removes the need to manually create and manage threads.
Example:
ExecutorService service = Executors.newFixedThreadPool(3);
service.submit(() -> System.out.println("Task running"));
service.shutdown();
Key Point:
Always call shutdown() or shutdownNow() to stop the service gracefully.
16. What are Generics in Java?
Answer:
Generics allow defining classes, interfaces, and methods with type parameters, improving type safety and reusability.
Example:
List<String> names = new ArrayList<>();
names.add("John"); // Only Strings allowed
Key Point:
Generics eliminate the need for casting and prevent ClassCastException.
17. Explain Java Memory Model (Heap vs Stack).
Answer:
- Stack Memory: Stores primitive values and references to objects. Each thread has its own stack.
- Heap Memory: Stores all Java objects and shared among threads.
Example:
int a = 10; // stored in Stack
Person p = new Person(); // stored in Heap
Key Point:
Understanding memory helps optimize performance and fix memory leaks.
18. What is a ClassLoader?
Answer:
A ClassLoader loads classes dynamically into the JVM at runtime. Types include Bootstrap, Extension, and Application ClassLoader.
Example:
Class<?> cls = Class.forName("com.example.MyClass");
Object obj = cls.newInstance();
Key Point:
Custom class loaders can be created to load classes from non-standard sources.
19. Explain try-with-resources in Java.
Answer:
Introduced in Java 7, it automatically closes resources like files or sockets after use, even if an exception occurs.
Example:
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(br.readLine());
}
Key Point:
The resource must implement AutoCloseable.
20. What is Garbage Collection in Java?
Answer:
Garbage Collection (GC) automatically frees memory by removing objects that are no longer reachable. Developers can suggest GC using System.gc(), but it’s not guaranteed to run immediately.
Example:
MyClass obj = new MyClass();
obj = null; // Eligible for GC
System.gc(); // Suggests GC
Key Point:
Efficient GC tuning is crucial for performance in large applications.
Conclusion
These 20 advanced Java questions cover the most important concepts for experienced developers — from concurrency and JVM internals to functional programming and modern APIs. Understanding these thoroughly not only helps you crack interviews but also makes you a stronger Java professional capable of writing efficient, scalable applications.