Skip to content
Java Interview Mastery: Core Concepts, JDK 8-21 Evolution & Modern Features
Fundamentals 58 min read

Java Interview Mastery: Core Concepts, JDK 8-21 Evolution & Modern Features

This comprehensive guide covers Java interview essentials including JDK/JRE/JVM differences, JDK 8-21 version evolution with key features like Records, Sealed Classes, Pattern Matching, Virtual Threads, and core topics such as String immutability, equals/hashCode contract, OOP principles, exception handling, reflection, serialization, and IO models.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

JDK, JRE, and JVM: Core Differences

The article opens with a cooking analogy to explain the relationship: JVM (Java Virtual Machine) is the "pot" that runs bytecode on any OS, enabling "write once, run anywhere." JRE (Java Runtime Environment) adds core libraries (String, ArrayList) — the "pot + water and seasoning" — allowing compiled programs to run but not develop. JDK (Java Development Kit) includes JRE plus development tools (javac, javadoc, jdb) — the "pot + seasoning + knives and spatulas" — for writing, compiling, and debugging code. The containment hierarchy is JDK ⊃ JRE ⊃ JVM.

JDK 17 Directory Structure Changes

JDK 17 (LTS) simplifies and modularizes the directory structure compared to JDK 8:

Removed jre directory — modules integrate JRE functionality into lib and bin.

Core libraries become lib/modules — a single module image file replacing scattered JARs like rt.jar and charsets.jar, enabling faster startup and custom runtime images via jlink.

Tool directory simplified — outdated tools (e.g., javah) removed; lib/jrt-fs.jar added for module-path filesystem access.

Configuration files moved to conf/ — net.properties, security policies centralized.

New jmods/ directory — holds JMOD files for compile-time linking, used by jlink to create minimal Docker images.

JDK8/
├── bin/          # javac, java, jar ...
├── jre/          # complete JRE copy
│   ├── bin/
│   └── lib/
├── lib/          # JDK tool libraries
└── include/      # JNI headers

JDK17/
├── bin/          # java, javac, jlink, jshell ... (no jre subdir)
├── conf/         # JDK config files (moved from jre/lib/security)
├── include/      # JNI headers
├── jmods/        # standard module JMOD files (compile-time)
├── legal/        # module licenses
├── lib/          # core runtime libraries (as modules file)
│   └── modules   # single binary containing all standard modules
└── man/          # help docs (optional)

JDK 8 to JDK 21/22: Major Changes & New Features

Version Baseline

JDK 8 — Classic Baseline, LTS, highest enterprise adoption, tags: Lambda, Stream, legacy business systems.

JDK 11 — Transition, LTS, mid-tier adoption, tags: lightweight trimming, initial container adaptation.

JDK 17 — New Mainstream, LTS, rapidly replacing JDK 8, tags: strong security, low-latency GC, syntax standardization.

JDK 21 — Latest Flagship, LTS, future standard, tags: virtual threads, concurrency revolution.

JDK 22 — Short-term, non-LTS, niche adoption, tags: extreme simplification, UX optimization.

One-line summary: JDK 9–16 were "experimental fields" with preview features; JDK 17 is "syntax unification"; JDK 21 is "concurrency revolution."

Core Language Features: Drastic Code Reduction

Record (JDK 14 preview → JDK 16 standard)

Solves JDK 8 pain: writing a POJO/DTO required 50+ lines of constructors, getters, equals, hashCode, toString. With record, a one-liner suffices:

// JDK 8: verbose Point class
public class Point {
    private final int x;
    private final int y;
    public Point(int x, int y) { this.x = x; this.y = y; }
    public int getX() { return x; }
    public int getY() { return y; }
    // equals, hashCode, toString ... 30+ more lines
}

// JDK 16+: one line
public record Point(int x, int y) {}

Compiler auto-generates: private final fields, canonical constructor, accessors ( x() / y()), equals / hashCode / toString. Ideal for DTOs, VOs, config carriers, multi-value returns. Not suitable for mutable fields or complex inheritance.

Sealed Classes (JDK 17 standard)

Restricts inheritance: traditional inheritance is "wide open"; sealed classes make it "controlled."

public sealed class Shape permits Circle, Rectangle { }
public final class Circle extends Shape { } // final: stops here
public non-sealed class Rectangle extends Shape { } // non-sealed: reopens inheritance
// public class Triangle extends Shape { } // ❌ compile error!

Subclasses must be final, sealed, or non-sealed. Maximum value: combined with pattern matching switch, compiler performs exhaustiveness checking — ensures all permitted subtypes are covered.

