Java Optional, Date/Time API & Modern Java Features Interview Questions (2026) Interview Questions | JiQuest

add

#

Java Optional, Date/Time API & Modern Java Features Interview Questions (2026)

BACKEND INTERVIEW PREPARATION
Java Optional, Date/Time API & Modern Features
Master 100+ interview questions on Optional, java.time API, and Java 8 through 21 new features including records, sealed classes, pattern matching, text blocks, and virtual threads.
⏳ 45 min read 📝 100+ Q&As 🎯 Java 8 to 21
⚡ Quick Reference
Optional.of()Non-null value; throws NPE if null passed
Optional.ofNullable()Null-safe; returns empty Optional if null
LocalDate/Time/DateTimeImmutable, thread-safe; no timezone. Use ZonedDateTime for TZ.
Period vs DurationPeriod: date-based (years/months/days). Duration: time-based (seconds/nanos).
Java 10 varLocal variable type inference — type inferred by compiler
Java 16 RecordImmutable data class; auto-generates constructor, equals, hashCode, toString
Java 17 SealedRestricts which classes can extend: sealed class X permits A, B
Java 21 Virtual ThreadsLightweight threads managed by JVM; Thread.ofVirtual().start()
Java Version Feature Map
Java 8
Lambdas, Stream API, Optional, java.time, default methods, method references
Java 9
Modules, JShell, private interface methods, Stream.takeWhile/dropWhile, Optional.ifPresentOrElse
Java 10
var (local type inference), List.copyOf, Collectors.toUnmodifiableList
Java 11
String.strip/lines/repeat/isBlank, Files.writeString, Predicate.not, HTTP Client API
Java 14
Switch expressions (standard), helpful NullPointerExceptions, records (preview)
Java 16
Records (standard), instanceof pattern matching (standard), Stream.toList()
Java 17
Sealed classes (standard), text blocks (standard since 15), strong encapsulation
Java 21
Virtual threads, sequenced collections, pattern matching for switch (standard), record patterns

Java Optional Interview Questions & Answers

Q1. What is Optional and why was it introduced?

A: Optional<T> is a container that may or may not hold a non-null value. Introduced in Java 8 to reduce NullPointerExceptions by making the possibility of absence explicit in the type system. Instead of returning null, methods return Optional, forcing callers to handle the absent case.

Q2. What is the difference between Optional.of() and Optional.ofNullable()?

A: Optional.of(value) — value must NOT be null; throws NullPointerException immediately if null is passed. Optional.ofNullable(value) — null-safe; returns Optional.empty() if null. Use of() when you're certain the value is non-null; ofNullable() when it might be null.

Optional<String> a = Optional.of("hello");        // OK
Optional<String> b = Optional.of(null);           // NullPointerException!
Optional<String> c = Optional.ofNullable(null);   // Optional.empty()
Optional<String> d = Optional.ofNullable("hi");   // Optional[hi]

Q3. What are Optional.get(), orElse(), orElseGet(), and orElseThrow()?

A: get() returns the value or throws NoSuchElementException if empty — avoid without isPresent() check. orElse(defaultValue) returns value or the default (default is always evaluated). orElseGet(Supplier) returns value or calls supplier — lazy, only evaluated if empty. orElseThrow() throws NoSuchElementException; orElseThrow(Supplier) throws custom exception.

Optional<String> opt = Optional.empty();
opt.orElse("default");                        // "default" (always computed)
opt.orElseGet(() -> computeDefault());        // lazy — only called if empty
opt.orElseThrow();                            // NoSuchElementException
opt.orElseThrow(() -> new RuntimeException("missing"));

Q4. What is the difference between orElse() and orElseGet()?

A: orElse(value) evaluates the default value ALWAYS, even if the Optional has a value — costs resources if the default involves object creation or method calls. orElseGet(Supplier) evaluates only if the Optional is empty — lazy. Always prefer orElseGet() when the default computation is expensive.

// Bad: expensiveCall() always runs
String val = opt.orElse(expensiveCall());

// Good: expensiveCall() only runs if opt is empty
String val2 = opt.orElseGet(() -> expensiveCall());

Q5. How does Optional.map() work?

A: map(Function) applies the function to the value if present and wraps the result in Optional. If empty or if mapper returns null, returns Optional.empty(). Chains transformations without explicit null checks.

Optional<String> name = Optional.of("john doe");
Optional<Integer> len = name.map(String::length);        // Optional[8]
Optional<String> upper = name.map(String::toUpperCase); // Optional[JOHN DOE]
Optional<String> empty = Optional.<String>empty().map(String::toUpperCase); // Optional.empty

Q6. What is the difference between Optional.map() and Optional.flatMap()?

A: map(Function<T,R>) wraps the result in Optional automatically — if mapper returns Optional, you get Optional<Optional>. flatMap(Function<T, Optional<R>>) expects mapper to return Optional — no double-wrapping. Use flatMap when calling methods that themselves return Optional.

Optional<User> user = findUser(1);
// With map: Optional<Optional<Address>> - double wrapped!
Optional<Optional<Address>> bad = user.map(u -> u.getAddress()); // if getAddress returns Optional
// With flatMap: Optional<Address> - correct
Optional<Address> addr = user.flatMap(u -> u.getAddress());

Q7. What is Optional.filter()?

A: filter(Predicate) returns the same Optional if value is present and predicate returns true; returns empty Optional otherwise. Useful for conditional access.

Optional<Integer> positive = Optional.of(5).filter(n -> n > 0); // Optional[5]
Optional<Integer> filtered = Optional.of(-3).filter(n -> n > 0); // Optional.empty

