Java Progressive Master Question Bank
75 progressive Java interview questions complete with technical explanations, key takeaways, diagrams, code examples, and interactive knowledge check quizzes.
Q31: How do TreeSet and TreeMap maintain sorted ordering?
TreeSet and TreeMap are backed by a Self-Balancing Red-Black Tree. They guarantee $O(log n)$ time complexity for add, remove, and contains operations. Elements are sorted either by natural ordering (Comparable) or an explicit Comparator passed at construction.
- Guarantees sorted element ordering using a Red-Black Tree.
- $O(log n)$ performance for insertion, lookup, and deletion.
What happens if you insert an object that does NOT implement Comparable into a default TreeSet?
Q32: Why is ArrayDeque preferred over java.util.Stack and LinkedList for stacks/queues?
java.util.Stack: Legacy class extendingVector. Synchronizes all individual operations, introducing unnecessary lock overhead. Obsolete.LinkedList: Allocates a wrapper node object for every element inserted, causing memory GC overhead.ArrayDeque: Resizable array-backed Queue/Deque. Superior CPU cache locality, no thread lock overhead, zero extra node allocation.
ArrayDequeis faster and memory-efficient compared toStackandLinkedList.
Why is legacy java.util.Stack considered bad practice in modern Java?
Q33: What is Type Erasure in Java Generics?
Java Generics were introduced in Java 5 with backward compatibility. Type Erasure means the Java compiler removes all generic type parameters during compilation, replacing bounded parameters with their bound (e.g., T -> Object or Comparable) and inserting explicit casts. At runtime, bytecode contains no generic type information.
// Written Code
List<String> list = new ArrayList<>();
list.add("Java");
String s = list.get(0);
// Compiled Bytecode Equivalent (Erased)
List list = new ArrayList();
list.add("Java");
String s = (String) list.get(0); // Cast inserted by compiler- Generic type information exists ONLY at compile time; erased in bytecode.
- Cannot instantiate generic arrays (
new T[]) or primitive generics (List<int>).
Can you check runtime types using instanceOf with explicit generics (e.g. obj instanceof List<String>)?
Q34: What are Upper/Lower Bounded Wildcards and the PECS Principle?
? extends T(Upper Bound): AcceptsTor any subclass ofT.? super T(Lower Bound): AcceptsTor any superclass ofT.- PECS Rule: Producer Extends, Consumer Super.
- Use
? extends Twhen reading data out of a collection (Collection is a Producer). - Use
? super Twhen writing data into a collection (Collection is a Consumer).
- Use
// Producer: Reading items out
public void processNumbers(List<? extends Number> list) {
for (Number n : list) { System.out.println(n); }
}
// Consumer: Writing items in
public void addIntegers(List<? super Integer> list) {
list.add(100); // Legal write
}- Producer Extends (
? extends T) = Read-only extraction. Consumer Super (? super T) = Write-only insertion.
According to PECS, which wildcard should be used on a method parameter list that you ONLY insert items INTO?
Q35: What is the Java Memory Model layout (Stack vs Heap Memory Regions)?
- JVM Stack: Each thread possesses an independent private execution stack. Stores local variables, primitive method parameters, and execution frame call stacks. Garbage Collector does NOT manage Stack.
- JVM Heap: Shared memory region housing all created Object instances, arrays, and instance fields. Managed by the Garbage Collector.
- Stack = Private per thread (primitive parameters, method frames). Heap = Shared across all threads (object allocations, instance fields).
Where is a local variable referencing an Object inside a method stored?
Q36: What is Metaspace and how does it differ from legacy PermGen Space?
Prior to Java 8, class metadata was stored in PermGen (Permanent Generation) inside Heap memory, bounded by fixed contiguous capacity (-XX:MaxPermSize), causing frequent OutOfMemoryError: PermGen space.
In Java 8, PermGen was replaced by Metaspace, located in Native OS Memory. Metaspace expands dynamically by default, limited only by available system RAM.
- Metaspace resides in Native Memory (not Heap).
- Prevents fixed-size class metadata
OutOfMemoryErrorbottlenecks.
Starting in Java 8, where is JVM class structure metadata stored?
Q37: How does Generational Garbage Collection work (Eden, Survivor, Tenured)?
Based on the Weak Generational Hypothesis (most objects die young):
- Young Generation:
- Eden Space: New objects allocated here.
- Survivor Spaces (S0 / S1): Survived objects from Minor GC passes copy back and forth between S0 and S1.
- Old Generation (Tenured): Objects surviving threshold age (e.g., 15 GC cycles) promote to Old Gen.
- Minor GC: Collects Young Gen.
- Major / Full GC: Collects Old Gen (and full heap). Causes longer Stop-The-World (STW) pauses.
- Eden -> Survivor (S0/S1) -> Old Generation promotion.
- Minor GC cleans Young Gen fast; Major GC cleans Old Gen with longer STW pauses.
Where are newly instantiated Java objects allocated first by default?
Q38: How do Garbage Collection algorithms compare (G1GC vs ZGC)?
- G1GC (Garbage-First): Default collector in Java 9+. Splits heap into region grids (~1-32MB). Targets configurable pause times (
-XX:MaxGCPauseMillis) by prioritizing regions with the most garbage. - ZGC (Z Garbage Collector): Low-latency collector (Java 15+). Scales to terabyte heaps with sub-millisecond pause times using colored pointers and load barriers during concurrent execution phases.
- G1GC = Region grid based, default enterprise collector.
- ZGC = Sub-millisecond pauses for massive multi-gigabyte/terabyte heaps.
Which Garbage Collector guarantees sub-millisecond maximum pause times even on multi-terabyte heaps?
Q39: What are Strong, Soft, Weak, and Phantom References in Java?
- Strong Reference: Standard reference (
Object obj = new Object()). Never garbage collected while reachable. - Soft Reference (
SoftReference): Collected ONLY when heap runs low on memory. Excellent for in-memory caches. - Weak Reference (
WeakReference): Collected immediately on the next GC pass if no strong references exist. Used inWeakHashMap. - Phantom Reference (
PhantomReference): Enqueued toReferenceQueueafter object is finalized. Used for resource cleanup.
- Soft = Reclaimed when memory runs out (Caching).
Weak = Reclaimed on next GC pass (
WeakHashMap). Phantom = Pre-mortem cleanup tracking.
Which reference type is ideal for building memory-sensitive caches that release items when JVM runs low on memory?
Q40: What causes Memory Leaks in Java and how do you diagnose them?
Memory leaks occur when unreferenced objects remain reachable through accidental reference paths, preventing GC reclamation.
- Causes: Un-removed static collection references, unclosed streams/connections, non-static inner class scope leaks, missing
equals()/hashCode()in keys. - Diagnosis: Analyze heap dumps (
.hprof) using Eclipse Memory Analyzer (MAT) or JProfiler, inspecting Dominator Trees and GCRoots paths.
- Unbounded static collections are a major cause of memory leaks.
- Diagnose using heap dumps (
jcmd,jmap) and MAT Dominator Trees.
Why do static collection instances frequently cause Java Memory Leaks if unmonitored?