Pattern Matching (JDK 16 preview → JDK 17 standard for instanceof ; JDK 21 standard for switch )

Enhanced instanceof : eliminates redundant cast.

// JDK 8
if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.toUpperCase());
}
// JDK 17+
if (obj instanceof String s) {
    System.out.println(s.toUpperCase()); // s in scope only here
}

Switch Pattern Matching (JDK 21): replaces if-else chains.

// JDK 8
static String format(Object obj) {
    if (obj instanceof Integer) {
        int i = (Integer) obj;
        return "整数:" + i;
    } else if (obj instanceof String) {
        String s = (String) obj;
        return "字符串:" + s;
    }
    return "未知";
}
// JDK 21+
static String format(Object obj) {
    return switch (obj) {
        case Integer i -> "整数:" + i;
        case String s  -> "字符串:" + s.toUpperCase();
        case null      -> "null 值";
        default        -> "其他类型";
    };
}

With sealed classes, compiler enforces exhaustiveness — missing a permitted subtype causes compile error.

Switch Expressions (JDK 14 standard)

Arrow syntax returns values, eliminates break fall-through bugs.

// JDK 8
String result;
switch (day) {
    case MONDAY: result = "周一"; break;
    case TUESDAY: result = "周二"; break;
    default: result = "未知";
}
// JDK 14+
String result = switch (day) {
    case MONDAY, FRIDAY -> "开心";
    case SUNDAY       -> "还行";
    default           -> "搬砖";
};

Text Blocks (JDK 15 standard)

Triple-quote strings preserve formatting — no more \n and + concatenation for SQL/JSON.

// JDK 8
String sql = "SELECT id, name, age
" +
           "FROM users
" +
           "WHERE age > 18
" +
           "ORDER BY id";
// JDK 15+
String sql = """
    SELECT id, name, age
    FROM users
    WHERE age > 18
    ORDER BY id
    """;

var Type Inference (JDK 10)

Compile-time inference, not dynamic typing.

// JDK 8
Map<String, List<String>> map = new HashMap<String, List<String>>();
// JDK 10+
var map = new HashMap<String, List<String>>();

Interface Private Methods (JDK 9)

Allows code reuse between default methods without exposing helpers.

public interface Logger {
    default void logInfo(String msg) { log("INFO", msg); }
    default void logError(String msg) { log("ERROR", msg); }
    private void log(String level, String msg) { // JDK 9
        System.out.println("[" + level + "] " + msg);
    }
}

JVM & GC: Under-the-Hood Improvements

GC evolution: Parallel GC (throughput) → G1 (low latency, default from JDK 9) → ZGC (sub-10ms pauses, production-ready JDK 15) → Shenandoah → Generational ZGC (JDK 21, throughput + low latency). Other improvements: PermGen → Metaspace (native memory, eliminates PermGen OOM), container awareness (JDK 11+ auto-detects Docker CPU/memory limits), tiered compilation for faster startup.

Phased Core Features (Interview Must-Know)

JDK 9–11: JPMS modules, var, native HttpClient, PermGen removal, String storage char[] → byte[].

JDK 12–16: Switch expressions, Record preview, Sealed classes preview, Stream takeWhile / dropWhile.

JDK 17 (LTS): Sealed classes final, instanceof pattern matching, ZGC stable, strong encapsulation (blocks illegal reflection), removes CMS & SecurityManager.

JDK 21 (LTS): Virtual Threads (lightweight, M:N mapping, millions of threads, unmount on I/O), Structured Concurrency ( StructuredTaskScope), Scoped Values (replaces ThreadLocal), Generational ZGC.

JDK 22: Statement-level pattern matching, simplified launch (no fixed public class / main), enhanced Collection APIs.

Virtual Threads Deep Dive (JDK 21)

Problem: Platform threads = 1:1 OS kernel threads. 10,000 threads → memory explosion + context-switch overhead. Forces NIO/Netty/WebFlux → "callback hell."

Solution: Virtual threads managed by JVM, not OS. M:N mapping: many virtual threads multiplex onto few carrier (platform) threads. On I/O (DB, network, sleep), virtual thread unmount s, freeing carrier; resumes after I/O completes.

// JDK 8: traditional thread pool
var executor = Executors.newFixedThreadPool(200);
executor.submit(() -> {
    Thread.sleep(1000);
    return doSomething();
});
// JDK 21: virtual thread, one-liner
Thread.startVirtualThread(() -> {
    Thread.sleep(1000);
    doSomething();
});
// Or virtual-thread-per-task executor
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10000).forEach(i -> executor.submit(() -> process(i)));
}

