Java Progressive Master Question Bank
75 progressive Java interview questions complete with technical explanations, key takeaways, diagrams, code examples, and interactive knowledge check quizzes.
Q21: How is the Java Exception Class Hierarchy structured (Checked vs Unchecked)?
Throwable is the root class, branching into Error and Exception:
- Checked Exceptions: Subclasses of
Exception(excludingRuntimeException). The compiler forces developers to catch or declare them (IOException,SQLException). Represents recoverable conditions. - Unchecked Exceptions: Subclasses of
RuntimeException(NullPointerException,IllegalArgumentException). Represents programming bugs. Error: Serious system failures (OutOfMemoryError,StackOverflowError). Applications should not attempt recovery.
- Checked = Forced by compiler (
Exceptionsubclasses). Unchecked = Runtime errors (RuntimeExceptionsubclasses).
Which of the following exceptions is a CHECKED exception enforced by the Java compiler?
Q22: How does Try-With-Resources operate under the hood with AutoCloseable?
Introduced in Java 7, Try-With-Resources guarantees that open resources (files, database connections) are closed automatically upon block exit. Any resource declared inside try(Resource r = ...) must implement java.lang.AutoCloseable or java.io.Closeable.
The compiler generates hidden finally blocks calling .close(), suppressing secondary exceptions cleanly.
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(br.readLine());
} // br.close() is automatically invoked here, even if exceptions occur- Requires classes to implement
AutoCloseableorCloseableinterface. - Eliminates verbose boilerplate
finallyresource closing logic.
What interface must a custom class implement to be managed inside a try-with-resources statement?
Q23: What are Suppressed Exceptions in Java Try-With-Resources?
When an exception occurs inside a try block AND another exception occurs while automatically calling .close() during resource cleanup, the primary exception is thrown to the caller, while the cleanup exception is attached to it as a Suppressed Exception.
Retrieved using primaryException.getSuppressed(). Preventing cleanup failures from masking original root errors.
- Preserves root exceptions while capturing secondary resource closing errors.
- Accessed via
e.getSuppressed()array.
If both the try block and auto-close method throw an exception, which exception is thrown directly to the outer catch block?
Q24: What are the best practices for designing Custom Exceptions?
- Extend
RuntimeExceptionfor business rule violations (un-checked) unless caller recovery is mandatory. - Provide meaningful message strings and pass cause exceptions (
Throwable cause) to preserve stack traces. - Keep custom exception names suffixed with
Exception(e.g.,OrderNotFoundException). - Maintain standard constructor overloads (
(String),(String, Throwable)).
- Preserve original cause stack traces (
super(msg, cause)). - Prefer unchecked exceptions for application logic errors.
Why should custom exceptions accept a Throwable cause parameter in their constructors?
Q25: What is the high-level architecture of the Java Collections Framework?
Rooted at java.util.Collection (for single elements) and java.util.Map (for key-value pairs):
Collection:List: Ordered, allows duplicates (ArrayList,LinkedList,Vector).Set: Unordered, unique elements (HashSet,LinkedHashSet,TreeSet).Queue/Deque: Element processing order (PriorityQueue,ArrayDeque).
Map(Separate Hierarchy): Key-value mapping (HashMap,LinkedHashMap,TreeMap,ConcurrentHashMap).
Mapdoes NOT extendCollection.Listmaintains insertion order;Setenforces element uniqueness.
Which core collection interface does java.util.Map extend?
Q26: What are the operational differences between ArrayList and LinkedList?
ArrayList: Backed by a dynamically resizing array. Provides $O(1)$ fast random index access. Insertions/deletions in the middle require shifting elements ($O(n)$).LinkedList: Backed by a Doubly Linked List. Index access requires traversing nodes ($O(n)$). Inserting or deleting known node pointers is $O(1)$.
- Use
ArrayListfor frequent reads and index lookups. - Use
LinkedList(orArrayDeque) when frequent head/tail insertions occur.
What is the time complexity of retrieving an element by index (list.get(500)) in an ArrayList?
Q27: How does HashMap work under the hood (Buckets, Hash Collisions, Treeification)?
HashMap uses an array of Node<K,V> buckets. Index calculated as (n - 1) & hash(key).
- Collisions: Multiple keys mapped to the same bucket are chained as a Singly Linked List.
- Treeification (Java 8+): When bucket list length exceeds threshold 8 AND total capacity $ge 64$, the bucket converts from Linked List ($O(n)$) to a Red-Black Tree ($O(log n)$).
- Untreeification: Shrinks back to Linked List when node count drops to 6 during resizing.
- Collisions chain elements as Linked Lists initially.
- Converts to Red-Black Tree when bucket size $ge 8$ and capacity $ge 64$ ($O(log n)$ lookup).
What is the worst-case lookup time complexity in a Java 8 HashMap with high collisions?
Q28: What are HashMap Capacity, Initial Capacity, and Load Factor?
- Capacity: The number of buckets in the array (default 16).
- Load Factor: Measure of how full the map gets before resizing (default 0.75).
- Threshold: Calculated as $ ext{Capacity} imes ext{Load Factor}$ ($16 imes 0.75 = 12$). When total entries exceed threshold 12, capacity doubles to 32, and all entries are re-hashed (Rehash operation).
- Default capacity = 16; Default load factor = 0.75; Default threshold = 12.
- Resizing doubles capacity and re-hashes existing nodes.
When does a default HashMap (capacity 16, load factor 0.75) resize its bucket array?
Q29: How does ConcurrentHashMap achieve high concurrency without lock overhead?
- Java 7: Used Segmented Locks (Array of 16 ReentrantLocks guarding bucket segments).
- Java 8+: Replaced segments with CAS (Compare-And-Swap) for empty bucket insertions and
synchronizedlocks on individual bucket head nodes for updates. Allows concurrent thread reads without locking and parallel bucket writes.
- Uses CAS for lock-free insertions on empty buckets.
- Locks individual bucket head nodes instead of locking the entire table.
How does ConcurrentHashMap manage read (get) operations across buckets?
Q30: What is the difference between Fail-Fast and Fail-Safe Iterators?
- Fail-Fast (
ArrayList,HashMap): Operates directly on the underlying collection. ChecksmodCount. If structural modifications occur during iteration, it throwsConcurrentModificationExceptionimmediately. - Fail-Safe (
ConcurrentHashMap,CopyOnWriteArrayList): Operates on a clone copy or weakly-consistent iterator view. Does NOT throwConcurrentModificationExceptionwhen collection is modified concurrently.
- Fail-Fast throws
ConcurrentModificationExceptionon concurrent edits. - Fail-Safe iterates over copies or concurrent snapshots cleanly.
Which collection produces a Fail-Safe iterator during modification iterations?