Q8. What is ifPresent() vs ifPresentOrElse()?

A: ifPresent(Consumer) executes consumer if value present; does nothing if empty. ifPresentOrElse(Consumer, Runnable) — Java 9 — executes consumer if present, or Runnable if empty. Cleaner than if(opt.isPresent()) ... else ...

opt.ifPresent(v -> System.out.println("Found: " + v));
opt.ifPresentOrElse(
    v -> System.out.println("Found: " + v),
    () -> System.out.println("Not found")
);

Q9. What is Optional.or() introduced in Java 9?

A: or(Supplier<Optional>) returns this Optional if non-empty, or the supplier's Optional if empty. Useful for chaining fallback Optionals. Different from orElseGet() which returns a raw value, not Optional.

Optional<String> primary = Optional.empty();
Optional<String> fallback = Optional.of("backup");
Optional<String> result = primary.or(() -> fallback); // Optional[backup]

Q10. What are Optional anti-patterns to avoid?

A: 1) Returning null Optional (return null instead of Optional.empty() defeats the purpose). 2) Using Optional as method parameter — use overloading or default values instead. 3) Using Optional as field — adds overhead; use null with @Nullable annotation. 4) Calling get() without isPresent() check. 5) Using Optional in collections — List<Optional> is awkward; use filter/flatMap instead. 6) Using isPresent()+get() instead of map/orElse chains.

Q11. What is Optional.stream() introduced in Java 9?

A: Returns a Stream of one element if value present, empty Stream if absent. Enables Optional to participate in Stream.flatMap() pipelines for filtering out absent values.

List<Optional<String>> list = List.of(Optional.of("a"), Optional.empty(), Optional.of("b"));
List<String> values = list.stream()
    .flatMap(Optional::stream)
    .collect(java.util.stream.Collectors.toList()); // ["a", "b"]

Q12. Does Optional work with serialization?

A: Optional does NOT implement Serializable intentionally. Don't use Optional as a field in serializable classes. Use @Nullable annotations or regular null fields for serializable data classes.

Java Date/Time API Interview Questions

Q13. Why was the new Date/Time API introduced in Java 8?

A: The old java.util.Date and Calendar had major problems: mutable (not thread-safe), poor API design (month 0-indexed), difficult date arithmetic, no time zone separation. java.time (JSR-310, inspired by Joda-Time) provides immutable, thread-safe classes with clear separation of concepts.

Q14. What is the difference between LocalDate, LocalTime, LocalDateTime, and ZonedDateTime?

A:

ClassContainsUse Case
LocalDateDate only (2024-07-14)Birthdays, due dates
LocalTimeTime only (10:30:00)Daily schedules
LocalDateTimeDate + Time, no TZLocal events
ZonedDateTimeDate + Time + TimeZoneGlobal events, APIs
InstantUTC epoch timestampDB timestamps, logs

Q14b. How do you create date/time objects?

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1990, Month.JUNE, 15);
LocalTime noon = LocalTime.of(12, 0, 0);
LocalDateTime meeting = LocalDateTime.of(2026, 7, 14, 10, 30);
ZonedDateTime ist = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
Instant now = Instant.now(); // UTC epoch

Q15. What is the difference between Period and Duration?

A: Period: date-based difference (years, months, days). Duration: time-based difference (hours, minutes, seconds, nanoseconds). Use Period for human-readable date gaps; Duration for precise time spans.

LocalDate start = LocalDate.of(2020, 1, 1);
LocalDate end = LocalDate.of(2026, 7, 14);
Period p = Period.between(start, end);
System.out.println(p.getYears() + "y " + p.getMonths() + "m " + p.getDays() + "d");

Instant t1 = Instant.now();
// ... some work ...
Instant t2 = Instant.now();
Duration d = Duration.between(t1, t2);
System.out.println(d.toMillis() + "ms");

Q16. How do you format and parse dates?

A: Use DateTimeFormatter — thread-safe and immutable, unlike SimpleDateFormat. Built-in formatters or custom patterns.

LocalDate date = LocalDate.of(2026, 7, 14);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formatted = date.format(fmt); // "14/07/2026"

LocalDate parsed = LocalDate.parse("14/07/2026", fmt);

// ISO formats built-in:
String iso = date.format(DateTimeFormatter.ISO_LOCAL_DATE); // "2026-07-14"

Q17. What are temporal adjusters?

A: TemporalAdjusters provide date manipulation operations: next(DayOfWeek), previous, firstDayOfMonth, lastDayOfMonth, firstInMonth, etc.

LocalDate today = LocalDate.now();
LocalDate nextMonday = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
LocalDate firstDay = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDay = today.with(TemporalAdjusters.lastDayOfYear());

Q18. How do you convert between java.util.Date and java.time?

// Date -> Instant -> LocalDateTime
Date oldDate = new Date();
Instant instant = oldDate.toInstant();
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

// LocalDateTime -> Date
Date newDate = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Q19. How does ChronoUnit work?

A: ChronoUnit provides standard date/time units and a between() method for calculating differences.

LocalDate start = LocalDate.of(2026, 1, 1);
LocalDate end = LocalDate.of(2026, 7, 14);
long days = ChronoUnit.DAYS.between(start, end);   // 194
long months = ChronoUnit.MONTHS.between(start, end); // 6

LocalDateTime t1 = LocalDateTime.now();
LocalDateTime t2 = t1.plusHours(2).plusMinutes(30);
long minutes = ChronoUnit.MINUTES.between(t1, t2);  // 150