Benchmark (10,000 tasks, each sleep 1s):

Time: Platform Threads (200-pool) ~50 seconds; Virtual Threads ~1 second.

Memory: Platform Threads very high; Virtual Threads extremely low.

Code Complexity: Platform Threads requires async frameworks; Virtual Threads synchronous style.

Virtual threads give Java Go-like lightweight concurrency while keeping synchronous code style.

Deprecated/Removed Features (Interview Traps)

PermGen, CMS collector (removed JDK 17).

SecurityManager (deleted).

Java EE legacy packages (JAXB, javax annotations) — must add dependencies manually.

Many outdated I/O, collection, reflection APIs marked deprecated.

Four LTS Comparison Cheat Sheet

Concurrency Model: JDK 8 heavy platform threads; JDK 11 no optimization; JDK 17 minor enhancements; JDK 21 virtual threads revolution.

Mainstream GC: JDK 8 G1/Parallel; JDK 11 G1; JDK 17 ZGC stable; JDK 21 Generational ZGC.

Syntax Power: JDK 8 Lambda+Stream; JDK 11 var, native HTTP; JDK 17 sealed, pattern matching; JDK 21 full-scenario simplification.

Container Fit: JDK 8 poor; JDK 11 fair; JDK 17 excellent; JDK 21 extreme adaptation.

Security: JDK 8 weak; JDK 11 medium; JDK 17 strict; JDK 21 enterprise-grade.

String Immutability & StringBuilder/StringBuffer

Why String Is Immutable (3 Core Reasons)

private final char[] value

— array reference fixed, no external access (no setters). final class String — cannot be subclassed to break immutability.

All "mutating" methods ( concat, replace) create new String objects; original value array unchanged.

Example: String s = "abc"; s = s.concat("d"); creates new "abcd" object; "abc" remains in constant pool.

String vs StringBuilder vs StringBuffer

Mutability: String immutable (new object on change); StringBuilder mutable (direct array ops); StringBuffer mutable (direct array ops).

Thread Safety: String safe (immutability); StringBuilder unsafe (no sync); StringBuffer safe (synchronized methods).

Efficiency: String lowest (many temp objects); StringBuilder highest (no lock); StringBuffer medium (lock overhead).

Underlying: String final char[] value; StringBuilder char[] value (no final); StringBuffer char[] value (no final).

Use Case: String rare changes, constants; StringBuilder single-thread, frequent changes; StringBuffer multi-thread, frequent changes.

Both StringBuilder and StringBuffer extend AbstractStringBuilder; difference is synchronization. Prefer StringBuilder for single-thread; avoid String concatenation in loops.

== vs equals() & hashCode() Contract

== vs equals()

== compares identity: primitives compare values; references compare memory addresses. equals() is an Object method; default compares addresses, but can be overridden to compare content (e.g., String overrides).

Comparison: == primitives: value; references: address. equals() default: address; overridden: content.

Overridable? == operator — no; equals() method — yes.

Typical Use: == check same heap object; equals() check business equality.

Example: String a="ab"; String b=new String("ab"); a==b → false; a.equals(b) → true (String overrides).

hashCode() & equals() Contract

If equals() returns true, hashCode() must be equal (required for hash collections).

If hashCode() equal, equals() not necessarily equal (hash collision).

Analogy: hashCode() = "neighborhood code"; equals() = "door number". Same door → same neighborhood; same neighborhood → many doors.

Critical: Override equals() → must override hashCode() . Otherwise HashMap / HashSet break: two equal objects may land in different buckets, containsKey() returns false. Reason: HashMap uses hashCode() to locate bucket, then equals() for exact match.

OOP Three Pillars & Interface vs Abstract Class

Encapsulation, Inheritance, Polymorphism

Encapsulation: Hide internals, expose via getters/setters (validate in setter). Like a phone — you press power button, don't touch circuits.

Inheritance: extends, single inheritance, reuse + extend. Child inherits non-private fields/methods, can override, call super.

Polymorphism: Same behavior, different implementations. Requires inheritance, method override, parent reference to child object. Enables decoupling — method accepts parent type, handles all children.

Interface vs Abstract Class Design Scenarios

Core distinction: Abstract class = "is-a" (shared state + partial impl) ; Interface = "has-a" / "can-do" (contract only) .

Essence: Interface can-do (capability); Abstract class is-a (identity).

Inheritance: Interface multiple implementations; Abstract class single inheritance.

Method Body: Interface JDK 8+ default / static; Abstract class can have concrete methods.

State: Interface only constants ( public static final); Abstract class instance variables allowed.

