Java Progressive Master Question Bank
75 progressive Java interview questions complete with technical explanations, key takeaways, diagrams, code examples, and interactive knowledge check quizzes.
Q1: What are JDK, JRE, and JVM, and how do they differ?
- JVM (Java Virtual Machine): The abstract runtime engine that executes compiled Java bytecode (
.classfiles). - JRE (Java Runtime Environment): Includes the JVM plus standard runtime libraries and class loaders required to execute Java programs.
- JDK (Java Development Kit): The complete software development kit containing the JRE, compiler (
javac), debugger (jdb), and development tools.
# 1. Compiler (JDK component) produces bytecode
javac Main.java -> Main.class
# 2. Virtual Machine (JRE/JVM component) executes bytecode
java Mainjavac converts human-readable source code into platform-independent JVM bytecode.
JVM executes bytecode; JRE = JVM + Standard Libraries; JDK = JRE + Developer Tools (
javac).JDK is needed for writing and compiling code; JRE is sufficient for execution.
Which software distribution is strictly required on a developer machine to compile .java source files?
Q2: How does Java achieve platform independence?
Java achieves platform independence through the concept of 'Write Once, Run Anywhere' (WORA). The Java compiler (javac) translates source code into an intermediate format called Bytecode (.class). Bytecode is platform-neutral; platform-specific JVM implementations interpret or JIT-compile this bytecode into native machine code.
Source code compiles to platform-neutral Bytecode (
.class).JVM implementations are platform-specific, making Java bytecode platform-independent.
Is the JVM itself platform-independent?
Q3: What is the JIT Compiler and how does Tiered Compilation work in HotSpot JVM?
The Just-In-Time (JIT) Compiler is a JVM subsystem that improves runtime performance by compiling frequently executed bytecode sequences ('hot spots') directly into native machine code at runtime. HotSpot uses Tiered Compilation:
- Tier 0: Interpreted bytecode execution.
- Tiers 1-3 (C1 Compiler / Client Compiler): Fast compilation with basic optimizations.
- Tier 4 (C2 Compiler / Server Compiler): Heavy profile-guided optimizations (inlining, escape analysis, loop unrolling).
JIT translates hot bytecode paths into native machine code at runtime.
Tiered compilation balances rapid startup time (C1) with high peak performance (C2).
What is the primary role of the C2 compiler in HotSpot Tiered Compilation?
Q4: Why is the main method declared as public static void main(String[] args)?
public: Allows the JVM execution engine (outside the package) to call the method.static: Enables the JVM to invoke the method without instantiating an instance of the outer class.void: Signals that the entry point returns no exit code value (JVM usesSystem.exit()for exit codes).main: The standard identifier searched for by the launcher.String[] args: Receives command-line arguments passed at application invocation.
public class Application {
public static void main(String[] args) {
System.out.println("Application Entry Point");
}
}The public static signature allows JVM launchers to call the entry point directly.
staticavoids requiring object allocation prior to execution initialization.String[] argscaptures command-line parameters.
What occurs if you omit the static keyword from the main method in Java 8?
Q5: What are Primitive Data Types versus Reference Types in Java?
- Primitive Types (8 total):
byte,short,int,long,float,double,char,boolean. They store raw binary values directly on the stack or inline inside heap objects. - Reference Types: Objects, Arrays, Interfaces, and Enums. They store memory addresses (references) pointing to heap-allocated object instances.
Primitives hold raw values directly; Reference types hold memory address references to heap objects.
Primitives cannot be
null; Reference variables default tonull.
Which of the following is NOT a Java primitive data type?
Q6: What are Autoboxing and Unboxing, and what performance pitfalls do they present?
- Autoboxing: Automatic conversion of primitives to wrapper objects (
int->Integer). - Unboxing: Automatic conversion of wrapper objects to primitives (
Integer->int). - Pitfalls: Unboxing a
nullwrapper throwsNullPointerException. Excessive autoboxing inside loops creates huge GC object pressure.
// Bad: Autoboxes 1,000,000 Integer objects
Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) {
sum += i; // Unboxes sum, adds i, autoboxes result to new Long object
}
// Good: Uses primitive long
long fastSum = 0L;
for (long i = 0; i < 1_000_000; i++) {
fastSum += i;
}Using wrapper objects in accumulation loops allocates millions of redundant heap wrapper instances.
Autoboxing creates new object wrapper allocations implicitly.
Unboxing
nullwrapper references throwsNullPointerException.
What error occurs when executing: Integer val = null; int num = val;
Q7: Why are Java Strings immutable and how does the String Constant Pool work?
Strings in Java are final and immutable for Security (db connections, network parameters), Thread-Safety (shared without synchronization), and Caching.
The String Constant Pool (SCP) is a special heap area. String literals are stored here and shared across the JVM to reduce duplicate memory footprint.
String s1 = "Java"; // Stored in String Pool
String s2 = "Java"; // Reuses pooled instance
String s3 = new String("Java"); // Explicitly creates new Heap object
System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false (different heap memory addresses)Literals reuse SCP instances; string construction via new allocates distinct heap instances.
Immutability enables safe sharing, hash code caching, and thread safety.
String literals are stored in the String Constant Pool inside heap memory.
Where is the String Constant Pool located in modern Java architectures (Java 7+)?
Q8: What are the differences between String, StringBuilder, and StringBuffer?
String: Immutable character sequence. Modifications create new object instances.StringBuilder: Mutable character sequence. Non-thread-safe, high performance.StringBuffer: Mutable character sequence. Thread-safe usingsynchronizedmethods (slower overhead).
Use
Stringfor immutable constants.Use
StringBuilderfor single-threaded dynamic string concatenation.Use
StringBufferfor multi-threaded thread-safe string concatenation.
Which class should be preferred for high-speed string concatenation in single-threaded methods?
Q9: What is the difference between == and the .equals() method?
==Operator: Compares primitive values directly, or checks reference identity (whether two reference variables point to the exact same memory address on the heap)..equals()Method: Compares logical content equality when overridden by a class (e.g.,String,Integer). The default implementation inObjectuses==reference identity.
==compares memory references;.equals()compares logical values (if overridden).Always override
.hashCode()whenever overriding.equals().
What is the output of: new String("A").equals(new String("A"))?
Q10: What is the equals() and hashCode() contract, and why must both be overridden together?
The contract dictates:
- If
a.equals(b)istrue, thena.hashCode() == b.hashCode()MUST betrue. - If
a.hashCode() == b.hashCode(),a.equals(b)may or may not betrue(hash collision). If you override.equals()without.hashCode(), key lookups in hash-based collections (HashMap,HashSet) will fail because duplicate objects resolve to different bucket indices.
public class Person {
private final int id;
private final String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person person)) return false;
return id == person.id && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}Both methods evaluate the exact same identity fields to satisfy the Java collection contract.
Equal objects MUST have equal hash codes.
Failing to override
hashCode()breaksHashMapandHashSetlookups.
What happens if two distinct instances return the exact same hashCode() value?
Q11: What are the Four Pillars of Object-Oriented Programming (OOP)?
- Encapsulation: Hiding state behind
privatefields, exposing access via controlledpublicmethods. - Abstraction: Hiding internal implementation complexity behind simple abstract interfaces or classes.
- Inheritance: Deriving new classes from parent classes to promote code reuse (
extends). - Polymorphism: Allowing objects to take multiple forms (Method Overloading and Method Overriding).
Encapsulation protects data integrity.
Abstraction simplifies user interaction contracts.
Inheritance models 'IS-A' hierarchies.
Polymorphism provides dynamic runtime dispatch.
Hiding implementation complexity and exposing only essential functional contracts is known as what?
Q12: How do Method Overloading and Method Overriding differ?
- Overloading (Compile-Time / Static Polymorphism): Multiple methods in the same class share the same name but differ in parameter count or parameter types. Return type alone is insufficient.
- Overriding (Runtime / Dynamic Polymorphism): Subclass provides a specific implementation of a method already declared in its superclass using the
@Overrideannotation. Method signature and return type must match (or be covariant).
Overloading = Same method name, different parameter signature (Compile-Time).
Overriding = Same method signature in child class (Runtime Dispatch).
Can you overload a method by changing ONLY its return type in Java?
Q13: What are the differences between an Abstract Class and an Interface?
| Feature | Abstract Class | Interface (Java 8+) |
|---|---|---|
| Inheritance | Single class inheritance (extends) | Multiple interface implementation (implements) |
| State | Can hold state (private instance fields) | Stateless (only public static final constants) |
| Constructors | Supported | Not supported |
| Methods | Abstract, concrete, protected, private methods | abstract, default, static, and private (Java 9+) methods |
Use Abstract Classes for sharing state and identity in class hierarchies.
Use Interfaces for defining peripheral behavioral capability contracts across unrelated hierarchies.
Can a class extend multiple abstract classes in Java?
Q14: What are Default, Static, and Private methods in Java Interfaces?
- Default Methods (Java 8+): Methods declared with
defaultkeyword providing concrete method bodies. Enables API evolution without breaking existing interface implementations. - Static Methods (Java 8+): Utility methods attached directly to the interface scope.
- Private Methods (Java 9+): Encapsulated helper methods used internally inside default or static interface methods.
public interface Logger {
void log(String message); // Abstract
default void logWarning(String msg) { // Default
formatAndPrint("WARN", msg);
}
private void formatAndPrint(String level, String msg) { // Private (Java 9+)
System.out.println("[" + level + "]: " + msg);
}
}Default methods provide implementation logic while private methods cleanly isolate helper logic.
defaultmethods allow adding new interface methods safely.privatemethods encapsulate shared internal logic inside interfaces.
Why were default methods introduced in Java 8?
Q15: How does Java resolve the Diamond Problem with Interface default methods?
If a class implements two interfaces that declare the exact same default method signature, the Java compiler raises a compile-time error due to ambiguity.
The implementing class MUST resolve the conflict explicitly by overriding the method and selecting a specific interface using InterfaceName.super.methodName() or providing custom logic.
interface A { default void show() { System.out.println("A"); } }
interface B { default void show() { System.out.println("B"); } }
class C implements A, B {
@Override
public void show() {
A.super.show(); // Explicitly resolves ambiguity
}
}C resolves the collision by explicitly invoking A's default implementation.
Ambiguous default methods force compile-time resolution.
Resolve using
InterfaceName.super.methodName()inside the override.
What happens if class C implements Interface A and Interface B, which both contain an identical default method signature, without overriding it?
Q16: How does the static keyword operate on variables, methods, blocks, and nested classes?
- Static Variables: Shared across all instances of a class; stored in heap class metadata area.
- Static Methods: Bound to the class context. Cannot access instance fields (
this/super). - Static Blocks: Execute once when the class is loaded into the JVM by the ClassLoader.
- Static Nested Classes: Nested classes that do not hold an implicit reference to an outer class instance.
Static members belong to the class, not individual instance allocations.
Static blocks run during class loading before constructor invocations.
Can a static method access a non-static instance variable directly without instantiating an object?
Q17: What are the differences between final, finally, and finalize?
final: Keyword modifier.final variable: Constant (value cannot be reassigned).final method: Prevents method overriding.final class: Prevents inheritance.
finally: Block paired withtry-catchto execute cleanup code unconditionally.finalize: DeprecatedObjectmethod invoked by Garbage Collector prior to object reclamation.
finalrestricts mutability/inheritance.finallyguarantees cleanup execution.finalize()is deprecated—useCleanerorAutoCloseableinstead.
Will a finally block execute if a try block contains a return statement?
Q18: What is the visibility matrix for Java Access Modifiers?
| Modifier | Same Class | Same Package | Subclass (Diff Pkg) | World (Diff Pkg) |
|---|---|---|---|---|
private | Yes | No | No | No |
default (package-private) | Yes | Yes | No | No |
protected | Yes | Yes | Yes | No |
public | Yes | Yes | Yes | Yes |
private: Lowest visibility (class scope).protected: Package scope + Subclasses across packages.default: Strictly package-wide scope.
Which access level allows access from a subclass located in a DIFFERENT package?
Q19: What is Composition versus Inheritance, and why favor Composition?
- Inheritance (
IS-A): Tightly couples subclass to superclass implementation details (class Dog extends Animal). Modifying parent behavior risks breaking derived subclasses. - Composition (
HAS-A): Assembles complex objects by embedding component objects as private fields (class Car { private Engine engine; }). - Principle: Favor Composition over Inheritance to achieve loose coupling, runtime behavior swapping, and robust encapsulation.
Inheritance =
IS-Arelationship (tight coupling). Composition =HAS-Arelationship (loose coupling, runtime flexibility).
Which design principle helps avoid brittle class hierarchies when extending framework features?
Q20: What are Covariant Return Types in method overriding?
Covariant Return Types allow an overriding method in a subclass to return a subtype of the return type declared in the superclass method. This removes the need for explicit client casting when calling derived methods.
class SuperFactory {
public Number produce() { return 100; }
}
class SubFactory extends SuperFactory {
@Override
public Integer produce() { // Covariant: Integer is a subtype of Number
return 200;
}
}SubFactory narrows the return type from Number to Integer legally.
Subclass overrides can narrow return types to more specific derived classes.
Can an overriding method return a supertype of the parent method's return type?
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 occurBufferedReader is closed automatically upon exiting the try block.
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?