Q20. How is java.time thread-safe?

A: All java.time classes (LocalDate, LocalDateTime, ZonedDateTime, etc.) are immutable — all modification methods return new instances. DateTimeFormatter is also stateless and thread-safe. This contrasts with java.util.Date (mutable) and SimpleDateFormat (NOT thread-safe — famous source of bugs in multi-threaded apps).

Modern Java Features (8 to 21) Interview Questions

Q21. What is the var keyword (Java 10)?

A: var enables local variable type inference — the compiler infers the type from the right-hand side. Only valid for local variables, not method parameters, fields, or return types. The inferred type is fixed at compile time (not dynamic like JavaScript).

var list = new ArrayList<String>();  // type: ArrayList<String>
var map = new HashMap<String, Integer>();
var entry = map.entrySet().iterator().next(); // Map.Entry<String,Integer>
// var cannot be used for:
// var x; // no initializer — error
// public var name; // field — error

Q22. What are the new String methods in Java 11?

A: Java 11 added: isBlank() (true if empty or whitespace), strip() (Unicode-aware trim), stripLeading(), stripTrailing(), lines() (returns Stream<String> of lines), repeat(n) (repeats string n times).

"  ".isBlank();           // true
"  hello  ".strip();       // "hello" (Unicode-aware)
"ab".repeat(3);            // "ababab"
"line1\nline2\nline3".lines().count(); // 3

Q23. What are switch expressions (Java 14)?

A: Switch expressions return a value, use arrow (lambda-style) syntax, and don't fall through. The yield keyword returns a value from a block arm. Traditional switch statements still work; expressions are the modern alternative.

// Switch expression (Java 14+)
String result = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> "Weekend or boundary";
    case TUESDAY -> "Tuesday";
    default -> {
        String msg = "Midweek: " + day;
        yield msg; // yield returns value from block
    }
};

Q24. What are text blocks (Java 15)?

A: Text blocks use triple-double-quotes to define multi-line strings without escape sequences. Leading whitespace is stripped based on indentation. Trailing whitespace on each line is stripped. Useful for JSON, HTML, SQL, XML literals in code.

String json = """
        {
            "name": "Rajesh",
            "role": "Java Developer"
        }
        """;
// No need for \n, \" escapes
String sql = """
        SELECT * FROM users
        WHERE active = true
        ORDER BY name
        """;

Q25. What are records in Java 16?

A: Records are immutable data classes. Syntax: record Name(Type field1, Type field2). Auto-generates: canonical constructor, getters (field name, not getField), equals(), hashCode(), toString(). Records are implicitly final and extend java.lang.Record.

record Point(int x, int y) {}
// Auto-generated: constructor, x(), y(), equals, hashCode, toString

Point p = new Point(3, 4);
System.out.println(p.x());   // 3 (not getX())
System.out.println(p);       // Point[x=3, y=4]

// Compact constructor for validation:
record Temperature(double celsius) {
    Temperature { // compact constructor
        if (celsius < -273.15) throw new IllegalArgumentException("Below absolute zero");
    }
}

Q26. What are the limitations of records?

A: Records cannot extend other classes (implicitly extend Record). They are implicitly final (cannot be subclassed). Fields are final — no setters. Cannot declare instance fields outside record components. Can implement interfaces. Can have static fields, methods, and additional constructors (must delegate to canonical).

Q27. What is instanceof pattern matching (Java 16)?

A: Combines instanceof check with type cast and variable binding in one expression. Eliminates explicit cast after instanceof check. The variable is in scope within the if block.

// Old style:
if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.length());
}
// Pattern matching (Java 16+):
if (obj instanceof String s) {
    System.out.println(s.length()); // s already bound and typed
}
// Can combine with conditions:
if (obj instanceof String s && s.length() > 5) { ... }

Q28. What are sealed classes (Java 17)?

A: Sealed classes restrict which classes can extend them. Permits clause lists allowed subclasses. Each permitted subclass must be: final (no further extension), sealed (extends with its own permits), or non-sealed (open to all). Enables exhaustive pattern matching in switch.

public sealed interface Shape permits Circle, Rectangle, Triangle {}
public record Circle(double radius) implements Shape {}
public record Rectangle(double width, double height) implements Shape {}
public non-sealed class Triangle implements Shape { ... }

// Exhaustive switch (compiler checks all cases covered):
double area = switch (shape) {
    case Circle c -> Math.PI * c.radius() * c.radius();
    case Rectangle r -> r.width() * r.height();
    case Triangle t -> t.computeArea(); // non-sealed — must handle
};

Q29. What is pattern matching for switch (Java 21)?

A: Extends switch to support type patterns, guarded patterns (when clause), and null handling. Works with objects (not just primitives/strings). With sealed types, the switch can be exhaustive and require no default.

static String format(Object obj) {
    return switch (obj) {
        case Integer i -> "int: " + i;
        case Long l -> "long: " + l;
        case String s when s.isEmpty() -> "empty string";
        case String s -> "string: " + s;
        case null -> "null value";
        default -> "other: " + obj;
    };
}

Q30. What are virtual threads (Java 21)?

A: Virtual threads are lightweight JVM-managed threads. Platform threads are OS threads (expensive: 1MB+ stack, OS scheduling). Virtual threads have small stacks (a few KB), mounted to platform carrier threads from a pool. Millions of virtual threads can exist simultaneously. Ideal for I/O-bound server workloads.

// Create virtual thread:
Thread.ofVirtual().start(() -> System.out.println("Virtual: " + Thread.currentThread()));