Constructor: Interface none; Abstract class yes (for child init).

Access Modifiers: Interface methods default public; Abstract class protected /package-private OK.

Use Abstract Class when: tightly related classes share fields & partial behavior; need Template Method pattern (skeleton in parent, steps in children); need protected members; stateful base (e.g., DAO base with DataSource).

Use Interface when: cross-hierarchy contracts (e.g., PaymentService for WeChat/Alipay/UnionPay); capability markers ( Comparable, Runnable); callbacks/listeners.

Best practice: Interface + skeletal abstract class (e.g., AbstractList, AbstractSet).

Java Exception System

Error vs Exception

Recoverable? Error no (programmer can't handle); Exception yes (catch/fix).

Cause: Error JVM-level (OOM, StackOverflow); Exception code logic / environment (NPE, IO).

Examples: Error OutOfMemoryError, StackOverflowError; Exception NullPointerException, IOException.

Exception subtypes: Checked (must handle: IOException, SQLException) vs Unchecked ( RuntimeException: NPE, index out of bounds).

try-catch-finally Execution Order

Rule: finally always executes (unless System.exit() or JVM crash). Three scenarios:

No exception: try → finally → subsequent code.

Exception caught: try (until exception) → catch → finally → subsequent code.

Exception not caught: try (until exception) → finally → exception propagates upward.

Return & Finally Pitfalls

return

value snapshotted before finally runs. finally executes before actual return. finally modifying local primitive / reassigning reference — no effect on returned value. finally modifying object contents (e.g., p.setName("李四")) — visible to caller. finally containing its own return — overrides everything, swallows exceptions (avoid).

// Returns 1 (finally changes local x, but snapshot already taken)
public static int test() {
    int x = 1;
    try { return x; }
    finally { x = 2; }
}
// Returns 2 (finally's return overrides)
public static int test2() {
    try { return 1; }
    finally { return 2; }
}
// Returns object with name "李四" (finally mutates object state)
public static Person test3() {
    Person p = new Person("张三");
    try { return p; }
    finally {
        p.setName("李四"); // mutates object → visible
        p = new Person("王五"); // reassigns reference → no effect
    }
}

Reflection: Principle, Pros/Cons, Real-World Uses

Core Principle

Reflection = runtime inspection & dynamic manipulation of class metadata (fields, methods, constructors, parents, interfaces). JVM creates a unique Class object per loaded class in method area — the "key" to unlock metadata.

Three steps: 1) Get Class key ( Class.forName(), obj.getClass(), Klass.class). 2) Find parts ( getDeclaredMethod(), getDeclaredField()). 3) Operate ( method.invoke(instance, args)).

Pros & Cons

Flexibility: Pros: god-tier dynamic wiring — swap impl without code change. Cons: lose compile-time safety — typos become NoSuchMethodException at runtime.

Performance: Pros: framework dev productivity. Cons: slower (10-100x), no JIT deep optimization, security checks, boxing overhead.

Encapsulation: Pros: access private members for tools. Cons: breaks encapsulation, security risk.

Dependencies: Pros: reduces compile-time hard deps. Cons: poor readability, broken IDE call chains, hard debugging.

Optimization tips: setAccessible(true) reduces access checks; cache Method / Field objects (thread-safe) — avoid repeated getMethod() in loops.

Real-World Scenarios

IoC Container (Spring-like): Scan @Component, Class.forName(), newInstance(), inject via field.setAccessible(true); field.set(obj, dependency).

Annotation Processing: @ExcelHeader on fields → reflect getDeclaredFields(), isAnnotationPresent(), getAnnotation() to read metadata, then field.get(obj) for values.

Dynamic Proxy (AOP): Proxy.newProxyInstance() with InvocationHandler; method.invoke(target, args) inside handler.

JDBC Driver Loading: Class.forName("com.mysql.cj.jdbc.Driver").

BeanUtils Property Copy: Reflect getters/setters for dynamic assignment.

Java Serialization, transient, serialVersionUID

Serialization Mechanism

Convert in-memory object → byte stream (persist to disk or send over network). Implement Serializable (marker interface), use ObjectOutputStream / ObjectInputStream. Process is recursive (entire object graph). static fields excluded (belong to class, not instance). Deserialization does not call constructor — allocates memory directly, restores field values.

transient Keyword

Marks a field to skip serialization. On deserialization, field gets default value (0/false/null). Example: private transient String password; — sensitive data not persisted. To restore value, implement custom writeObject / readObject private methods.

serialVersionUID

Version identifier for serialization compatibility. Written to stream during serialization; compared during deserialization. Mismatch → InvalidClassException.

