HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
75 Topics
Chapter•390 Minutes

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 (excluding RuntimeException). 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.
Throwable Class Hierarchy Structure
Key Takeaways
  • Checked = Forced by compiler (Exception subclasses). Unchecked = Runtime errors (RuntimeException subclasses).
Knowledge Check

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-With-Resources Syntax
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    System.out.println(br.readLine());
} // br.close() is automatically invoked here, even if exceptions occur
💡 BufferedReader is closed automatically upon exiting the try block.
Key Takeaways
  • Requires classes to implement AutoCloseable or Closeable interface.
  • Eliminates verbose boilerplate finally resource closing logic.
Knowledge Check

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.

Key Takeaways
  • Preserves root exceptions while capturing secondary resource closing errors.
  • Accessed via e.getSuppressed() array.
Knowledge Check

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?

  1. Extend RuntimeException for business rule violations (un-checked) unless caller recovery is mandatory.
  2. Provide meaningful message strings and pass cause exceptions (Throwable cause) to preserve stack traces.
  3. Keep custom exception names suffixed with Exception (e.g., OrderNotFoundException).
  4. Maintain standard constructor overloads ((String), (String, Throwable)).
Key Takeaways
  • Preserve original cause stack traces (super(msg, cause)).
  • Prefer unchecked exceptions for application logic errors.
Knowledge Check

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).
Key Takeaways
  • Map does NOT extend Collection.
  • List maintains insertion order; Set enforces element uniqueness.
Knowledge Check

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)$.
Key Takeaways
  • Use ArrayList for frequent reads and index lookups.
  • Use LinkedList (or ArrayDeque) when frequent head/tail insertions occur.
Knowledge Check

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.
HashMap Bucket Chain Treeification Architecture
Key Takeaways
  • 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).
Knowledge Check

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).
Key Takeaways
  • Default capacity = 16; Default load factor = 0.75; Default threshold = 12.
  • Resizing doubles capacity and re-hashes existing nodes.
Knowledge Check

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 synchronized locks on individual bucket head nodes for updates. Allows concurrent thread reads without locking and parallel bucket writes.
Key Takeaways
  • Uses CAS for lock-free insertions on empty buckets.
  • Locks individual bucket head nodes instead of locking the entire table.
Knowledge Check

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. Checks modCount. If structural modifications occur during iteration, it throws ConcurrentModificationException immediately.
  • Fail-Safe (ConcurrentHashMap, CopyOnWriteArrayList): Operates on a clone copy or weakly-consistent iterator view. Does NOT throw ConcurrentModificationException when collection is modified concurrently.
Key Takeaways
  • Fail-Fast throws ConcurrentModificationException on concurrent edits.
  • Fail-Safe iterates over copies or concurrent snapshots cleanly.
Knowledge Check

Which collection produces a Fail-Safe iterator during modification iterations?