// Virtual thread executor (Loom):
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 1_000_000).forEach(i ->
        executor.submit(() -> task(i)) // 1M virtual threads
    );
}

Q31. What is the difference between platform threads and virtual threads?

AspectPlatform ThreadVirtual Thread
Managed byOSJVM
Stack size~1MBA few KB (grows as needed)
Max countThousandsMillions
Best forCPU-bound tasksI/O-bound tasks (web servers)

Q32. What are sequenced collections (Java 21)?

A: New interfaces: SequencedCollection (addFirst/addLast/getFirst/getLast/removeFirst/removeLast/reversed()), SequencedSet, SequencedMap. Added to List, Deque, SortedSet, SortedMap hierarchies. Provides uniform API for ordered collections without needing to know the specific type.

Q33. What are record patterns (Java 21)?

A: Extends pattern matching to deconstruct records inline in instanceof and switch. Allows accessing record components without explicit getter calls.

record Point(int x, int y) {}
Object obj = new Point(3, 4);
if (obj instanceof Point(int x, int y)) {
    System.out.println(x + ", " + y); // 3, 4 — directly deconstructed
}

// In switch:
String describe(Object o) {
    return switch (o) {
        case Point(int x, int y) when x == y -> "Diagonal point: " + x;
        case Point(int x, int y) -> "Point: " + x + ", " + y;
        default -> "Unknown";
    };
}

Q34. What are the Java 9 module system (JPMS) basics?

A: Java Platform Module System (Project Jigsaw): packages are grouped into modules. module-info.java declares: module name, requires (dependencies), exports (public API packages). Benefits: strong encapsulation, explicit dependencies, smaller JRE (jlink). Most application code uses unnamed module (classpath) for backward compatibility.

// module-info.java
module com.myapp.service {
    requires java.sql;
    requires com.myapp.core;
    exports com.myapp.service.api;
    // com.myapp.service.impl is NOT exported — encapsulated
}

Q35. What is JShell (Java 9)?

A: JShell is Java's REPL (Read-Eval-Print Loop) — an interactive tool to execute Java code snippets without writing a full class/method. Useful for quick testing, learning, and experimentation. Start with jshell command from terminal.

Q36. What are private interface methods (Java 9)?

A: Java 9 allows private and private static methods in interfaces. Used to share common code between default methods without exposing it as public API. Prevents code duplication inside interfaces.

interface Validator {
    boolean validate(String s);
    default boolean validateAndLog(String s) {
        boolean result = validate(s);
        log(s, result); // calls private method
        return result;
    }
    private void log(String s, boolean result) {
        System.out.println("Validated: " + s + " = " + result);
    }
}

Q37. What are the Java 11 HTTP Client API improvements?

A: Java 11 standardized HttpClient (incubated in Java 9). Supports HTTP/1.1 and HTTP/2, WebSocket, both synchronous and asynchronous modes, reactive streams for body handling.

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .GET().build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

Q38. What are helpful NullPointerExceptions (Java 14)?

A: Java 14+ (with -XX:+ShowCodeDetailsInExceptionMessages) provides detailed NPE messages pinpointing which variable was null. Instead of just "NullPointerException", you get: "Cannot invoke 'String.length()' because 'str' is null".

Q39. What are the key Java 12-13 features?

A: Java 12: Switch expressions (preview), Collectors.teeing(), String indent(n) and transform(Function). Java 13: Text blocks (preview), Socket API reimplementation (Project Loom infrastructure). Both versions were stepping stones to LTS Java 17.

Q40. What is the difference between Java LTS and non-LTS versions?

A: LTS (Long-Term Support) versions (Java 8, 11, 17, 21) receive extended security/bug fix updates (3-8+ years). Non-LTS versions (9, 10, 12-16, 18-20) are supported for 6 months. Production environments typically use LTS versions. The 6-month cadence allows features to graduate from preview to standard across 2-3 releases.

Q41. What is the Collections.unmodifiableList vs List.of() vs List.copyOf()?

A: Collections.unmodifiableList(list) wraps an existing list — view-only, but the original list can still be mutated (structural changes reflected). List.of(elements) — Java 9 — creates an immutable list (no add/remove/set, no nulls allowed). List.copyOf(collection) — Java 10 — creates an immutable copy of existing collection.

List<String> mutable = new ArrayList<>(List.of("a","b","c"));
List<String> view = Collections.unmodifiableList(mutable); // view changes if mutable changes
List<String> immutable = List.of("a","b","c");  // truly immutable, no nulls
List<String> copy = List.copyOf(mutable);       // immutable snapshot

Q42. What are Map.of() and Map.entry() (Java 9)?

A: Map.of(k1,v1, k2,v2,...) creates an immutable Map with up to 10 entries (overloads for each count). Map.ofEntries(entry, ...) handles more entries. Map.entry(k,v) creates an immutable entry. No nulls allowed.

Map<String, Integer> map = Map.of("a", 1, "b", 2, "c", 3);
// For more than 10 entries:
Map<String, Integer> big = Map.ofEntries(
    Map.entry("key1", 1), Map.entry("key2", 2) // ...
);

Q43. What is Stream.toList() introduced in Java 16?

A: Stream.toList() is a terminal operation returning an unmodifiable List. Shorter than collect(Collectors.toList()). The returned list does not support add/remove. For a mutable list, still use collect(Collectors.toList()).

Q44. What are the Files utility improvements in Java 11?

A: Java 11 added: Files.writeString(path, string), Files.readString(path), Files.isSameFile(). These avoid the boilerplate of Files.write/readAllBytes and new String conversions.

