Java Fundamentals
1. JDK vs JRE vs JVM?
- JVM — Java Virtual Machine; runs bytecode.
- JRE — JVM + runtime libraries (enough to RUN Java).
- JDK — JRE + compiler (
javac), tools (jshell,jlink,jpackage) — needed to BUILD Java.
2. == vs .equals() ?
== compares references (same object in memory). .equals() compares values (when properly overridden). For strings:
"hi" == "hi" // true — interned literals
new String("hi") == new String("hi") // false
new String("hi").equals(new String("hi")) // true
3. What's new in Java 21 (LTS) vs Java 8?
- Records —
record Point(int x, int y) {}— immutable value classes for free. - Pattern matching in
switchandinstanceof. - Sealed classes — restrict who can extend.
- Virtual threads (Project Loom) — millions of lightweight threads.
- Text blocks —
"""multi-line strings""". - Switch expressions — return a value, no fall-through bugs.
4. Checked vs unchecked exceptions?
- Checked (
extends Exception) — compiler forcesthrowsortry/catch. Used for recoverable conditions (IOException). - Unchecked (
extends RuntimeException) — programmer errors (NullPointerException,IllegalArgumentException). Caller chooses to handle.
OOP
5. Abstract class vs Interface?
| Abstract class | Interface | |
|---|---|---|
| Multiple inheritance | ❌ | ✅ |
| Default methods | ✅ | ✅ (since Java 8) |
| State / fields | ✅ | only public static final |
| Constructor | ✅ | ❌ |
6. final, finally, finalize?
final— modifier (final class, final method, final var).finally— block that always runs after try/catch.finalize()— deprecated GC hook. Don't use; prefertry-with-resourcesor Cleaner API.
7. What is method overloading vs overriding?
- Overloading — same name, different parameter list (compile-time).
- Overriding — subclass redefines a parent method (runtime polymorphism). Use
@Overrideannotation to catch typos.
Collections
8. ArrayList vs LinkedList?
ArrayList | LinkedList | |
|---|---|---|
get(i) | O(1) | O(n) |
add(end) | O(1) amortised | O(1) |
add(middle) | O(n) (shift) | O(n) (traverse) |
| Memory | contiguous array | per-node overhead |
In practice, ArrayList wins almost always. LinkedList is rarely the right choice.
9. HashMap vs ConcurrentHashMap vs Hashtable?
HashMap— not thread-safe; fastest single-thread.ConcurrentHashMap— thread-safe with fine-grained locking; modern default for concurrent use.Hashtable— legacy; coarse-grained synchronisation; avoid.
10. How does HashMap work internally?
Array of buckets indexed by hash(key) & (n-1). Collisions form a linked list; if a bucket grows beyond 8 entries (Java 8+), it becomes a balanced tree — O(log n) instead of O(n) for pathological inputs.
Concurrency
11. synchronized vs ReentrantLock?
synchronized— simpler, intrinsic, JVM-monitored.ReentrantLock— more features: fairness, tryLock, interruptibility, condition variables.
12. Volatile vs Atomic?
volatile— guarantees visibility (writes seen by other threads) but NOT atomicity (x++still broken).AtomicInteger.incrementAndGet()— atomic + visible.
13. Virtual threads (Java 21)?
Lightweight threads scheduled by the JVM, not the OS. Millions can exist. Blocking I/O no longer wastes a real thread — perfect for high-concurrency web servers.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i ->
executor.submit(() -> { Thread.sleep(1000); return i; }));
}
JVM & Performance
14. Garbage collectors — name three.
- G1 GC — default in modern JVMs, low-pause.
- ZGC — ultra-low pause (sub-millisecond), handles TBs of heap.
- Shenandoah — concurrent compaction, also low-pause.
- Parallel GC — throughput-optimised; older default.
15. How do you profile a Java app?
- JFR (Java Flight Recorder) — built-in, near-zero overhead.
- VisualVM — free GUI for live profiling.
- async-profiler — sampling flame-graph profiler.
- JMH — micro-benchmarks done right.
Spring & Frameworks
16. What is Dependency Injection in Spring?
Instead of new inside a class, Spring injects dependencies through constructors / setters. Allows easy mocking in tests, runtime swapping (production vs test config), and clean separation of concerns.
17. @Component vs @Service vs @Repository?
All are stereotypes that register the class as a Spring bean. @Service and @Repository add semantic meaning (and @Repository enables exception translation). Functionally similar.
18. Spring Boot — what does it give you?
- Auto-configuration based on classpath.
- Embedded Tomcat/Jetty —
java -jar app.jarand you're serving HTTP. - Production-ready endpoints (
/actuator). - Opinionated starter dependencies.
Real-World
19. Walk me through a Spring MVC request lifecycle.
DispatcherServlet → HandlerMapping (matches URL to controller) → HandlerAdapter (invokes the controller method) → controller returns ModelAndView → ViewResolver → View renders the response.
20. How do you write thread-safe singleton in Java?
public final class Config {
private static volatile Config instance;
private Config() {}
public static Config get() {
Config c = instance;
if (c == null) {
synchronized (Config.class) {
c = instance;
if (c == null) instance = c = new Config();
}
}
return c;
}
}
Or simpler — enum:
public enum Config { INSTANCE; }
