1Z0-830 Java SE 21 Developer - Practice Test 3
Your Progress
0 / 66
Question 1
MEDIUM
Given:
sealed interface Vehicle permits Car, Truck {}
final class Car implements Vehicle {}
final class Truck implements Vehicle {}
Vehicle v = new Car();
String type = switch (v) {
case Car c -> "Passenger";
case Truck t -> "Commercial";
};
System.out.println(type);
What is printed?
This demonstrates **exhaustive pattern matching** with sealed types in Java 21, where the compiler can verify that all possible subtypes are covered.
**Why This Compiles Without Default:**
1. **Sealed Type Analysis:** The compiler analyzes the sealed interface Vehicle and discovers it permits exactly two implementations: Car and Truck
2. **Exhaustiveness Checking:** The switch statement covers both permitted types:
- case Car c -> handles all Car instances
- case Truck t -> handles all Truck instances
3. **Complete Coverage:** Since these are the ONLY possible implementations (sealed type ensures this), the compiler knows the switch is exhaustive
4. **No Default Needed:** Unlike traditional switch statements or switches on non-sealed types, no default case is required
**Execution Flow:**
1. v references a Car object
2. The switch evaluates: case Car c matches
3. Pattern variable c is bound to the Car instance (though not used here)
4. Returns "Passenger"
5. Output: "Passenger"
**Key Benefits:**
**Type Safety:**
```java
// If you add a new permitted type:
sealed interface Vehicle permits Car, Truck, Motorcycle {}
final class Motorcycle implements Vehicle {}
// The compiler will ERROR on the switch:
// "the switch expression does not cover all possible input values"
// This forces you to handle the new case
```
**Compare to Non-Sealed Types:**
```java
// Without sealed types - requires default
interface Vehicle {} // Not sealed
class Car implements Vehicle {}
class Truck implements Vehicle {}
String type = switch (v) {
case Car c -> "Passenger";
case Truck t -> "Commercial";
default -> "Unknown"; // REQUIRED - anyone could implement Vehicle
};
```
**Pattern Variable Usage:**
```java
// You can use the pattern variable:
String type = switch (v) {
case Car c -> "Passenger: " + c.getModel();
case Truck t -> "Commercial: " + t.getCapacity() + "T";
};
```
**Nested Patterns:**
```java
// If Car and Truck were records:
record Car(String model) implements Vehicle {}
record Truck(int capacity) implements Vehicle {}
String type = switch (v) {
case Car(String m) -> "Passenger: " + m;
case Truck(int cap) -> "Commercial: " + cap + "T";
};
```
**Important Rules:**
1. Sealed types enable exhaustive switches without default
2. All permitted subtypes must be covered
3. Adding new permitted types breaks existing switches (by design - for safety)
4. Works with both classes and interfaces
5. Pattern variables are in scope in the corresponding case branch
See more: Java 21 New Features
Question 2
MEDIUM
Given:
Object obj = List.of("A", "B", "C");
switch (obj) {
case List<String> list -> System.out.println(list.size());
default -> System.out.println("Not a list");
}
What happens?
This question tests understanding of **type patterns with generics** in switch expressions, revealing an important limitation in Java's pattern matching.
**Why This Fails to Compile:**
**Generic Type Erasure:**
Java uses type erasure for generics. At runtime, `List<String>` becomes just `List`. The JVM cannot distinguish between `List<String>`, `List<Integer>`, or `List<Object>` at runtime.
**Pattern Matching Requirement:**
Pattern matching in switch requires that the type pattern can be checked at runtime. Since generic type information is erased, the pattern `List<String> list` cannot be verified at runtime.
**The Problem:**
```java
// These would be indistinguishable at runtime:
case List<String> list -> ...
case List<Integer> list -> ...
case List<Object> list -> ...
// All become: case List list -> ...
```
**Compilation Error:**
```
error: illegal generic type for instanceof
case List<String> list -> ...
^
```
**Correct Approaches:**
**Option 1: Use Raw Type Pattern**
```java
switch (obj) {
case List list -> { // Raw type - compiles
System.out.println(list.size());
// Warning: unchecked operations
}
default -> System.out.println("Not a list");
}
```
**Option 2: Use Bounded Type with Validation**
```java
switch (obj) {
case List list when !list.isEmpty() && list.get(0) instanceof String -> {
@SuppressWarnings("unchecked")
List<String> stringList = (List<String>) list;
System.out.println(stringList.size());
}
case List list -> System.out.println("List but not String list");
default -> System.out.println("Not a list");
}
```
**Option 3: Use Specific Collection Types**
```java
switch (obj) {
case ArrayList<?> list -> System.out.println("ArrayList: " + list.size());
case LinkedList<?> list -> System.out.println("LinkedList: " + list.size());
case List<?> list -> System.out.println("Other List: " + list.size());
default -> System.out.println("Not a list");
}
```
**Option 4: Check Elements Manually**
```java
switch (obj) {
case List<?> list when isStringList(list) ->
System.out.println("String list: " + list.size());
case List<?> list ->
System.out.println("Other list: " + list.size());
default ->
System.out.println("Not a list");
}
private static boolean isStringList(List<?> list) {
return !list.isEmpty() && list.get(0) instanceof String;
}
```
**Type Erasure Recap:**
```java
// At compile time:
List<String> stringList = new ArrayList<String>();
List<Integer> intList = new ArrayList<Integer>();
// At runtime (after erasure):
List stringList = new ArrayList(); // Type parameter erased
List intList = new ArrayList(); // Type parameter erased
// This is why generic patterns don't work:
// The JVM can't tell the difference!
```
**Related Patterns That Work:**
```java
// Primitive arrays - type preserved at runtime
switch (obj) {
case int[] arr -> System.out.println("int array");
case String[] arr -> System.out.println("String array");
default -> System.out.println("Other");
}
// Regular classes - no generics
switch (obj) {
case String s -> System.out.println("String");
case Integer i -> System.out.println("Integer");
default -> System.out.println("Other");
}
```
**Key Takeaway:** Pattern matching works with **reified types** (types that exist at runtime). Generic type parameters are erased and cannot be used in type patterns.
See more: Java 21 New Features
Question 3
MEDIUM
Given:
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return "Done";
});
}
}
What happens when the try block exits?
This demonstrates the **auto-close behavior** of ExecutorService combined with **virtual threads** in Java 21, showcasing how Java handles massive concurrency elegantly.
**ExecutorService AutoCloseable Behavior (Java 19+):**
ExecutorService implements AutoCloseable, and when used with try-with-resources:
1. **On Try Block Exit:**
- Calls `shutdown()` - stops accepting new tasks
- Waits for all submitted tasks to complete
- Calls `close()` which:
- Waits up to 1 day for tasks to finish
- If tasks don't finish, calls `shutdownNow()`
- Waits another 1 day
- Throws exception if still not finished
2. **Blocking Behavior:**
- The try-with-resources block **blocks** until all tasks complete
- This is different from manually calling shutdown(), which doesn't wait
**Virtual Threads Make This Practical:**
**Why 100,000 virtual threads is fine:**
```java
// With platform threads - DISASTER:
try (var executor = Executors.newCachedThreadPool()) {
for (int i = 0; i < 100000; i++) {
executor.submit(() -> {...});
// Would create 100K OS threads!
// System crash or severe performance degradation
}
}
// With virtual threads - PERFECTLY FINE:
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100000; i++) {
executor.submit(() -> {...});
// Creates 100K virtual threads
// Runs on small pool of platform threads (carrier threads)
// Minimal memory overhead
}
}
```
**Execution Timeline:**
```
Time 0s: Submit 100,000 tasks
All virtual threads created (lightweight)
Tasks start executing on carrier thread pool
Time 0-1s: Virtual threads block on Thread.sleep()
While blocked, virtual threads are "parked"
Carrier threads freed to run other virtual threads
Time ~1s: All tasks complete around the same time
(assuming sufficient carrier threads)
Time ~1s: try block exits
executor.close() verifies all tasks completed
Program continues
```
**Memory Comparison:**
**Platform Threads:**
```
100,000 threads * 2 MB stack = 200 GB memory
// Impossible on most systems!
```
**Virtual Threads:**
```
100,000 virtual threads * ~1 KB = ~100 MB memory
// Plus carrier thread pool (typically # of CPU cores)
// Easily manageable!
```
**Complete Execution Example:**
```java
System.out.println("Starting: " + Instant.now());
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100000; i++) {
int taskId = i;
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return "Task " + taskId + " done";
});
}
System.out.println("All submitted: " + Instant.now());
} // Blocks here until all complete
System.out.println("All complete: " + Instant.now());
// Output shows ~1 second gap (assuming enough CPU cores)
```
**Carrier Thread Pool:**
```java
// Virtual threads run on carrier threads
// Default carrier pool size = number of CPU cores
// With 8 cores:
// - 8 platform (carrier) threads created
// - 100,000 virtual threads scheduled on these 8 carriers
// - When a virtual thread blocks (sleep, I/O), it's unmounted
// - Another virtual thread can use that carrier thread
```
**Contrast with Manual Shutdown:**
```java
// Manual approach - doesn't wait:
var executor = Executors.newVirtualThreadPerTaskExecutor();
for (int i = 0; i < 100000; i++) {
executor.submit(() -> {...});
}
executor.shutdown(); // Stops accepting new tasks
// Program continues immediately - tasks run in background!
// Must explicitly wait:
executor.awaitTermination(1, TimeUnit.HOURS);
```
**Key Points:**
1. Try-with-resources on ExecutorService waits for completion
2. Virtual threads enable massive concurrency (millions possible)
3. Virtual threads are scheduled on small pool of carrier threads
4. Blocking operations don't block carrier threads
5. Perfect for I/O-bound workloads
See more: Concurrency
Question 4
MEDIUM
Given:
SequencedMap<String, Integer> map = new LinkedHashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
var reversed = map.reversed();
reversed.put("D", 4);
System.out.println(map);
System.out.println(reversed);
What is printed?
This demonstrates the **SequencedMap** interface and its `reversed()` method, introduced in Java 21 as part of the Sequenced Collections feature.
**SequencedMap Key Concepts:**
SequencedMap is a Map that maintains a defined encounter order with first and last elements. It provides:
- `reversed()` - Returns a reverse-ordered **view**
- `firstEntry()` / `lastEntry()` - Access entries at both ends
- `pollFirstEntry()` / `pollLastEntry()` - Remove and return entries
- `putFirst(K, V)` / `putLast(K, V)` - Add entries at specific positions
**Critical Understanding: reversed() Returns a VIEW**
The reversed map is NOT a copy - it's a live view of the original map with reversed iteration order.
**Step-by-Step Execution:**
1. **Initial map creation:**
```
map = {A=1, B=2, C=3}
```
2. **Create reversed view:**
```
reversed = map.reversed()
// reversed is a VIEW that iterates in reverse order
// Same underlying data as map
```
3. **Put through reversed view:**
```
reversed.put("D", 4)
// Adds to the BEGINNING of reversed view
// Which is the END of the original map
```
4. **Result:**
```
map = {A=1, B=2, C=3, D=4} // D added at end
reversed = {D=4, C=3, B=2, A=1} // Same data, reverse order
```
**View Behavior in Detail:**
```java
SequencedMap<String, Integer> map = new LinkedHashMap<>();
map.put("A", 1);
map.put("B", 2);
var rev = map.reversed();
// They share the same data:
map.put("C", 3);
System.out.println(rev); // {C=3, B=2, A=1} - sees the change!
rev.put("D", 4);
System.out.println(map); // {A=1, B=2, C=3, D=4} - sees the change!
// Removing from one affects the other:
rev.remove("A"); // Removes from both
System.out.println(map); // {B=2, C=3, D=4}
// Double reverse returns original:
var original = rev.reversed();
assert original == map; // true - same object!
```
**putFirst() and putLast():**
```java
// LinkedHashMap supports putFirst and putLast:
map.putFirst("X", 99); // Add at beginning
map.putLast("Z", 100); // Add at end
// Same as:
reversed.putLast("X", 99); // Last in reversed = first in original
reversed.putFirst("Z", 100); // First in reversed = last in original
```
**Iteration Order:**
```java
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// Original order:
for (var entry : map.entrySet()) {
System.out.print(entry.getKey()); // ABC
}
// Reversed order:
for (var entry : map.reversed().entrySet()) {
System.out.print(entry.getKey()); // CBA
}
```
**SequencedMap Hierarchy:**
```
SequencedMap
SortedMap
TreeMap (sorted by keys)
LinkedHashMap (insertion order)
```
**Operations on Reversed View:**
```java
var rev = map.reversed();
// All mutations affect both:
rev.put("X", 10); // Adds to both
rev.remove("A"); // Removes from both
rev.clear(); // Clears both
rev.putFirst("Y", 20); // Affects both
// Queries work on same data:
rev.size(); // Same as map.size()
rev.containsKey("A"); // Same as map.containsKey("A")
rev.get("A"); // Same as map.get("A")
```
**Performance:**
- Creating reversed view: O(1) - just creates wrapper
- Iterating reversed view: O(n) - same as original
- Put/remove through view: O(1) for LinkedHashMap, O(log n) for TreeMap
- No extra memory needed - shares data structure
**Important Notes:**
1. reversed() returns a view, not a copy
2. Changes through either map affect both
3. Iteration order is reversed, but it's the same data
4. putFirst() on reversed view = putLast() on original
5. Double reversing returns the original: `map.reversed().reversed() == map`
See more: Collections
Question 5
MEDIUM
Given:
record Box<T>(T value) {}
Box<String> box = new Box<>("Hello");
if (box instanceof Box(String s)) {
System.out.println(s.toUpperCase());
}
What happens?
This question reveals an important limitation when combining **record patterns** with **generic types** in Java 21.
**Why This Fails:**
**Type Erasure Problem:**
Generic types are erased at runtime. The JVM cannot verify the component type `String` in the pattern `Box(String s)` because at runtime, `Box<String>` becomes just `Box`.
**Compilation Error:**
```
error: record pattern with generic record is not supported
if (box instanceof Box(String s)) {
^
```
**The Core Issue:**
```java
// At compile time:
Box<String> stringBox = new Box<>("Hello");
Box<Integer> intBox = new Box<>(42);
// At runtime (after type erasure):
Box stringBox = new Box("Hello"); // Type parameter erased
Box intBox = new Box(42); // Type parameter erased
// The pattern Box(String s) cannot be verified:
// How does the JVM know if the Box contains String or Integer?
// The generic type information is gone!
```
**Workarounds:**
**Solution 1: Use Type Pattern with Manual Extraction**
```java
if (box instanceof Box<?> b) { // Raw type pattern works
Object value = b.value();
if (value instanceof String s) {
System.out.println(s.toUpperCase()); // HELLO
}
}
```
**Solution 2: Guard with Runtime Check**
```java
if (box instanceof Box<?> b && b.value() instanceof String) {
@SuppressWarnings("unchecked")
Box<String> stringBox = (Box<String>) b;
System.out.println(stringBox.value().toUpperCase());
}
```
**Solution 3: Use Non-Generic Record**
```java
// Define specific record types:
record StringBox(String value) {}
record IntBox(Integer value) {}
StringBox box = new StringBox("Hello");
if (box instanceof StringBox(String s)) { // Works!
System.out.println(s.toUpperCase()); // HELLO
}
```
**Solution 4: Sealed Hierarchy with Specific Types**
```java
sealed interface Box<T> permits StringBox, IntBox {}
record StringBox(String value) implements Box<String> {}
record IntBox(Integer value) implements Box<Integer> {}
Box<?> box = new StringBox("Hello");
String result = switch (box) {
case StringBox(String s) -> s.toUpperCase(); // Works!
case IntBox(Integer i) -> i.toString();
};
System.out.println(result); // HELLO
```
**Why Non-Generic Records Work:**
```java
// Non-generic record - type is known at runtime:
record Point(int x, int y) {}
Point p = new Point(3, 4);
if (p instanceof Point(int a, int b)) { // Works perfectly!
System.out.println(a + b); // 7
}
// The types 'int' are preserved at runtime
```
**Detailed Type Erasure Example:**
```java
// These are all the same at runtime:
Box<String> box1 = new Box<>("Hello");
Box<Integer> box2 = new Box<>(42);
Box<List<String>> box3 = new Box<>(List.of("A", "B"));
// After erasure:
Box box1 = new Box("Hello");
Box box2 = new Box(42);
Box box3 = new Box(List.of("A", "B"));
// This is why patterns can't work:
if (box1 instanceof Box(String s)) { // Can't verify String at runtime!
// ...
}
```
**Pattern Matching Rules for Generics:**
**Works:**
```java
// Raw type pattern:
if (box instanceof Box<?> b) { ... }
if (box instanceof Box b) { ... }
// Wildcard pattern:
if (box instanceof Box<?>) { ... }
```
**Doesn't Work:**
```java
// Specific generic type:
if (box instanceof Box<String>) { ... }
// Generic record pattern:
if (box instanceof Box(String s)) { ... }
if (box instanceof Box<String>(String s)) { ... }
```
**Comparison Table:**
| Pattern Type | Runtime Checkable | Pattern Matching Support |
|-------------|-------------------|-------------------------|
| `Box<?> b` | Yes | Yes |
| `Box<String> b` | No (erased) | No |
| `Box(var v)` | Yes | Yes |
| `Box(String s)` | No (generic) | No |
| `StringBox(String s)` | Yes | Yes |
**Best Practice:**
When you need pattern matching with type-specific behavior:
1. Use sealed hierarchies with specific record types
2. Avoid generic records in pattern matching contexts
3. Use type patterns followed by manual extraction
4. Consider using guards to check component types
**The Fundamental Problem:**
Java's type erasure means generic type parameters only exist at compile time. Pattern matching requires runtime type information, creating an incompatibility between generic records and record patterns.
See more: Java 21 New Features
Question 6
MEDIUM
Given:
Stream<String> stream = Stream.of("a", "b", "c");
List<String> list1 = stream.toList();
List<String> list2 = stream.collect(Collectors.toList());
What happens?
This demonstrates the fundamental rule that **streams can only be consumed once** and highlights the difference between `toList()` and `collect(Collectors.toList())` in Java 21.
**Stream Consumption Rules:**
A stream can only have **one terminal operation** executed on it. After a terminal operation completes, the stream is closed and cannot be reused.
**Execution Flow:**
1. **Stream creation:**
```java
Stream<String> stream = Stream.of("a", "b", "c");
// Stream is in OPEN state
```
2. **First terminal operation:**
```java
List<String> list1 = stream.toList();
// toList() is a terminal operation
// Returns: [a, b, c] (unmodifiable list)
// Stream is now CLOSED
```
3. **Second terminal operation:**
```java
List<String> list2 = stream.collect(Collectors.toList());
// Attempts to operate on CLOSED stream
// Throws: IllegalStateException: stream has already been operated upon or closed
```
**Why Streams Can't Be Reused:**
**Design Rationale:**
```java
// Streams are designed for single-pass processing:
Stream<String> stream = Files.lines(Paths.get("huge-file.txt"));
long count = stream.count(); // Processes entire file
// If we could reuse:
stream.forEach(System.out::println); // Would need to re-read entire file!
// This defeats the purpose of lazy evaluation and streaming
```
**State Tracking:**
```java
// Internally, stream tracks its state:
Stream<String> stream = Stream.of("a", "b", "c");
// Internal state: OPEN
stream.toList();
// Internal state: CLOSED
stream.count(); // Checks state, finds CLOSED, throws exception
```
**Correct Approaches:**
**Solution 1: Store Result and Reuse**
```java
Stream<String> stream = Stream.of("a", "b", "c");
List<String> list = stream.toList();
// Reuse the list, not the stream:
System.out.println(list);
List<String> copy = new ArrayList<>(list);
long count = list.size();
```
**Solution 2: Create Multiple Streams from Source**
```java
List<String> source = List.of("a", "b", "c");
// Create new stream each time:
List<String> list1 = source.stream().toList();
List<String> list2 = source.stream().collect(Collectors.toList());
long count = source.stream().count();
// Each operation gets fresh stream
```
**Solution 3: Use Supplier for Lazy Stream Creation**
```java
Supplier<Stream<String>> streamSupplier =
() -> Stream.of("a", "b", "c");
List<String> list1 = streamSupplier.get().toList();
List<String> list2 = streamSupplier.get().collect(Collectors.toList());
long count = streamSupplier.get().count();
// Each get() creates new stream
```
**toList() vs collect(Collectors.toList()) in Java 21:**
**toList() (Java 16+):**
```java
List<String> list = stream.toList();
// Returns: UNMODIFIABLE list
// Simpler, more concise
// Optimized implementation
// Cannot add/remove elements
list.add("d"); // UnsupportedOperationException
```
**collect(Collectors.toList()):**
```java
List<String> list = stream.collect(Collectors.toList());
// Returns: MUTABLE list (typically ArrayList)
// More verbose
// Allows modifications
list.add("d"); // OK - list is mutable
```
**Comparison Table:**
| Feature | toList() | collect(Collectors.toList()) |
|---------|----------|-----------------------------|
| Introduced | Java 16 | Java 8 |
| Mutability | Unmodifiable | Mutable |
| Nulls | Throws NPE | Allows nulls |
| Performance | Slightly better | Standard |
| Verbosity | Concise | Verbose |
| Implementation | Optimized | ArrayList |
**Terminal vs Intermediate Operations:**
**Terminal (closes stream):**
```java
stream.toList(); // Closes stream
stream.collect(...); // Closes stream
stream.forEach(...); // Closes stream
stream.count(); // Closes stream
stream.reduce(...); // Closes stream
stream.findFirst(); // Closes stream
stream.anyMatch(...); // Closes stream
```
**Intermediate (returns new stream):**
```java
stream.filter(...); // Returns new stream
stream.map(...); // Returns new stream
stream.sorted(); // Returns new stream
stream.distinct(); // Returns new stream
stream.limit(10); // Returns new stream
// Chain these - they're lazy!
```
**Complete Example:**
```java
// WRONG - stream reuse:
Stream<String> stream = Stream.of("a", "b", "c");
stream.forEach(System.out::println); // OK
stream.count(); // IllegalStateException
// RIGHT - single use:
Stream<String> stream = Stream.of("a", "b", "c");
long count = stream
.filter(s -> s.length() > 0)
.map(String::toUpperCase)
.peek(System.out::println)
.count(); // Only ONE terminal operation
// RIGHT - multiple streams from source:
List<String> source = List.of("a", "b", "c");
source.stream().forEach(System.out::println);
source.stream().count();
source.stream().toList();
```
**Key Takeaways:**
1. Streams are **single-use** - one terminal operation only
2. After terminal operation, stream is closed
3. Attempting to reuse throws `IllegalStateException`
4. Create new streams from the source for multiple operations
5. toList() returns unmodifiable list (Java 16+)
6. collect(Collectors.toList()) returns mutable list
See more: Streams & Lambdas
Question 7
MEDIUM
Given:
var text = """
Line 1\
Line 2
""";
System.out.println(text);
What is printed?
This demonstrates **line continuation** in text blocks using the backslash (\) escape sequence.
**How Line Continuation Works:**
The backslash at the end of a line (\) suppresses the newline character, joining the current line with the next line without any space.
**Processing Steps:**
1. Text block starts with "Line 1\\"
2. The trailing \\ indicates line continuation
3. The newline after "Line 1" is suppressed
4. "Line 2" is joined directly: "Line 1Line 2"
5. Result: "Line 1Line 2" (single line, no newline)
**Common Use Cases:**
```java
// Long SQL query as single line:
String sql = """
SELECT id, name, email \
FROM users \
WHERE status = 'ACTIVE'
""";
// Result: "SELECT id, name, email FROM users WHERE status = 'ACTIVE'"
// Long text message:
String msg = """
This is a very long message \
that should be on one line.
""";
// Result: "This is a very long message that should be on one line."
```
**Important Rules:**
1. Backslash must be the LAST character on the line
2. Any whitespace after \\ causes compilation error
3. No space is added when joining lines
4. To add space, include it before \\: "Line 1 \\"
See more: Data Types & Variables
Question 8
MEDIUM
Given:
Integer value = 5;
String result = switch (value) {
case null -> "Null";
case 1, 2, 3 -> "Low";
case 4, 5, 6 -> "Medium";
case 7, 8, 9 -> "High";
default -> "Other";
};
System.out.println(result);
What is printed?
This demonstrates **switch expressions** with **multiple case labels** and **null handling** in Java 21.
**Execution Flow:**
1. value = 5 (not null)
2. Check case null -> doesn't match
3. Check case 1, 2, 3 -> 5 not in {1, 2, 3}
4. Check case 4, 5, 6 -> **5 matches!**
5. Returns "Medium"
6. Output: "Medium"
**Key Features Demonstrated:**
**Multiple Case Labels:**
```java
case 1, 2, 3 -> "Low"; // Matches any of 1, 2, or 3
// Equivalent to:
case 1:
case 2:
case 3:
return "Low";
```
**Null Case (Java 21):**
```java
case null -> "Null"; // Explicitly handles null
// Prevents NullPointerException
```
**Switch Expression Benefits:**
1. Returns a value (can assign to variable)
2. No fall-through between cases
3. Exhaustiveness checking by compiler
4. More concise than traditional switch
**Comparison:**
```java
// Old style (statement):
String result;
switch (value) {
case 1: case 2: case 3:
result = "Low";
break;
case 4: case 5: case 6:
result = "Medium";
break;
default:
result = "Other";
}
// New style (expression):
String result = switch (value) {
case 1, 2, 3 -> "Low";
case 4, 5, 6 -> "Medium";
default -> "Other";
};
```
See more: Control Flow
Question 9
MEDIUM
Given:
Thread t1 = Thread.ofVirtual().unstarted(() -> {
System.out.println("Task");
});
System.out.println(t1.isVirtual());
t1.start();
t1.join();
What is printed?
This demonstrates creating virtual threads using the **builder pattern** with `unstarted()` method.
**Thread.ofVirtual() Builder Pattern:**
`Thread.ofVirtual()` returns a builder that allows configuration before starting:
```java
Thread.Builder builder = Thread.ofVirtual();
// Two ways to create threads:
// 1. unstarted() - creates thread but doesn't start it
Thread t = builder.unstarted(() -> {...});
// 2. start() - creates and starts immediately
Thread t = builder.start(() -> {...});
```
**Execution Breakdown:**
1. **Create unstarted virtual thread:**
```java
Thread t1 = Thread.ofVirtual().unstarted(() -> {...});
// Thread created but NOT started
// State: NEW
```
2. **Check if virtual:**
```java
System.out.println(t1.isVirtual()); // true
// Even unstarted threads know they're virtual
```
3. **Start the thread:**
```java
t1.start();
// Thread begins execution
// Prints "Task"
```
4. **Wait for completion:**
```java
t1.join();
// Main thread waits until t1 completes
```
**Output:** "true" then "Task"
**Builder Configuration Options:**
```java
Thread t = Thread.ofVirtual()
.name("my-virtual-thread")
.uncaughtExceptionHandler((thread, ex) ->
System.err.println("Error: " + ex))
.unstarted(() -> {
// task code
});
// Check properties:
t.isVirtual(); // true
t.getName(); // "my-virtual-thread"
t.getState(); // NEW (before start())
t.start(); // Begin execution
t.getState(); // RUNNABLE (after start())
```
**Comparison: unstarted() vs start():**
```java
// unstarted() - manual control:
Thread t1 = Thread.ofVirtual().unstarted(() -> {...});
// ... do other setup ...
t1.start(); // Start when ready
// start() - immediate execution:
Thread t2 = Thread.ofVirtual().start(() -> {...});
// Already running!
// startVirtualThread() - convenience method:
Thread t3 = Thread.startVirtualThread(() -> {...});
// Equivalent to: Thread.ofVirtual().start(...)
```
**Thread States:**
```java
Thread t = Thread.ofVirtual().unstarted(() -> {...});
t.getState(); // NEW
t.start();
t.getState(); // RUNNABLE
// After task completes:
t.getState(); // TERMINATED
```
See more: Concurrency
Question 10
MEDIUM
Given:
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
String first = list.removeFirst();
String last = list.removeLast();
System.out.println(list + " " + first + " " + last);
What is printed?
This demonstrates the **removeFirst()** and **removeLast()** methods from the SequencedCollection interface in Java 21.
**Step-by-Step Execution:**
1. **Initial state:**
```java
list = [A, B, C]
```
2. **Remove first element:**
```java
String first = list.removeFirst();
// Removes "A" from index 0
// first = "A"
// list = [B, C]
```
3. **Remove last element:**
```java
String last = list.removeLast();
// Removes "C" from end
// last = "C"
// list = [B]
```
4. **Print result:**
```java
System.out.println(list + " " + first + " " + last);
// [B] A C
```
**SequencedCollection Methods:**
Java 21 added these methods to the Collection hierarchy:
```java
// Access without removal:
E getFirst(); // Returns first element
E getLast(); // Returns last element
// Remove and return:
E removeFirst(); // Removes and returns first
E removeLast(); // Removes and returns last
// Add at specific positions:
void addFirst(E); // Add at beginning
void addLast(E); // Add at end
// Get reversed view:
SequencedCollection<E> reversed();
```
**Exception Behavior:**
```java
List<String> empty = new ArrayList<>();
// These throw NoSuchElementException on empty collection:
empty.getFirst(); // NoSuchElementException
empty.getLast(); // NoSuchElementException
empty.removeFirst(); // NoSuchElementException
empty.removeLast(); // NoSuchElementException
// Compare to traditional methods:
empty.get(0); // IndexOutOfBoundsException
empty.remove(0); // IndexOutOfBoundsException
```
**Performance Characteristics:**
**ArrayList:**
```java
list.removeFirst(); // O(n) - shifts all elements
list.removeLast(); // O(1) - just decrements size
list.getFirst(); // O(1) - access index 0
list.getLast(); // O(1) - access last index
```
**LinkedList:**
```java
list.removeFirst(); // O(1) - update head reference
list.removeLast(); // O(1) - update tail reference
list.getFirst(); // O(1) - return head
list.getLast(); // O(1) - return tail
```
**Complete Example:**
```java
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
// [1, 2, 3]
numbers.addFirst(0); // [0, 1, 2, 3]
numbers.addLast(4); // [0, 1, 2, 3, 4]
int first = numbers.removeFirst(); // 0, list = [1, 2, 3, 4]
int last = numbers.removeLast(); // 4, list = [1, 2, 3]
int head = numbers.getFirst(); // 1, list unchanged
int tail = numbers.getLast(); // 3, list unchanged
```
See more: Collections
Question 11
MEDIUM
Given:
sealed class Parent permits Child {}
final class Child extends Parent {}
class GrandChild extends Child {}
What happens?
This tests understanding of **sealed class hierarchies** and the interaction between sealed and final modifiers in Java 21.
**Why This Fails:**
The `final` modifier on Child prevents ANY class from extending it, including GrandChild.
**Sealed Class Rules:**
When extending a sealed class, the subclass MUST be one of:
1. **final** - No further subclassing allowed
2. **sealed** - Further subclassing controlled
3. **non-sealed** - Open hierarchy (anyone can extend)
**This Example:**
```java
sealed class Parent permits Child {} // Parent is sealed
final class Child extends Parent {} // Child is final - hierarchy ENDS here
class GrandChild extends Child {} // ERROR! Cannot extend final class
```
**Compilation Error:**
```
error: cannot inherit from final Child
class GrandChild extends Child {}
^
```
**Correct Approaches:**
**Option 1: Make Child non-sealed**
```java
sealed class Parent permits Child {}
non-sealed class Child extends Parent {} // Open for extension
class GrandChild extends Child {} // OK!
class GreatGrandChild extends GrandChild {} // OK!
// Anyone can extend Child or its subclasses
```
**Option 2: Make Child sealed with permits**
```java
sealed class Parent permits Child {}
sealed class Child extends Parent permits GrandChild {} // Control continues
final class GrandChild extends Child {} // End of hierarchy
```
**Option 3: Keep Child final (no GrandChild)**
```java
sealed class Parent permits Child {}
final class Child extends Parent {} // Hierarchy ends here
// No GrandChild possible
```
**Complete Sealed Hierarchy Example:**
```java
// Three-level controlled hierarchy:
sealed class Animal permits Mammal, Bird {}
sealed class Mammal extends Animal permits Dog, Cat {}
final class Dog extends Mammal {}
final class Cat extends Mammal {}
non-sealed class Bird extends Animal {} // Open for extension
class Sparrow extends Bird {} // Anyone can extend Bird
class Eagle extends Bird {} // OK
```
**Sealed Class Decision Tree:**
```
Extending a sealed class?
Want to END the hierarchy here?
Use: final class
Want to CONTROL further subclassing?
Use: sealed class permits ...
Want to OPEN the hierarchy?
Use: non-sealed class
```
**Visual Hierarchy:**
```
Parent (sealed, permits Child)
Child (final) <- Hierarchy ends
GrandChild <- Cannot extend final class
Vs.
Parent (sealed, permits Child)
Child (non-sealed) <- Hierarchy opens
GrandChild
GreatGrandChild
```
**Why Sealed Classes Matter:**
1. **Exhaustive Pattern Matching:**
```java
sealed class Shape permits Circle, Rectangle {}
final class Circle extends Shape {}
final class Rectangle extends Shape {}
// Compiler knows ALL possible subtypes:
double area = switch (shape) {
case Circle c -> Math.PI * c.radius * c.radius;
case Rectangle r -> r.width * r.height;
// No default needed - exhaustive!
};
```
2. **Domain Modeling:**
```java
sealed interface Result permits Success, Failure {}
record Success(String data) implements Result {}
record Failure(String error) implements Result {}
// Only Success or Failure - no surprises!
```
See more: OOP & Classes
Question 12
MEDIUM
Given:
record Person(String name, int age) {}
Person p = new Person("Alice", 30);
if (p instanceof Person(var n, var a)) {
System.out.println(n + " is " + a);
}
What is printed?
This demonstrates using **var for type inference** in **record patterns**, a convenient feature in Java 21.
**How var Works in Record Patterns:**
The `var` keyword can be used in record patterns to let the compiler infer the types of pattern variables from the record components.
**Execution:**
1. **Pattern matching:**
```java
if (p instanceof Person(var n, var a)) {
```
- Checks if p is a Person (it is)
- Extracts components using var
- Compiler infers: n is String, a is int
2. **Type inference:**
```java
var n // Inferred as String (from Person.name)
var a // Inferred as int (from Person.age)
```
3. **Print:**
```java
System.out.println(n + " is " + a);
// "Alice is 30"
```
**Comparison of Syntax Options:**
**Option 1: Explicit types**
```java
if (p instanceof Person(String n, int a)) {
System.out.println(n + " is " + a);
}
// Clear but verbose
```
**Option 2: var inference**
```java
if (p instanceof Person(var n, var a)) {
System.out.println(n + " is " + a);
}
// Concise and still type-safe
```
**Option 3: Mixed**
```java
if (p instanceof Person(String n, var a)) {
System.out.println(n + " is " + a);
}
// Can mix explicit and var
```
**var Benefits:**
1. **Less verbose:**
```java
record Point3D(double x, double y, double z) {}
// With explicit types:
if (obj instanceof Point3D(double x, double y, double z)) {...}
// With var:
if (obj instanceof Point3D(var x, var y, var z)) {...}
```
2. **Easier refactoring:**
```java
// If you change Person record:
record Person(String firstName, int age) {} // Changed name -> firstName
// With var, this still works:
if (p instanceof Person(var n, var a)) {...}
// With explicit type, would need update:
if (p instanceof Person(String n, int a)) {...}
```
**When to Use Each:**
**Use explicit types when:**
- Types aren't obvious from context
- You want to document the types
- Reviewing code later requires clarity
**Use var when:**
- Types are obvious from record definition
- You want concise code
- You're working with complex generic types
**Switch Expression Example:**
```java
String description = switch (p) {
case Person(var name, var age) when age < 18 ->
name + " is a minor";
case Person(var name, var age) when age >= 65 ->
name + " is a senior";
case Person(var name, var age) ->
name + " is " + age + " years old";
};
```
**Nested Patterns with var:**
```java
record Address(String city, String country) {}
record Employee(String name, Address address) {}
Employee emp = new Employee("Bob", new Address("NYC", "USA"));
if (emp instanceof Employee(var name, Address(var city, var country))) {
System.out.println(name + " lives in " + city + ", " + country);
// Bob lives in NYC, USA
}
```
**Complex Type Inference:**
```java
record Container<T>(T value) {}
Container<List<String>> container = new Container<>(List.of("A", "B"));
// var infers the complex type:
if (container instanceof Container(var value)) {
// value is inferred as List<String>
value.forEach(System.out::println);
}
```
See more: Java 21 New Features
Question 13
MEDIUM
Given:
Path path = Path.of("test.txt");
Files.writeString(path, "Hello", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Files.writeString(path, " World", StandardOpenOption.APPEND);
String content = Files.readString(path);
System.out.println(content);
What is printed (assuming test.txt doesn't exist initially)?
This demonstrates **Files.writeString()** with **StandardOpenOption** parameters, showing how file I/O options work in Java 21.
**StandardOpenOption.CREATE:**
- Creates the file if it doesn't exist
- If file exists, content depends on other options
**StandardOpenOption.APPEND:**
- Appends to end of file instead of truncating
- If file doesn't exist and CREATE is specified, creates then appends
**Execution Flow:**
1. **First write:**
```java
Files.writeString(path, "Hello", CREATE, APPEND);
// File doesn't exist
// CREATE: creates test.txt
// APPEND: writes "Hello" to empty file
// File content: "Hello"
```
2. **Second write:**
```java
Files.writeString(path, " World", APPEND);
// File exists with "Hello"
// APPEND: adds " World" to end
// File content: "Hello World"
```
3. **Read and print:**
```java
String content = Files.readString(path);
System.out.println(content);
// Output: "Hello World"
```
**StandardOpenOption Values:**
```java
// Common options:
CREATE // Create if doesn't exist
CREATE_NEW // Create only if doesn't exist (fails if exists)
APPEND // Append to end
TRUNCATE_EXISTING // Clear existing content (default for writing)
WRITE // Open for writing
READ // Open for reading
```
**Behavior Comparison:**
```java
// Scenario 1: Truncate (default)
Files.writeString(path, "Hello"); // File: "Hello"
Files.writeString(path, "World"); // File: "World" (replaces)
// Scenario 2: Append
Files.writeString(path, "Hello", APPEND); // File: "Hello"
Files.writeString(path, "World", APPEND); // File: "HelloWorld"
// Scenario 3: CREATE_NEW
Files.writeString(path, "Hello", CREATE_NEW); // Creates, writes "Hello"
Files.writeString(path, "Hi", CREATE_NEW); // FileAlreadyExistsException!
```
See more: Java I/O API
Question 14
MEDIUM
Given:
String sql = "SELECT * FROM users WHERE id = ? AND status = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 100);
ps.setString(2, "ACTIVE");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println(rs.getString("name"));
}
}
What happens if the users table has no column named "name"?
Accessing a non-existent column in ResultSet throws **SQLException** at runtime.
**ResultSet Column Access:**
You can access columns by:
1. Column name: `rs.getString("columnName")`
2. Column index: `rs.getString(1)` (1-based)
**What Happens:**
```java
ResultSet rs = ps.executeQuery();
// Executes query successfully
// ResultSet contains rows from users table
rs.next(); // Move to first row - returns true if exists
rs.getString("name"); // Column "name" doesn't exist
// Throws: SQLException: Column 'name' not found
```
**Safe Approaches:**
**Option 1: Use correct column name**
```java
if (rs.next()) {
String username = rs.getString("username"); // Actual column
}
```
**Option 2: Use column index**
```java
if (rs.next()) {
String value = rs.getString(1); // First column
}
```
**Option 3: Check metadata**
```java
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = meta.getColumnName(i);
System.out.println(columnName);
}
```
**Option 4: Handle exception**
```java
try {
String name = rs.getString("name");
} catch (SQLException e) {
System.out.println("Column not found, using default");
String name = "Unknown";
}
```
See more: JDBC
Question 15
MEDIUM
Given:
Locale locale = Locale.of("de", "DE");
NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
System.out.println(nf.format(1234.56));
What is the expected output format?
German locale (de_DE) uses specific formatting conventions for currency.
**German Currency Format:**
- Currency symbol: € (Euro)
- Thousands separator: . (period)
- Decimal separator: , (comma)
- Symbol position: After amount with space
**Formatting Details:**
```java
Double amount = 1234.56;
// German (DE):
NumberFormat de = NumberFormat.getCurrencyInstance(Locale.GERMANY);
de.format(amount); // "1.234,56 €"
// US:
NumberFormat us = NumberFormat.getCurrencyInstance(Locale.US);
us.format(amount); // "$1,234.56"
// France:
NumberFormat fr = NumberFormat.getCurrencyInstance(Locale.FRANCE);
fr.format(amount); // "1 234,56 €"
// UK:
NumberFormat uk = NumberFormat.getCurrencyInstance(Locale.UK);
uk.format(amount); // "£1,234.56"
```
**Key Differences by Locale:**
| Locale | Format | Thousands | Decimal | Symbol Position |
|--------|---------|-----------|---------|----------------|
| de_DE | 1.234,56 € | . | , | After |
| en_US | $1,234.56 | , | . | Before |
| fr_FR | 1 234,56 € | space | , | After |
| en_GB | £1,234.56 | , | . | Before |
See more: Localization
Question 16
MEDIUM
Given:
class Resource1 implements AutoCloseable {
public void close() { System.out.print("R1 "); }
}
class Resource2 implements AutoCloseable {
public void close() { System.out.print("R2 "); }
}
try (Resource1 r1 = new Resource1(); Resource2 r2 = new Resource2()) {
System.out.print("Try ");
}
What is printed?
Try-with-resources closes resources in **reverse order** of declaration.
**Execution Order:**
1. **Resources created in order:**
- r1 = new Resource1()
- r2 = new Resource2()
2. **Try block executes:**
- Prints "Try "
3. **Resources closed in REVERSE order:**
- r2.close() -> prints "R2 "
- r1.close() -> prints "R1 "
**Complete output:** "Try R2 R1"
**Why Reverse Order?**
Resources often depend on each other. Later resources may depend on earlier ones:
```java
try (FileInputStream fis = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(fis)) {
// bis depends on fis
// Must close bis BEFORE fis
}
// Close order: bis.close(), then fis.close()
```
**Multiple Resources Example:**
```java
try (R1 r1 = new R1(); // Created 1st, closed 4th
R2 r2 = new R2(); // Created 2nd, closed 3rd
R3 r3 = new R3(); // Created 3rd, closed 2nd
R4 r4 = new R4()) { // Created 4th, closed 1st
// Use resources
}
// Close order: r4, r3, r2, r1 (reverse)
```
See more: Exception Handling
Question 17
MEDIUM
Given a module-info.java:
module com.app {
requires java.sql;
requires transitive java.logging;
exports com.app.api;
}
Another module declares: requires com.app;
Which modules are readable by the other module?
**requires transitive** creates **implied readability** - modules requiring com.app also implicitly require java.logging.
**Module Dependency Types:**
**requires (normal):**
```java
requires java.sql;
// Only com.app can read java.sql
// Other modules requiring com.app CANNOT read java.sql
```
**requires transitive:**
```java
requires transitive java.logging;
// com.app can read java.logging
// Any module requiring com.app ALSO reads java.logging (transitive)
```
**Scenario Analysis:**
```java
// Module: com.app
module com.app {
requires java.sql; // Normal dependency
requires transitive java.logging; // Transitive dependency
exports com.app.api;
}
// Module: other.module
module other.module {
requires com.app;
// Implicitly requires java.logging (transitive)
// Does NOT implicitly require java.sql
}
```
**What other.module can access:**
1. ✅ com.app - explicitly required
2. ✅ java.logging - transitive from com.app
3. ❌ java.sql - not transitive, not accessible
**When to Use requires transitive:**
Use when your exported API **exposes types** from the dependency:
```java
// com.app exports API using Logger:
package com.app.api;
import java.util.logging.Logger;
public class Service {
public Logger getLogger() { // Returns Logger from java.logging
return Logger.getLogger("app");
}
}
// If com.app uses:
requires transitive java.logging;
// Then clients of com.app can use Logger without requiring java.logging
// If com.app uses:
requires java.logging; // Not transitive
// Clients get compilation error when using getLogger()
```
See more: Modules & Packaging
Question 18
MEDIUM
Given:
Optional<String> opt = Optional.ofNullable(null);
String result = opt.orElse("Default");
System.out.println(result);
What is printed?
Optional.ofNullable(null) creates an empty Optional.
orElse() returns the value if present, otherwise returns the default.
Since Optional is empty, returns "Default".
See more: Streams & Lambdas
Question 19
MEDIUM
Given:
var list = List.of(1, 2, 3);
var first = list.get(0);
System.out.println(first.getClass().getName());
What is printed?
List.of() creates List<Integer>. var infers the type from the right side.
list.get(0) returns Integer (not primitive int due to generics).
getClass().getName() returns "java.lang.Integer".
See more: Data Types & Variables
Question 20
MEDIUM
Given:
sealed interface Animal {}
record Dog(String name) implements Animal {}
What happens?
Sealed interfaces must use 'permits' clause to specify allowed implementations.
Without permits clause, no class can implement the sealed interface.
Correct:
sealed interface Animal permits Dog {}
record Dog(String name) implements Animal {}
See more: Java 21 New Features
Question 21
MEDIUM
Question testing Java I/O - NIO.2 and file operations
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Java I/O in Java 21.
Key concepts:
- NIO.2 and file operations
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Java I/O
Question 22
MEDIUM
Question testing JDBC - database connectivity
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of JDBC in Java 21.
Key concepts:
- database connectivity
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: JDBC
Question 23
MEDIUM
Question testing Localization - resource bundles and formatting
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Localization in Java 21.
Key concepts:
- resource bundles and formatting
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Localization
Question 24
MEDIUM
Question testing Java 21 Features - pattern matching and records
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Java 21 Features in Java 21.
Key concepts:
- pattern matching and records
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Java 21 Features
Question 25
MEDIUM
Question testing Data Types & Variables - String manipulation and date/time API
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Data Types & Variables in Java 21.
Key concepts:
- String manipulation and date/time API
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Data Types & Variables
Question 26
MEDIUM
Question testing Control Flow - switch expressions and loops
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Control Flow in Java 21.
Key concepts:
- switch expressions and loops
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Control Flow
Question 27
MEDIUM
Question testing OOP & Classes - inheritance and sealed classes
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of OOP & Classes in Java 21.
Key concepts:
- inheritance and sealed classes
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: OOP & Classes
Question 28
MEDIUM
Question testing Exception Handling - try-with-resources and custom exceptions
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Exception Handling in Java 21.
Key concepts:
- try-with-resources and custom exceptions
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Exception Handling
Question 29
MEDIUM
Question testing Collections - List, Set, Map operations
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Collections in Java 21.
Key concepts:
- List, Set, Map operations
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Collections
Question 30
MEDIUM
Question testing Streams & Lambdas - stream operations and functional interfaces
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Streams & Lambdas in Java 21.
Key concepts:
- stream operations and functional interfaces
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Streams & Lambdas
Question 31
MEDIUM
Question testing Modules & Packaging - module system and services
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Modules & Packaging in Java 21.
Key concepts:
- module system and services
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Modules & Packaging
Question 32
MEDIUM
Question testing Concurrency - virtual threads and synchronization
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Concurrency in Java 21.
Key concepts:
- virtual threads and synchronization
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Concurrency
Question 33
MEDIUM
Question testing Java I/O - NIO.2 and file operations
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Java I/O in Java 21.
Key concepts:
- NIO.2 and file operations
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Java I/O
Question 34
MEDIUM
Question testing JDBC - database connectivity
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of JDBC in Java 21.
Key concepts:
- database connectivity
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: JDBC
Question 35
MEDIUM
Question testing Localization - resource bundles and formatting
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Localization in Java 21.
Key concepts:
- resource bundles and formatting
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Localization
Question 36
MEDIUM
Question testing Java 21 Features - pattern matching and records
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Java 21 Features in Java 21.
Key concepts:
- pattern matching and records
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Java 21 Features
Question 37
MEDIUM
Question testing Data Types & Variables - String manipulation and date/time API
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Data Types & Variables in Java 21.
Key concepts:
- String manipulation and date/time API
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Data Types & Variables
Question 38
MEDIUM
Question testing Control Flow - switch expressions and loops
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Control Flow in Java 21.
Key concepts:
- switch expressions and loops
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Control Flow
Question 39
MEDIUM
Question testing OOP & Classes - inheritance and sealed classes
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of OOP & Classes in Java 21.
Key concepts:
- inheritance and sealed classes
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: OOP & Classes
Question 40
MEDIUM
Question testing Exception Handling - try-with-resources and custom exceptions
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Exception Handling in Java 21.
Key concepts:
- try-with-resources and custom exceptions
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Exception Handling
Question 41
MEDIUM
Question testing Collections - List, Set, Map operations
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Collections in Java 21.
Key concepts:
- List, Set, Map operations
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Collections
Question 42
MEDIUM
Question testing Streams & Lambdas - stream operations and functional interfaces
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Streams & Lambdas in Java 21.
Key concepts:
- stream operations and functional interfaces
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Streams & Lambdas
Question 43
MEDIUM
Question testing Modules & Packaging - module system and services
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Modules & Packaging in Java 21.
Key concepts:
- module system and services
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Modules & Packaging
Question 44
MEDIUM
Question testing Concurrency - virtual threads and synchronization
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Concurrency in Java 21.
Key concepts:
- virtual threads and synchronization
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Concurrency
Question 45
MEDIUM
Question testing Java I/O - NIO.2 and file operations
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Java I/O in Java 21.
Key concepts:
- NIO.2 and file operations
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Java I/O
Question 46
MEDIUM
Question testing JDBC - database connectivity
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of JDBC in Java 21.
Key concepts:
- database connectivity
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: JDBC
Question 47
MEDIUM
Question testing Localization - resource bundles and formatting
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Localization in Java 21.
Key concepts:
- resource bundles and formatting
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Localization
Question 48
MEDIUM
Question testing Java 21 Features - pattern matching and records
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Java 21 Features in Java 21.
Key concepts:
- pattern matching and records
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Java 21 Features
Question 49
MEDIUM
Question testing Data Types & Variables - String manipulation and date/time API
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Data Types & Variables in Java 21.
Key concepts:
- String manipulation and date/time API
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Data Types & Variables
Question 50
MEDIUM
Question testing Control Flow - switch expressions and loops
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Control Flow in Java 21.
Key concepts:
- switch expressions and loops
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Control Flow
Question 51
MEDIUM
Question testing OOP & Classes - inheritance and sealed classes
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of OOP & Classes in Java 21.
Key concepts:
- inheritance and sealed classes
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: OOP & Classes
Question 52
MEDIUM
Question testing Exception Handling - try-with-resources and custom exceptions
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Exception Handling in Java 21.
Key concepts:
- try-with-resources and custom exceptions
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Exception Handling
Question 53
MEDIUM
Question testing Collections - List, Set, Map operations
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Collections in Java 21.
Key concepts:
- List, Set, Map operations
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Collections
Question 54
MEDIUM
Question testing Streams & Lambdas - stream operations and functional interfaces
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Streams & Lambdas in Java 21.
Key concepts:
- stream operations and functional interfaces
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Streams & Lambdas
Question 55
MEDIUM
Question testing Modules & Packaging - module system and services
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Modules & Packaging in Java 21.
Key concepts:
- module system and services
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Modules & Packaging
Question 56
MEDIUM
Question testing Concurrency - virtual threads and synchronization
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Concurrency in Java 21.
Key concepts:
- virtual threads and synchronization
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Concurrency
Question 57
MEDIUM
Question testing Java I/O - NIO.2 and file operations
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Java I/O in Java 21.
Key concepts:
- NIO.2 and file operations
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Java I/O
Question 58
MEDIUM
Question testing JDBC - database connectivity
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of JDBC in Java 21.
Key concepts:
- database connectivity
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: JDBC
Question 59
MEDIUM
Question testing Localization - resource bundles and formatting
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Localization in Java 21.
Key concepts:
- resource bundles and formatting
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Localization
Question 60
MEDIUM
Question testing Java 21 Features - pattern matching and records
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Java 21 Features in Java 21.
Key concepts:
- pattern matching and records
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Java 21 Features
Question 61
MEDIUM
Question testing Data Types & Variables - String manipulation and date/time API
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Data Types & Variables in Java 21.
Key concepts:
- String manipulation and date/time API
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Data Types & Variables
Question 62
MEDIUM
Question testing Control Flow - switch expressions and loops
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Control Flow in Java 21.
Key concepts:
- switch expressions and loops
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Control Flow
Question 63
MEDIUM
Question testing OOP & Classes - inheritance and sealed classes
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of OOP & Classes in Java 21.
Key concepts:
- inheritance and sealed classes
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: OOP & Classes
Question 64
MEDIUM
Question testing Exception Handling - try-with-resources and custom exceptions
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Exception Handling in Java 21.
Key concepts:
- try-with-resources and custom exceptions
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Exception Handling
Question 65
MEDIUM
Question testing Collections - List, Set, Map operations
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Collections in Java 21.
Key concepts:
- List, Set, Map operations
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Collections
Question 66
MEDIUM
Question testing Streams & Lambdas - stream operations and functional interfaces
Given appropriate Java 21 code, what is the expected behavior?
This question tests understanding of Streams & Lambdas in Java 21.
Key concepts:
- stream operations and functional interfaces
- Proper usage of Java 21 features
- Best practices and common patterns
The code demonstrates typical scenarios encountered in the 1Z0-830 exam.
See: Streams & Lambdas
Popular Posts
1Z0-830 Java SE 21 Developer Certification
Azure AI Foundry Hello World
Azure AI Agent Hello World
Foundry vs Hub Projects
Build Agents with SDK
Bing Web Search Agent
Function Calling Agent
Spring Boot + Azure Key Vault Hello World Example
Spring Boot + Elasticsearch + Azure Key Vault Example
Spring Boot Azure AD (Entra ID) OAuth 2.0 Authentication
Deploy Spring Boot App to Azure App Service
Secure Azure App Service using Azure API Management
Deploy Spring Boot JAR to Azure App Service
Deploy Spring Boot + MySQL to Azure App Service
Spring Boot + Azure Managed Identity Example
Secure Spring Boot Azure Web App with Managed Identity + App Registration
Elasticsearch 8 Security - Integrate Azure AD OIDC