Path path = Path.of("output.txt");
Files.writeString(path, "Hello World"); // Java 11
String content = Files.readString(path); // Java 11

Q45. What is the instanceof check improvement for null?

A: instanceof always returns false for null — no NullPointerException. So if (obj instanceof String s) is safe even if obj is null: it evaluates to false, the variable s is not bound. No null check needed before instanceof.

Object obj = null;
if (obj instanceof String s) { // false — safe, no NPE
    System.out.println(s); // never reached
}
// Old code: if (obj != null && obj instanceof String) — extra null check needed

Q46. What are the Collectors.toUnmodifiableList/Set/Map added in Java 10?

A: Returns unmodifiable collections from stream operations. The collected result cannot be modified. Equivalent to wrapping collect(Collectors.toList()) with Collections.unmodifiableList(), but more concise.

Q47. What is the difference between preview and standard features?

A: Preview features are complete but not finalized — require --enable-preview JVM flag. They may change in future releases. Typically a feature stays in preview for 1-2 releases before becoming standard. Records: preview in Java 14, standard in 16. Sealed classes: preview in 15-16, standard in 17.

Q48. What is the enhanced instanceof in switch expressions (Java 21)?

A: Pattern matching for switch (Java 21 standard) allows type patterns, guarded patterns (when), and deconstruction patterns. Works on any Object reference. The switch is exhaustive for sealed hierarchies, requiring no default.

Q49. What are the key Collection factory changes in Java 9?

A: List.of(), Set.of(), Map.of() create immutable instances. They don't allow null values (throws NullPointerException). They use compact internal representations (smaller memory footprint than ArrayList). Iteration order of Set.of() and Map.of() is unspecified (may vary run to run).

Q50. What is Instant vs LocalDateTime for storing timestamps?

A: Use Instant for absolute points in time (UTC epoch milliseconds) — for database timestamps, event logs, API responses. Use LocalDateTime for wall-clock time in a specific context without timezone (e.g., appointment scheduled "at 3pm" without specifying timezone). Use ZonedDateTime to combine both for global events.

Q51. What are compact constructors in records?

A: Compact constructor omits the parameter list — it implicitly receives all record components. Used to add validation or normalization logic. Fields are assigned automatically after the compact constructor body.

record Range(int min, int max) {
    Range { // compact constructor
        if (min > max) throw new IllegalArgumentException("min > max");
        // min and max are assigned automatically after this block
    }
}
new Range(1, 10);  // OK
new Range(10, 1);  // IllegalArgumentException

Q52. Can records extend other classes?

A: No. Records implicitly extend java.lang.Record and cannot extend any other class (single inheritance). However, records CAN implement interfaces. This makes records ideal for implementing interface-based value types like DTOs, value objects, and API responses.

Q53. What is the difference between sealed class permits and non-sealed?

A: A sealed class lists its permitted subclasses with permits. Each subclass must choose: final (end of hierarchy), sealed (continues with its own permits), or non-sealed (reopens for open extension). This lets library authors seal the core type while allowing non-sealed for user-extensible subtypes.

Q54. What Java 17 features are most important for backend developers?

A: 1) Sealed classes for domain modeling and exhaustive switches. 2) Records for DTOs/value objects. 3) Pattern matching instanceof for type-safe casting. 4) Strong encapsulation of JDK internals (replaces many --add-opens hacks). 5) Text blocks for SQL/JSON in code. Java 17 is LTS and the major upgrade target from Java 11.

Q55. What is Project Loom and how do virtual threads change Spring/backend applications?

A: Virtual threads (Java 21, Project Loom) enable thread-per-request model at scale. Traditional Spring MVC on Tomcat uses platform threads (limited to ~200 concurrently). With virtual threads, each HTTP request gets its own virtual thread — millions concurrently, blocking I/O unmounts carrier thread automatically. Spring Boot 3.2+ supports virtual threads via spring.threads.virtual.enabled=true.

Q56. What is the difference between String.trim() and String.strip()?

A: trim() removes characters with ASCII value ≤ 32 (old definition of whitespace). strip() — Java 11 — removes Unicode whitespace as defined by Character.isWhitespace() — handles all Unicode space characters. For modern code, prefer strip()/stripLeading()/stripTrailing().

Q57. What is the instanceof null behavior change in Java 21 switch?

A: Pattern matching switch (Java 21) can handle null explicitly with case null. Previously, switch on a null reference always threw NullPointerException. Now you can add case null to handle it gracefully without a separate null check.

String result = switch (obj) {
    case null -> "null value";
    case String s -> "String: " + s;
    default -> "other";
};

Q58. What are the improvements to Optional in Java 9 and 11?

A: Java 9: ifPresentOrElse(Consumer, Runnable), or(Supplier<Optional>), stream(). Java 11: isEmpty() (complement of isPresent() — no need for !opt.isPresent()). These additions make Optional more useful in functional pipelines.

Optional<String> opt = Optional.empty();
opt.isEmpty(); // true — Java 11
// Java 9:
opt.ifPresentOrElse(System.out::println, () -> System.out.println("empty"));
Optional<String> withFallback = opt.or(() -> Optional.of("fallback")); // Optional[fallback]

Q59. What is the enhanced switch with yield?

A: yield is used inside a block arm of a switch expression to return a value. Unlike return, yield only exits the switch expression, not the enclosing method. Required when the switch arm has multiple statements.

int result = switch (grade) {
    case "A" -> 4;           // arrow: no yield needed
    case "B" -> 3;
    default -> {
        System.out.println("Processing: " + grade);
        yield 0;              // yield required in block
    }
};