Strongly recommend explicit declaration: private static final long serialVersionUID = 1L; Without it, compiler generates hash from class structure — any change (add field) changes UID, breaking existing serialized data. Explicit UID allows compatible changes (adding fields) without breaking deserialization.

Java IO: BIO / NIO / AIO Models

Core Analogy

BIO: Stand at door waiting for courier — do nothing else 😵 (Blocking).

NIO: Check door every few minutes; grab package if there, else do other work 👀 (Non-blocking, self-polling).

AIO: Authorize parcel locker; courier texts when delivered — you ignore it 📲 (Async, OS notifies).

Java Implementation

BIO ( java.io )

ServerSocket

+ thread-per-connection. read() blocks until data arrives. Simple but thread count = connection count → high context-switch overhead.

ServerSocket server = new ServerSocket(8080);
while (true) {
    Socket client = server.accept(); // main blocks
    new Thread(() -> { /* handle client, read blocks */ }).start();
}

NIO ( java.nio )

Core trio: Channel (bidirectional pipe), Buffer (data staging), Selector (multiplexer). Register channels to selector → single thread calls select() → processes only ready channels. Still synchronous — user thread copies data from kernel buffer via read(), but doesn't block waiting for readiness.

Selector selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(8080));
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
    selector.select(); // blocks until events
    Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
    while (keys.hasNext()) {
        SelectionKey key = keys.next();
        if (key.isAcceptable()) { /* handle new connection */ }
        else if (key.isReadable()) { /* read data */ }
        keys.remove();
    }
}

AIO ( java.nio.channels.Asynchronous* , JDK 7)

Methods return immediately; provide CompletionHandler callback or return Future. OS copies data kernel→user space, then notifies. True async — user thread does other work entirely.

AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();
server.bind(new InetSocketAddress(8080));
server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
    public void completed(AsynchronousSocketChannel client, Object attachment) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        client.read(buffer, null, new CompletionHandler<Integer, Object>() {
            // auto-invoked when read finishes
        });
    }
    public void failed(Throwable exc, Object attachment) { }
});

Comparison Summary

Blocking: BIO thread blocks entirely; NIO blocks only in select(); AIO never blocks.

I/O Type: BIO sync blocking; NIO sync non-blocking (multiplexing); AIO async non-blocking.

Thread Model: BIO 1 conn → 1 thread; NIO 1 thread → many conns; AIO callback/observer.

Thread Count: BIO high (∝ connections); NIO low (≈ CPU cores); AIO even lower (event-driven).

Data Copy: BIO user thread calls read; NIO user thread calls read; AIO kernel copies & notifies.

Java Package: BIO java.io; NIO java.nio; AIO java.nio.channels.Asynchronous*.

Best For: BIO low concurrency, legacy; NIO high concurrency (MQ, chat); AIO ultra-high perf file I/O, massive concurrency.

JDK 17/21 New Features Recap

Sealed Classes (JDK 17)

Restrict inheritance via sealed ... permits. Subclasses: final, sealed, non-sealed. Enables exhaustive switch checks.

Record (JDK 16/17)

record User(Long id, String name, Integer age) {}

— auto-generates final fields, canonical constructor, accessors ( name()), equals / hashCode / toString. For pure data carriers.

Pattern Matching for switch (JDK 21)

Type patterns, null patterns, constant patterns. Auto-casts, declares pattern variables. With sealed classes, compiler enforces exhaustiveness.

Virtual Threads (JDK 21)

JVM-managed, few KB each, millions possible. M:N mapping to carrier threads. Unmount on I/O. Ideal for I/O-bound high concurrency; CPU-bound gains minimal.

Structured Concurrency (JDK 21)

StructuredTaskScope

manages child threads: parent waits for all, exceptions propagate, cancellation support ( ShutdownOnFailure). Solves orphan threads, resource leaks.

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Future<User> userFuture = scope.fork(() -> userService.getUser(1L));
    Future<Order> orderFuture = scope.fork(() -> orderService.getOrder(1L));
    scope.join();
    scope.throwIfFailed();
    User user = userFuture.resultNow();
    Order order = orderFuture.resultNow();
}

Interview Answer Strategies

Status: Legacy systems on JDK 8; new/cloud-native projects on JDK 17.

Trend: High-concurrency, microservices, big data → JDK 21 adoption in top companies.

Core Value of Upgrading: Lower memory + lower GC latency + cleaner syntax + stronger security + native high concurrency.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaReflectionSerializationJDKInterviewVirtual ThreadsSealed ClassesRecords
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.