Whether you are prepping for a technical screen or putting together a study guide, these 10 core Java questions come up regularly in interviews—covering language fundamentals, memory, collections, concurrency, and modern Java.
![]()
1. What is the difference between JDK, JRE, and JVM?
- JVM (Java Virtual Machine): An abstract machine that executes Java bytecode on a specific OS/hardware platform, handling memory management, garbage collection, and runtime execution.
- JRE (Java Runtime Environment): Includes the JVM plus the core class libraries and supporting files needed to run Java applications (does not include compilers or development tools).
- JDK (Java Development Kit): A superset of the JRE that adds development tools such as
javac(compiler), debuggers, and packaging utilities needed to build Java applications.
2. What is the difference between == and .equals() in Java?
==compares references (whether two reference variables point to the exact same object in memory) for reference types, or compares values directly for primitive types..equals()is a method onObjectintended to compare logical equality / content (for example,String.equals()compares character sequences).
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false (distinct heap objects)
System.out.println(a.equals(b)); // true (same character content)
3. Why are String objects immutable in Java?
Strings in Java cannot be changed after creation (String is final and backs its characters in a final array). Immutability provides several key benefits:
- String Pool efficiency: Multiple references can safely share the same literal in the String Pool without risking accidental mutation by one caller.
- Thread safety: Immutable objects are inherently thread-safe and can be shared across threads without synchronization.
- Security: Strings are widely used for class names, file paths, network hosts, and database connection details—immutability prevents tampering after validation.
- Cached
hashCode(): Because the contents never change,hashCode()can be computed once and cached, makingStringreliable and fast as aHashMapkey.
4. What happens if you override equals() without overriding hashCode()?
You violate the general contract between equals() and hashCode(): if two objects are equal according to equals(Object), they must produce the same `hashCode()`.
In hash-based collections like HashMap or HashSet, lookup first locates a bucket using hashCode() and then checks equality with equals(). If equals() is overridden without hashCode(), two equal objects may hash to different buckets, causing map.get(key) or set.contains(item) to fail to find them even when present.
5. How does HashMap work internally?
A HashMap stores entries as key-value pairs in an array of buckets (nodes):
- It computes
hash(key)using the key'shashCode()(mixed with higher bits to reduce collisions) and maps it to a bucket index ((n - 1) & hash). - If the target bucket is empty, the entry is stored directly; if a collision occurs (different keys landing in the same bucket), entries are chained in a linked list.
- When a single bucket exceeds a treeify threshold (default
8nodes, provided table capacity is at least64), Java converts that bucket from a linked list into a balanced red-black tree, improving worst-case lookup from $O(n)$ to $O(\log n)$. - When the number of entries exceeds
capacity * loadFactor(default load factor is0.75), the map resizes (typically doubling capacity) and rehashes entries.
6. What is the difference between ArrayList and LinkedList?
| Feature | ArrayList |
LinkedList |
|---|---|---|
| Underlying structure | Resizable array | Doubly linked list |
Random access (get(i)) |
$O(1)$ | $O(n)$ |
| Insert/remove at ends | Amortized $O(1)$ at end; $O(n)$ at front | $O(1)$ at head or tail |
| Insert/remove in middle | $O(n)$ (shifting elements) | $O(n)$ to traverse to node; $O(1)$ once at node |
| Memory overhead | Lower (contiguous array) | Higher (node pointers + object wrappers) |
In practice, ArrayList is the default choice for most workloads due to $O(1)$ indexing and CPU cache locality.
7. What is the difference between checked and unchecked exceptions?
- Checked exceptions extend
Exception(excludingRuntimeException) and must be either caught in atry-catchblock or declared withthrowsin the method signature (e.g.,IOException,SQLException). They represent recoverable external conditions the caller should anticipate. - Unchecked exceptions extend
RuntimeExceptionand do not require explicittry-catchorthrowsdeclarations (e.g.,NullPointerException,IllegalArgumentException,IndexOutOfBoundsException). They commonly stem from programming errors or invalid arguments.
8. What does try-with-resources do, and why use it?
Introduced in Java 7, try-with-resources automatically closes one or more resources that implement AutoCloseable (including Closeable) when execution exits the try block—whether normally or via an exception.
It eliminates boilerplate finally cleanup code and properly handles suppressed exceptions (if both the try block and close() throw exceptions, the try exception is thrown and the close() exception is attached as a suppressed exception rather than silently overwriting it).
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line = reader.readLine();
System.out.println(line);
} // reader.close() is called automatically
9. What is the difference between synchronized and volatile?
volatileguarantees visibility (writes to avolatilevariable are flushed to main memory and reads see the latest write) and prevents certain instruction reorderings across threads. It does not provide mutual exclusion or make compound actions (likecount++) atomic.synchronizedprovides mutual exclusion (only one thread can hold the monitor lock on that object/class at a time) plus memory visibility when acquiring and releasing the lock.
10. What are Java record classes, and when should you use them?
Introduced as a standard feature in Java 16, a record is a compact class designed to model immutable data carriers with minimal boilerplate. Declaring a record automatically generates:
private finalfields for each component in the state description- A canonical constructor
- Public accessor methods named after each component (e.g.,
point.x(), notgetX()) equals(),hashCode(), andtoString()implementations based on all components
public record Point(int x, int y) {}
Use records for value objects, DTOs, configuration payloads, or return tuples where state is transparent and immutable. Avoid using records when instances need mutable state or when behavior/encapsulation invariants require full class design.