Q60. What is the structured concurrency API (Java 21 preview)?

A: Structured concurrency (JEP 453, preview in 21) treats multiple concurrent tasks as a unit. StructuredTaskScope ensures subtasks are cleaned up when parent exits. Subtasks are cancelled if the parent is cancelled, and their results/exceptions can be handled uniformly.

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    var user = scope.fork(() -> fetchUser(id));
    var order = scope.fork(() -> fetchOrder(id));
    scope.join().throwIfFailed();
    return new Dashboard(user.get(), order.get());
}

Q61. How do records interact with Jackson serialization?

A: Jackson 2.12+ supports records. By default, uses record components (field names) for serialization. Deserialization uses the canonical constructor. Use @JsonProperty on components for custom names. Records are ideal for Spring REST response DTOs.

record UserDTO(@JsonProperty("user_name") String name, int age) {}
// Serializes to: {"user_name":"John","age":30}
// Deserializes via constructor: new UserDTO("John", 30)

Q62. What are the String methods added in Java 12?

A: indent(n) adds n spaces to each line (negative removes). transform(Function) applies function to the string. describeConstable() and resolveConstantDesc() for constant folding. stripIndent() and translateEscapes() standardized in Java 15 for text blocks.

Q63. What is ZoneOffset vs ZoneId?

A: ZoneOffset is a fixed UTC offset (e.g., +05:30). ZoneId is a named time zone (e.g., "Asia/Kolkata") that handles DST transitions. OffsetDateTime uses ZoneOffset; ZonedDateTime uses ZoneId. For IST: ZoneId.of("Asia/Kolkata"), offset +05:30 (no DST).

ZoneOffset offset = ZoneOffset.of("+05:30");
ZoneId zone = ZoneId.of("Asia/Kolkata");
OffsetDateTime odt = OffsetDateTime.now(offset);
ZonedDateTime zdt = ZonedDateTime.now(zone);

Q64. What is the difference between LocalDate.of() and LocalDate.parse()?

A: of(year, month, day) creates from integers — compile-time known values, no parsing overhead. parse(string) parses from a string using ISO format by default — for runtime input. parse(string, formatter) with custom formatter for non-ISO formats.

Q65. How do you do date arithmetic with java.time?

LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plusWeeks(1);
LocalDate lastMonth = today.minusMonths(1);
LocalDate nextYear = today.plusYears(1);
boolean isLeapYear = today.isLeapYear();
DayOfWeek dayOfWeek = today.getDayOfWeek(); // MONDAY, TUESDAY, ...
int dayOfYear = today.getDayOfYear(); // 1-365/366

Q66. What is the Clock class in java.time?

A: Clock provides the current instant, date, and time using a time zone. Used for dependency injection in tests — replace Clock.systemUTC() with a fixed or offset clock to control time in tests. All java.time "now" methods accept a Clock parameter.

Clock fixedClock = Clock.fixed(Instant.parse("2026-07-14T10:00:00Z"), ZoneOffset.UTC);
LocalDate testDate = LocalDate.now(fixedClock); // always 2026-07-14 in tests

Q67. What is the difference between Java 8 default interface methods and abstract class methods?

A: Default interface methods have a body but no state access (no instance fields). Abstract class methods can access instance fields. Default methods can be overridden or explicitly selected with Interface.super.method(). Abstract class methods participate in the normal inheritance chain. Default methods solve the multiple inheritance of behavior problem for interfaces.

Q68. How do you migrate from java.util.Date to java.time in practice?

A: Strategy: 1) Use Instant at system boundaries (DB, REST APIs). 2) Use LocalDate/LocalDateTime for business logic. 3) Convert only at JPA boundaries using @Temporal or AttributeConverter. 4) Spring Data JPA 2.0+ handles java.time natively. 5) Replace SimpleDateFormat with DateTimeFormatter globally.

Q69. What are the Java 21 sequenced collection methods?

A: SequencedCollection adds: getFirst(), getLast(), addFirst(e), addLast(e), removeFirst(), removeLast(), reversed(). List, Deque (and subclasses) implement these. LinkedHashSet now implements SequencedSet. Previously you needed list.get(0) vs list.get(size-1) — now uniform getFirst()/getLast().

Q70. What is String.formatted() introduced in Java 15?

A: String.formatted(args) is an instance method equivalent to String.format(this, args). More concise and object-oriented. Useful with text blocks for interpolation.

String msg = "Hello, %s! You have %d messages.".formatted("Rajesh", 5);
// Same as: String.format("Hello, %s! You have %d messages.", "Rajesh", 5)

Q71. What are the key improvements to the garbage collector in recent Java versions?

A: Java 11: Epsilon GC (no-op, for benchmarking). Java 12: Shenandoah (low-pause, concurrent). Java 14: G1 GC became default from Java 9; ZGC went production (sub-millisecond pauses). Java 15: ZGC and Shenandoah production. Java 21: Generational ZGC (default option). For web servers: G1 or ZGC. For ultra-low latency: ZGC.

Q72. What is the var keyword's limitation with anonymous types?

A: var can capture anonymous class types — an interesting use case where var allows accessing members of anonymous classes that aren't accessible through the named type:

var obj = new Object() {
    String message = "anonymous";
    void greet() { System.out.println(message); }
};
obj.greet();     // works with var
obj.message;     // works — captured anonymous type

Q73. What is the enhanced for-loop with records and pattern matching?

A: Java 22 (preview) allows pattern variables in for loops. In Java 21, you use instanceof in the loop body or process records via their accessor methods. Records make data access clean through generated accessor methods.

