Java 21 Interview Questions: Sequenced Collections, Pattern Switches, and Version Boundaries
Quick Overview
Trace event order and routing in Java 21, then verify which code can still build for Java 17.
A Java 21 refactor replaces list indexing with getFirst and uses a pattern switch to route queue events. It looks simpler but a teammate says the downstream library must still build for Java 17. In a Java 21 interview, explain what defines collection encounter order, how the switch handles type and null, and which Java release accepts the resulting code. Test the language target, standard library API, and runtime compatibility independently.
The event queue below is fictional. JEP 431 specifies sequenced collections, JEP 441 specifies pattern matching for switch as finalized in Java 21, and Oracle’s javac reference describes release targeting. Use the PracHub sealed class exercise to practise a neighboring exhaustive switch design.

What does a sequenced collection promise?
A sequenced collection has a defined encounter order. The APIs give a common way to ask for the first or last element and a reversed-order view. They do not define which order is appropriate for your product. An event list might put the oldest insertion first. A sorted collection may order according to its comparator. A collection without a suitable order contract should not be used to represent “the next operator action” unless the app imposes an order separately.
Take a list with events E03, E01, E02 in that insertion order. getFirst returns E03 and getLast returns E02. The first element of the reversed view is E02. Sorting the list by event number changes the contract and yields E01 first. A plain HashSet can change the encounter order the caller sees and does not provide the Java 21 sequenced collection contract. A LinkedHashSet is an option when the caller wants ordered unique elements and the chosen order matches its requirements.
The JEP defines the reversed result as a view backed by the original collection. Explain which mutations are supported by the concrete type. If a mutable list is updated after producing the reverse view, the view can reflect the change. Use a deliberate snapshot when the export requires its original sequence at review time. A copy of references can still show changes in mutable elements, even if the collection structure is immutable. Include that in the decision if the exercise needs a reliable audit artifact.
| Event list operation | Observable result in this case | Question for the caller |
|---|---|---|
| getFirst on E03, E01, E02 | E03 | Is insertion order the business priority? |
| reversed view then getFirst | E02 | Should a later change be visible in the view? |
| Sort by ordinal before reading | E01 | Is ordinal a validated field and is there a tie-breaker? |
| getFirst on an empty sequence | NoSuchElementException for the stated List contract | What is the empty-queue domain result? |
| Mutate an unmodifiable sequence | Operation may be unsupported | Which modification rights does the API expose? |
An interviewer might ask how this differs from List.get(0). In a list it may be mostly about naming a boundary. In an API accepting several types with encounter order, the common sequenced interface can express a property without requiring indexed access. Choose a read or write interface on purpose. Java exposes interfaces whose mutating methods may be optional, so test or document that aspect of the contract.

