Interview
Java 9–21 Features — Interview Questions (95+)
See `pkg2versions` and core16–core17, core24–core28.
Detailed Questions
1. Java release cadence since Java 9?
- Short: 6-month releases; LTS every 2 years (11, 17, 21).
- Detailed: Feature releases (9,10,12…) get updates for ~6 months; LTS gets long-term support. Production typically targets LTS. Preview/incubator features need
--enable-preview. - Example: This project targets Java 21 LTS.
2. Java 9 — modules (JPMS)?
- Short:
module-info.javadefines exports/requires; strong encapsulation. - Detailed: Modules control visibility at compile and runtime.
requires transitivepasses dependency to consumers.opensfor reflection (Hibernate). Classpath JARs become unnamed module. - Example: `pkg15modules`.
3. Java 9 — collection factories?
- Short:
List.of,Set.of,Map.of— immutable, null-hostile. - Detailed: Compact, thread-safe, no setters.
Map.ofmax 10 pairs; useMap.ofEntriesbeyond. Duplicate keys throwIllegalArgumentException. - Example:
List.of(1,2,3)vsArrays.asList(mutable size).
4. Java 9 — Stream takeWhile/dropWhile?
- Short: Short-circuit on sorted/predicate prefix; not same as filter.
- Detailed:
takeWhilestops at first false; on infinite stream behaves like limit while true.dropWhileskips while true, then takes rest. - Example:
Stream.of(1,2,3,4,1).takeWhile(x->x<4)→ [1,2,3].
5. Java 10 — `var`?
- Short: Local variable type inference; still statically typed.
- Detailed: Compiler infers type from initializer. Not for fields, method params, or without initializer. Use when type obvious (
var list = new ArrayList<String>()). Avoid obscuring important types. - Example:
var map = Map.of("a", 1);
6. Java 11 — HttpClient?
- Short: Modern async/sync HTTP in
java.net.http; replaces Apache for many cases. - Detailed: HTTP/2, WebSocket, CompletableFuture async API. Immutable request/response objects.
- Example: `pkg10networking/networking5HttpClient.java`.
7. Java 14 — switch expressions?
- Short: Switch as expression with
->andyield; exhaustiveness for enums. - Detailed: No fall-through with arrows. Blocks use
yield value. Compiler checks enum/sealed coverage when exhaustive. - Example:
String r = switch (d) { case MON -> "weekday"; default -> "other"; };
8. Java 15 — text blocks?
- Short: Multi-line string literals with
"""; auto-indent strip. - Detailed: Escape sequences still work; concatenation with
+allowed..formatted()for interpolation-style formatting. - Example: JSON/SQL in
core9StringsDemo.
9. Java 16 — records?
- Short: Immutable data carriers: canonical ctor, equals/hashCode/toString, accessors.
- Detailed: Compiler generates boilerplate. Can implement interfaces, define compact ctor validation. Not JPA entities without care (no no-arg ctor by default).
- Example:
record Point(int x, int y) {}
10. Java 16 — pattern matching for instanceof?
- Short:
if (o instanceof String s)binds variable in scope. - Detailed: Eliminates cast after instanceof. Works with null (false, no binding).
- Example:
if (obj instanceof Integer n) sum += n;
11. Java 17 — sealed classes?
- Short: Restrict which classes can extend/implement; enables exhaustive switches.
- Detailed:
sealed class X permits A, B. Subclasses must befinal,sealed, ornon-sealed. Works with pattern matching switch. - Example:
core17SealedClassesDemo.
12. Java 21 — virtual threads?
- Short: Lightweight threads for massive blocking I/O concurrency.
- Detailed: JVM-scheduled; cheap to create millions. Don't pool them like platform threads. Pinning issue: synchronized block may pin carrier thread.
- Example:
Thread.startVirtualThread(() -> ...)orExecutors.newVirtualThreadPerTaskExecutor().
13. Java 21 — record patterns?
- Short: Deconstruct records in switch/instanceof patterns.
- Detailed:
case Point(int x, int y)extracts components. Guards withwhen. Null case explicit in switch. - Example:
versions6Java21Features.describe().
14. Java 21 — sequenced collections?
- Short:
SequencedCollection,SequencedSet,SequencedMap— uniform first/last/reversed. - Detailed:
getFirst(),getLast(),reversed(). Implemented byLinkedHashMap,ArrayList, etc. - Example:
list.getFirst()instead oflist.get(0)with clearer intent.
15. Preview features — how to use?
- Short:
--enable-previewon compile and run; API may change. - Detailed: String templates, structured concurrency were previews. Don't use preview in production without acceptance of churn.
- Example:
java --enable-preview MyApp.java
Rapid-Fire (Q → A)
- Java 8 headline? → Lambdas, streams, java.time.
- Java 9 headline? → Modules, JShell, factory methods.
- Java 10 headline? → var.
- Java 11 LTS headline? → HttpClient, String methods, run single-file.
- Java 14 headline? → Records preview, switch expr, helpful NPEs.
- Java 15 headline? → Text blocks, sealed classes preview.
- Java 16 headline? → Records, instanceof patterns.
- Java 17 LTS headline? → Sealed classes, pattern switch preview.
- Java 21 LTS headline? → Virtual threads, record patterns, sequenced collections.
- LTS releases? → 11, 17, 21 (also 8 before cadence change).
- module-info exports? → Public API of module.
- requires transitive? → Implicit dependency for consumers.
- opens package? → Deep reflection for framework.
- unnamed module? → Classpath JARs on module path.
- List.of mutable? → No.
- List.of null element? → NPE.
- Map.of max pairs? → 10.
- copyOf collections? → Immutable copy.
- var for field? → Not allowed.
- var without init? → Not allowed.
- HttpClient in which module? → java.net.http.
- run-java source? → java File.java (11+).
- switch arrow no fall-through? → Correct.
- switch yield? → Return from block case.
- record can extend class? → No (implicit extends Record).
- record can implement interface? → Yes.
- record accessor name? →
name()notgetName()unless override. - compact record ctor? → Validates before field assign.
- sealed permits required? → Yes on sealed type.
- non-sealed subclass? → Open to further extension.
- pattern switch exhaustiveness? → Compiler checks sealed/enums.
- virtual thread carrier? → Platform thread pool underneath.
- pin virtual thread? → synchronized/native on carrier.
- use platform threads when? → CPU-bound, many cores, short tasks.
- structured concurrency preview? → Scope for child task lifetime.
- String templates preview? → STR."Hello {name}".
- foreign function API? → Panama; call native code.
- vector API incubating? → SIMD operations.
- ZGC generational? → Java 21 improvement.
- Shenandoah? → Low-pause GC alternative.
- deprecate finalize? → Yes; use Cleaner.
- strong encapsulation JDK internals? → Illegal access warnings/errors.
- jlink? → Custom runtime image.
- reactive streams in JDK? → Flow API (Java 9).
- Optional.orElseThrow? → Java 10 (was get()).
- Collectors.toUnmodifiableList? → Java 10.
- teeing collector? → Combine two collectors.
- takeWhile on unordered stream? → Still short-circuits first false.
- dropWhile difference from skip? → Predicate-based prefix skip.
- Predicate.not? → Java 11 negation.
- Files.readString? → Java 11.
- isIdentical for strings? → Reference equality helper.
- record serialization? → Serial form defined; consider stability.
- record reflection? → Record components API.
- hidden classes? → Framework-generated (lambda impls).
- nestmates? → Inner/outer access control.
- compact source? → Smaller source file feature (preview).
- multi-file source? → Single class per file loosened (preview).
- deprecate SecurityManager? → Removed/disabled modern JDKs.
- javax to jakarta? → EE namespace change (not JDK but ecosystem).
- microprofile? → Small EE specs on Jakarta.
- enable-preview compile? → javac --enable-preview --release 21.
- migration 8→11 pain? → JAXB removed, illegal reflective access.
- migration 11→17? → Fewer breaking; sealed/records adoption.
- migration 17→21? → Virtual threads opt-in.
- jpackage? → Native installer (14+).
- instanceof pattern null? → false, no binding.
- switch null case? → Java 21 explicit
case null. - sequenced map reversed? → Reverse-order view.
- LinkedHashMap getFirst? → Java 21 SequencedMap.
- ArrayList reversed view? → SequencedCollection.
- ListIterator vs reversed? → reversed() is view.
- record generic? →
record Box<T>(T value) {}. - local record? → Allowed in methods.
- anonymous to private instance? → Less boilerplate with records.
- pattern for guarded case? →
case Integer i when i > 0. - exhaustiveness default needed? → For non-sealed/non-enum.
- java.time in which version? → Java 8.
- var with lambda? → Must infer functional interface type.
- var with diamond? →
var list = new ArrayList<>()infers raw-ish; specify generic.
Source named in this chapter
- networking5HttpClientpkg10networking/networking5HttpClient.java