Q74. What is the difference between isBlank() and isEmpty()?

A: isEmpty() returns true only if length is 0 — a string of spaces is NOT empty. isBlank() (Java 11) returns true if empty OR contains only whitespace. Use isBlank() for input validation; isEmpty() only when you need to check for zero-length string specifically.

"".isEmpty();    // true
"   ".isEmpty(); // false
"   ".isBlank(); // true
"".isBlank();    // true

Q75. What are the annotation improvements since Java 8?

A: Java 8: @Repeatable (same annotation multiple times), type annotations (annotate any use of type, not just declarations), ElementType.TYPE_USE and TYPE_PARAMETER. Java 9+: @Deprecated enhanced with forRemoval and since attributes. Java 16: @SuppressWarnings improved for pattern matching.

Q76. What is the try-with-resources improvement in Java 9?

A: Java 9 allows effectively final variables in try-with-resources, avoiding the need to re-declare the variable. The variable is closed automatically if it implements AutoCloseable.

// Java 7:
InputStream is = getStream();
try (InputStream is2 = is) { ... } // needed to redeclare

// Java 9+:
InputStream is = getStream();
try (is) { ... } // directly use effectively-final variable

Q77. How does Spring Boot 3 use Java 17+ features?

A: Spring Boot 3 (min Java 17): Uses records for configuration properties (@ConfigurationProperties). Uses sealed types for internal modeling. Pattern matching instanceof simplifies type checks in framework code. Text blocks for test SQL/JSON. Virtual threads via spring.threads.virtual.enabled=true (Spring Boot 3.2+). Spring 6 generates AOT metadata for GraalVM native image.

Q78. What is the Comparable interface and how does it relate to modern Java?

A: Comparable<T> with compareTo() defines natural ordering. Records that implement Comparable enable sorting without a separate Comparator. Pattern matching switch can route objects that implement specific Comparable subtypes. Java 21 records work naturally with TreeSet/TreeMap for sorted collections.

Q79. What is the difference between new Integer(5) and Integer.valueOf(5)?

A: new Integer(5) is deprecated since Java 9, removed in Java 17 — always creates a new object. Integer.valueOf(5) uses the Integer cache (-128 to 127) — returns cached instance for common values. Always use valueOf() or autoboxing. In Java 21, new Integer() is a compile error with Integer(int) constructor removed.

Q80. What are the deprecations and removals in Java 17?

A: Removed: Applet API, RMI Activation System, Security Manager (deprecated for removal), strongly encapsulates JDK internals (--add-opens needed for many reflection hacks). Deprecated for removal: finalize() in many classes. Java 17 is the major breaking point for legacy code relying on JDK internal APIs.

Q81. How do Optional and Stream work together in Java 9+?

// Flatten a list of Optionals to present values:
List<Optional<String>> opts = List.of(Optional.of("a"), Optional.empty(), Optional.of("c"));
List<String> values = opts.stream()
    .flatMap(Optional::stream)   // Java 9
    .collect(java.util.stream.Collectors.toList()); // ["a", "c"]

// Find first non-empty from multiple sources (Java 9 Optional.or):
Optional<String> result = getFromCache()
    .or(() -> getFromDB())
    .or(() -> Optional.of("default"));

Q82. What is the difference between switch expression and switch statement?

A: Switch statement: traditional, executes code for side effects, fall-through by default. Switch expression (Java 14+): produces a value, no fall-through with arrows, exhaustive (must cover all cases), can use yield. Both can use the traditional or arrow syntax. Rule: if you need a value, use expression; otherwise, statement.

Q83. What improvements came to instanceof in Java 16?

A: Pattern matching instanceof became standard in Java 16. The pattern variable (e.g., String s) is in scope: in the if block (when condition is true), and in the else-negation context when combined with negation (if (!(obj instanceof String s)) return; — then s is in scope after).

Q84. How do records compare to Lombok @Value?

A: Both create immutable value classes. Records: built into language (no dependency), limited customization, components are final, specific naming (getField() not getField-style). Lombok @Value: annotation-based, more flexible (can add methods, custom constructors easily), generates getters with getX() style. Records preferred for simple DTOs; Lombok for complex value objects needing more control.

Q85. What is the purpose of the non-sealed keyword?

A: non-sealed allows a permitted subclass of a sealed class to be extended freely by any class, removing the sealed restriction for that branch. Creates a mixed hierarchy: sealed root controls direct children, but non-sealed children can be extended by anyone. Useful for library design where you want to seal the primary types but allow one extensible branch.

Q86. What Java feature was most impactful for microservices development?

A: Records (Java 16) — reduced DTO boilerplate dramatically. Virtual threads (Java 21) — enables thread-per-request at scale without reactive programming complexity. Text blocks (Java 15) — cleaner SQL/JSON in code. Sealed types (Java 17) — better domain modeling for event-driven microservices. The combination of these Java 17/21 features is transforming how backend services are written.

Q87. What is DateTimeFormatter.ISO_INSTANT and when to use it?

A: ISO_INSTANT formats Instant as "2026-07-14T10:00:00Z" (UTC). Use for REST API responses, logging, and database storage where timezone-independent timestamps are needed. For human-readable local time in API responses, use ZonedDateTime with ISO_OFFSET_DATE_TIME.

Q88. What is the purpose of Scoped Values (Java 21 preview)?

A: ScopedValue is a modern alternative to ThreadLocal for virtual threads. ThreadLocal can leak memory with virtual threads (thousands per request). ScopedValue is immutable and bound to a scope, automatically unbound when the scope exits. Used to pass context (user, request ID) through a call chain without method parameters.