How do you trace a Java 21 pattern switch?
The example route policy treats a delayed Retry separately from a normal Retry. A separate null case models an empty or corrupt input in this exercise. The sealed event family describes which variants the application owns.
sealed interface Event permits Ready, Retry, Drop {}
record Ready(String id) implements Event {}
record Retry(String id, int delaySeconds) implements Event {}
record Drop(String id) implements Event {}
static String route(Event event) {
return switch (event) {
case null -> "review-missing-event";
case Ready ready -> "publish:" + ready.id();
case Retry retry when retry.delaySeconds() > 30 -> "delay:" + retry.id();
case Retry retry -> "retry-now:" + retry.id();
case Drop drop -> "close:" + drop.id();
};
}
A Retry with delay 31 selects delay, while delay 30 selects retry-now. Place the guarded Retry first. Putting unconditional Retry before it would cover the guarded pattern and causes a dominance error. The null label makes the missing-event result explicit. A switch without an applicable null case ordinarily throws NullPointerException. A default label should not be assumed to catch it. Check the source under the exact language release instead of importing assumptions from a pre-final preview.
Exhaustiveness depends on the covered variants and selector type. A sealed family can make missing cases discoverable when recompiling the switch. If another permitted subtype is added later, a switch compiled with the earlier set can still be deployed against newer types, so control module and artifact compatibility and compile against the same model version. Use a domain-appropriate result for unexpected input when the boundary is open or versioned. Distinguish expected domain variants from bad deserialization before saying the language guarantees impossible states end to end.
What compiles under which release?
The final pattern switch in the exercise targets Java 21. Pattern matching for switch appeared in earlier previews, including Java 17. Preview details varied across releases and Java 17 did not provide the final Java 21 feature. Sequenced collections entered the standard Java 21 API. On a Java 21 compiler targeting --release 17, calling List.getFirst is an API error, and this final pattern switch is outside the target language.
| Check | Expected result | Evidence |
|---|---|---|
| Compile the new exercise with Java 21 and target release 21 | Success under ordinary compilation | Toolchain version and accepted flags |
| Compile the Java 21 collection API excerpt with Java 21 targeting 17 | getFirst and reversed are unavailable through the target standard API | Keep the diagnostics visible |
| Compile the final pattern switch with target 17 and no preview settings | Rejected | Language target cannot accept final Java 21 syntax |
| Run release-21 classes on Java 17 | Compatibility failure for the newer class format | Preserve runtime and artifact version |
| Compile shared module with Java 21 targeting 17, using supported APIs and constructs | Can succeed if all other dependencies are compatible | Run on the actual Java 17 runtime as a separate check |
Ask which module in the deployment needs which target. A Java 21 service can depend on a library built for Java 17, subject to its other compatibility constraints. A shared Java 17 library can use Java 17 alternatives such as indexed reads through List if that is the chosen contract and order, or supported instanceof patterns where appropriate. Keep the Java 21-only API inside the service that guarantees its runtime. Build tasks and CI runners should name these boundaries explicitly so one developer’s local JDK does not decide publication behavior.
How would you review the resulting change?
Work through three observations. First, the list reverses presentation while preserving event object identity. Second, the switch routes four defined fixture cases and deliberately handles null. Third, the shared library still compiles for its contractual release and runs with that runtime. Keep expected results beside those checks. If the reviewer can see the output for two edge cases, they can judge the change without running a long demonstration.
Add one fixture where the first element changes after the team stores the reversed view. Use a mutable ArrayList and add E04 to the tail of the original after capturing the reversed view. Now the reverse head is E04. If the original API promised a snapshot holding E02, the implementation needs a snapshot of the appropriate order instead. Confirm whether elements can be null before choosing List.copyOf, because that API rejects null elements. Alternatively, create a separate collection appropriate to the contract.
Finally decide which properties of the old code the team relied on. The old polling code used an array-like list, had a defined result for empty work, and kept the order of events with equal priority. The refactor may obscure the old tie-break if it replaces the list with a sorted set whose comparator compares only priority. Add two distinct events with the same priority and verify both survive. Explain what ordered uniqueness means and whether the comparator intentionally collapses those two values.
A short answer could end with the deployment condition. “The service uses Java 21 to access the two ends of its chosen encounter order and switch over our sealed events. I’d keep that code away from the library targeting 17, prove the same order and routing for a concrete fixture, and build each artifact with an explicit release.”
How do you make one release boundary visible in CI?
Put the order check and the route check in separately compiled examples. First compile the sequence example with target 17. Its diagnostic should concern the missing Java 21 collection API. Separately compile the switch. The diagnostic there should concern the language feature. One file containing both failures can stop compilation at the first syntax error and hide the second boundary. On 21, run each from a clean output directory so artifacts built in the earlier attempt cannot leak into the result.
Build a third source that represents the shared contract. For Java 17, its caller can handle an empty list explicitly and call get(0) after that check. Run it under the Java 17 runtime even if it was compiled by a newer toolchain, and run a compatibility test where appropriate on the Java 21 consumer. The Java 17-facing artifact should never accidentally be substituted with a class file from the Java 21 service during the test. Keep versions or paths distinct and record the effective toolchain for both passes.
Review output at the visible boundary. The same test case E03, E01, E02 is useful across both builds because they can preserve the insertion-order decision using different APIs. Type-specific switching belongs only in the artifact that can use it. A reviewer can compare the same route result through a supported Java 17 alternative if the shared library actually needs equivalent behavior.
Review an API signature under the same constraints. A method that accepts only SequencedCollection documents encounter order directly for Java 21 clients. If a shared Java 17 interface used a plain Collection, it needs a separate strategy to guarantee order, such as accepting a List or requiring the caller to provide a sorted snapshot. Keeping a Java 21 type out of the implementation is insufficient if older callers still need to load the class or compile against its public signature. Inspect both the implementation and interface dependencies.
Related PracHub interview practice
Use these questions to separate a type-system choice from an order guarantee. In each answer, state the oldest release your caller supports and give one compiler or runtime observation.
| PracHub question | What to practise |
|---|---|
| Spring Boot Internals and Java 21 Features Behind a Machine Coding Solution | Explain which Java features require the application’s chosen version. |
| Java Core Deep Dive: Concurrent Collections and Java 8 Features | Compare order and concurrency guarantees across collection types. |
| Explain Java follow-ups after solving coding problem | Answer follow-ups about Java API contracts and compiler choices. |
| Add a Paginated GET Endpoint to an Existing Java Service, Then Design Its Production DB | Pick a stable order in a modern Java service boundary. |
| Evaluate Arithmetic Expressions with Parentheses | Map explicit cases to behavior and predict how the implementation handles an empty or invalid input. |
Use the PracHub sealed class exercise to add a new subtype and predict the compiler’s response. Rehearse the difference between a missing variant, an earlier dominating pattern, and an incompatible runtime.
Comments (0)