static final ScopedValue<String> USER = ScopedValue.newInstance();
ScopedValue.where(USER, "rajesh").run(() -> {
    System.out.println(USER.get()); // "rajesh" — available in scope
});

Q89. What are the key java.time interoperability points with Spring?

A: Spring MVC: Jackson 2.9+ serializes/deserializes java.time types automatically (jackson-datatype-jsr310 module). Spring Data JPA: @EntityListeners + Auditing uses Instant/LocalDateTime directly. @CreatedDate/@LastModifiedDate work with both. Spring Boot auto-configures Jackson with JavaTimeModule if jackson-datatype-jsr310 is on classpath.

Q90. What is the Memory API (Foreign Function and Memory API, Java 21)?

A: Foreign Function & Memory API (JEP 442, previewing toward standard in Java 22) lets Java code safely interact with native code and memory outside the JVM heap. Replaces unsafe.allocateMemory and JNI for native interop. Provides MemorySegment, MemoryLayout, Linker for safe off-heap memory access. Used for high-performance native library integration.

Q91. What is the difference between Optional.isEmpty() and Optional.isPresent()?

A: isPresent() returns true if a value is present (non-empty). isEmpty() (Java 11) returns true if no value is present (empty). isEmpty() = !isPresent(). isEmpty() was added to improve readability of negative checks: opt.isEmpty() is clearer than !opt.isPresent().

Q92. How does java.time handle leap seconds?

A: By default, java.time ignores leap seconds — it uses POSIX time where a day is always 86,400 seconds. Instant uses UTC-SLS (Smoothed Leap Seconds) in some implementations. For applications needing strict leap second handling, use a specialized TaiClock or external library. Most enterprise applications don't need leap second precision.

Q93. What is the significance of Java 21 being LTS after Java 17?

A: Java 21 is the next LTS after Java 17 (3 years gap, 6-month release cadence = 6 non-LTS versions in between). It brings: virtual threads (production), sequenced collections, record patterns, pattern matching for switch (standard), structured concurrency (preview). Most organizations on Java 11/17 should plan migration to Java 21 LTS.

Q94. Can you use records as JPA entities?

A: Not directly — JPA requires mutable no-arg constructor (proxy creation) and mutable state. Records are immutable and final (no proxying). Workaround: use records as DTOs/projections in Spring Data (Spring Data Projections with records work via interface-based or class-based projections). For actual entities, use regular classes or Kotlin data classes.

Q95. What is the String.indent() method (Java 12)?

A: indent(n) adds n spaces to the beginning of each line (if n > 0) or removes up to n leading spaces (if n < 0). Each line gets a trailing newline added if missing. Used with text blocks for dynamic indentation adjustment.

Q96. What is the difference between Java 8 CompletableFuture and virtual threads for async?

A: CompletableFuture: reactive/async style, non-blocking, complex chaining, harder to debug stack traces, good for I/O-bound work. Virtual threads: synchronous-looking code, blocking calls don't waste carrier threads, much simpler code, better stack traces. Spring WebFlux uses reactive; Spring MVC with virtual threads achieves similar throughput with simpler code. Virtual threads are the preferred approach for new Java 21+ applications.

Q97. How do you detect if code is running on a virtual thread?

Thread current = Thread.currentThread();
System.out.println("Is virtual: " + current.isVirtual()); // Java 21
System.out.println("Thread name: " + current.getName());
// Virtual threads have auto-generated names like "virtual-1"

Q98. What are the practical benefits of text blocks for database queries?

// Before text blocks (Java 14):
String sql = "SELECT u.id, u.name, u.email\n" +
             "FROM users u\n" +
             "JOIN orders o ON u.id = o.user_id\n" +
             "WHERE u.active = true\n" +
             "ORDER BY u.name";

// With text blocks (Java 15+):
String sql = """
        SELECT u.id, u.name, u.email
        FROM users u
        JOIN orders o ON u.id = o.user_id
        WHERE u.active = true
        ORDER BY u.name
        """;

Q99. What Java 8-21 features are most commonly asked in interviews?

A: Top asked features: 1) Lambdas and functional interfaces (Java 8). 2) Stream API (Java 8). 3) Optional (Java 8). 4) java.time (Java 8). 5) var (Java 10). 6) Switch expressions (Java 14). 7) Text blocks (Java 15). 8) Records (Java 16). 9) instanceof pattern matching (Java 16). 10) Sealed classes (Java 17). 11) Virtual threads (Java 21). Focus on these for 90% of interview coverage.

Q100. What is the recommended upgrade path from Java 8 to Java 21?

A: Step 1: Java 11 (LTS) — clean up deprecated APIs, add module compatibility, update dependencies. Step 2: Java 17 (LTS) — adopt records/sealed/text blocks, remove Security Manager usage, fix strong encapsulation issues (--illegal-access removed). Step 3: Java 21 (LTS) — adopt virtual threads for server applications, use pattern matching, migrate to sequenced collections API. Test at each step before moving to next.

Q101. What are the hidden gems of Java 11 that most developers miss?

A: 1) Predicate.not() for cleaner negation in streams. 2) Collection.toArray(IntFunction) — toArray(String[]::new) creates typed array cleanly. 3) Files.readString()/writeString() eliminates boilerplate. 4) Path.of() as cleaner Paths.get() alternative. 5) HttpClient for modern HTTP calls. 6) var in lambda parameters for annotating parameters. 7) Running single-file programs: java Hello.java (no compile step).

No comments
Leave a Comment