Oracle Certified Professional Java SE 17 Developer 1Z0-829 (1Z0-829) — Questions 151225

509 questions total · 7pages · All types, answers revealed

Page 2

Page 3 of 7

Page 4
151
MCQmedium

Given the following code snippet inside a method: try { // risky code } catch (IOException | SQLException e) { // handle } What is the implicit type of the exception variable 'e' in the catch block?

A.It is of type Object.
B.It is of type Exception.
C.It is of type Throwable.
D.It is either IOException or SQLException.
AnswerB

The common base of IOException and SQLException is Exception.

Why this answer

In Java, when a multi-catch clause catches multiple exception types (e.g., IOException | SQLException), the compiler infers the catch parameter's type as the closest common superclass that is not Object or Throwable. Since IOException and SQLException both extend Exception directly, the implicit type of 'e' is Exception. This allows the catch block to handle both exception types polymorphically.

Exam trap

The trap here is that candidates mistakenly think 'e' has a union type (like TypeScript) or that the compiler uses the first listed exception type, when in fact Java infers the most specific common superclass, which is Exception for IOException and SQLException.

How to eliminate wrong answers

Option A is wrong because the implicit type is not Object; the compiler selects the most specific common superclass, which is Exception, not Object. Option C is wrong because Throwable is too broad; the common superclass of IOException and SQLException is Exception, not Throwable. Option D is wrong because 'e' is not a union type; it is a single type (Exception) that can reference either IOException or SQLException at runtime, but its compile-time type is Exception.

152
MCQhard

Refer to the exhibit. Which Java code correctly performs the equivalent timezone conversion?

A.LocalDateTime.of(2024,3,10,2,30).atZone(ZoneOffset.UTC)
B.Instant.parse("2024-03-10T02:30:00Z")
C.OffsetDateTime.of(2024,3,10,2,30,0,0,ZoneOffset.UTC)
D.ZonedDateTime.of(2024,3,10,2,30,0,0,ZoneId.of("America/New_York")).withZoneSameInstant(ZoneOffset.UTC)
AnswerD

Correct: withZoneSameInstant converts to UTC while preserving the instant.

Why this answer

Option D is correct because it explicitly constructs a ZonedDateTime for the given date and time in the America/New_York timezone, then converts it to UTC using withZoneSameInstant. This correctly accounts for the fact that on March 10, 2024, at 2:30 AM, clocks in New York were set forward to 3:30 AM EDT (UTC-4), so the equivalent UTC time is 6:30 AM, not 2:30 AM UTC.

Exam trap

Oracle often tests the misconception that a simple UTC offset or LocalDateTime can be used to represent a time that falls within a DST gap, when in fact you must use ZonedDateTime with the correct ZoneId to trigger the proper offset adjustment.

How to eliminate wrong answers

Option A is wrong because LocalDateTime.of(2024,3,10,2,30).atZone(ZoneOffset.UTC) creates a LocalDateTime without timezone context and then attaches UTC offset, resulting in 2:30 AM UTC, which ignores the DST transition in America/New_York. Option B is wrong because Instant.parse("2024-03-10T02:30:00Z") directly parses a UTC instant of 2:30 AM, which does not represent the equivalent time in New York after the DST spring-forward. Option C is wrong because OffsetDateTime.of(2024,3,10,2,30,0,0,ZoneOffset.UTC) creates a date-time with a fixed UTC offset of +00:00, again yielding 2:30 AM UTC and failing to account for the DST shift.

153
MCQhard

A developer has a method that contains a try-catch-finally block inside a while loop. The try block throws a checked exception that is caught by the catch block. The catch block throws a new runtime exception. What is the behavior?

A.The loop continues after the finally block, and the runtime exception is thrown after the loop.
B.The loop terminates immediately, and the runtime exception propagates.
C.The loop continues after the catch block, and the runtime exception is not propagated.
D.The loop continues after the finally block, and the runtime exception is suppressed.
AnswerB

The runtime exception thrown in catch causes the loop to exit and the exception to propagate.

Why this answer

When a checked exception is caught and the catch block throws a new runtime exception, the finally block executes before the runtime exception propagates. Since the runtime exception is thrown from within the catch block (inside the while loop), it immediately terminates the loop and propagates up the call stack. Option B is correct because the loop does not continue; the runtime exception is thrown after the finally block completes.

Exam trap

The trap here is that candidates mistakenly think the finally block or the loop's condition allows the loop to continue, but the runtime exception thrown in the catch block immediately propagates, terminating the loop.

How to eliminate wrong answers

Option A is wrong because the runtime exception is thrown inside the loop, not after the loop; the finally block executes, but the exception propagates immediately, preventing any further loop iterations. Option C is wrong because the catch block throws a runtime exception, which is not caught within the loop, so the loop does not continue; the exception propagates. Option D is wrong because the runtime exception is not suppressed; it propagates after the finally block executes, and the loop terminates.

154
Multi-Selecthard

Which two statements are true about Java module declarations? (Choose two.)

Select 2 answers
A.The uses directive is used to specify that a module provides a service implementation.
B.A module can read another module only if it explicitly requires it.
C.A qualified export allows access to the exported package only to specific modules.
D.The requires directive can be used to specify a module that is optional.
E.The opens directive allows reflective access to all types and members in the opened package, including private members.
AnswersC, E

Qualified exports restrict accessibility to a comma-separated list of module names.

Why this answer

Options A and B are correct. A qualified export (exports package to module) restricts access to specified modules. The opens directive grants reflective access to all members, including private ones.

Option C is false because java.base is implicitly required; in a named module, other modules must be explicitly required or inherited. Option D is false: uses is for consuming services, provides is for implementing them. Option E is false: requires static makes a dependency optional, not requires alone.

155
MCQhard

A company uses jlink to create a custom runtime image. They want to reduce the image size by removing debug information. Which jlink option or plugin should they use?

A.--compress=2
B.--strip-debug
C.--no-header-files
D.--bind-services
AnswerB

Specifically removes debug information to reduce image size.

Why this answer

The `--strip-debug` option in jlink removes debug information from the custom runtime image, including line numbers, local variable tables, and source file references, which significantly reduces the image size. This is the correct option for stripping debug information, as it directly targets the removal of debugging metadata from the generated image.

Exam trap

The trap here is that candidates often confuse `--strip-debug` with `--compress=2`, assuming compression removes debug information, but compression only reduces file size without eliminating the underlying debug metadata.

How to eliminate wrong answers

Option A is wrong because `--compress=2` applies ZIP compression to resources in the runtime image, which reduces size through compression but does not remove debug information. Option C is wrong because `--no-header-files` excludes header files (e.g., C headers for native code) from the image, which is unrelated to debug information removal. Option D is wrong because `--bind-services` enables service binding resolution for modules, which affects module graph resolution but has no impact on debug information.

156
MCQhard

A developer creates an unmodifiable list via Collections.unmodifiableList(originalList). Later, originalList is modified by adding an element. Which statement is true?

A.The unmodifiable list remains unchanged
B.The unmodifiable list becomes inconsistent
C.An UnsupportedOperationException is thrown
D.The unmodifiable list reflects the addition
AnswerD

Unmodifiable wrapper is a view; changes to backing list are visible.

Why this answer

D is correct because `Collections.unmodifiableList()` returns a view-backed unmodifiable list that reflects any changes made to the original list. The unmodifiable list does not create a snapshot; it wraps the original list, so modifications to the original are visible through the unmodifiable wrapper.

Exam trap

The trap here is that candidates often assume `Collections.unmodifiableList()` creates an immutable copy, similar to `List.copyOf()`, but it actually creates a dynamic view that changes with the original list.

How to eliminate wrong answers

Option A is wrong because the unmodifiable list is a view of the original list, so it does change when the original list is modified. Option B is wrong because the unmodifiable list remains consistent with the original list; it does not become inconsistent. Option C is wrong because `UnsupportedOperationException` is thrown only when attempting to modify the unmodifiable list itself (e.g., calling `add()` on it), not when the original list is modified.

157
MCQeasy

A web application allows users to specify filenames for uploaded documents. The application saves files to a directory using the provided name. Which secure programming practice should be applied to prevent path traversal attacks?

A.Validate that the filename contains only alphanumeric characters.
B.Generate a random UUID for each file, ignoring the user-provided filename.
C.Replace all occurrences of ".." and "/" with an empty string.
D.Use File.getCanonicalPath() to resolve the path and check it starts with the intended directory.
AnswerD

By resolving the canonical path, the application can verify that the file lies within the allowed directory.

Why this answer

Option D is correct because `File.getCanonicalPath()` resolves all symbolic links, `.` and `..` sequences, and platform-specific path conventions to produce an absolute, unique path. By then verifying that this canonical path starts with the intended base directory (e.g., `/var/uploads/`), the application can definitively reject any path that escapes outside the allowed directory, even if the user-supplied filename contains encoded or obfuscated traversal sequences.

Exam trap

The trap here is that candidates often choose Option C (string replacement) because it seems straightforward, but they overlook that simple blacklisting of `..` and `/` is trivially bypassed by double-encoding, nested patterns, or Unicode normalization, whereas canonical path resolution is the only robust defense against path traversal.

How to eliminate wrong answers

Option A is wrong because restricting to alphanumeric characters is overly restrictive and still fails to prevent path traversal if the filename contains encoded traversal sequences (e.g., `%2e%2e%2f`) that are decoded after validation. Option B is wrong because while generating a random UUID eliminates the user-supplied filename entirely and prevents traversal, it is not a validation or sanitization technique; it is a complete replacement strategy that discards user intent, which may not be acceptable for all use cases (e.g., when the original filename must be preserved for business logic). Option C is wrong because simply replacing `..` and `/` with an empty string is easily bypassed by using nested patterns like `....//` which, after removal of `..` and `/`, leave `../` intact, or by using URL-encoded or Unicode variants that the replacement logic does not catch.

158
MCQeasy

What does the following code print? List<Integer> list = List.of(1, 2, 3, 4, 5); list.stream().filter(i -> i % 2 == 0).forEach(System.out::print);

A.No output
B.12345
C.135
D.24
AnswerD

Correct.

Why this answer

The correct answer is D because the stream filters only even numbers (i % 2 == 0) from the list, producing 2 and 4, which are then printed sequentially via forEach. The filter operation retains elements where the predicate is true, so only 2 and 4 satisfy the condition.

Exam trap

The trap here is that candidates often confuse the filter predicate (i % 2 == 0) with selecting odd numbers, or they forget that filter retains matching elements rather than removing them, leading to selection of option C or B.

How to eliminate wrong answers

Option A is wrong because the stream pipeline does produce output; the filter does not eliminate all elements, so there is output. Option B is wrong because it prints all numbers (1,2,3,4,5), which would occur if no filter were applied, but the filter removes odd numbers. Option C is wrong because it prints odd numbers (1,3,5), which is the opposite of the filter condition (i % 2 == 0 selects even numbers).

159
MCQhard

Which of the following will compile without error and produce an unmodifiable list containing three elements?

A.Arrays.asList("A","B","C")
B.new ArrayList<>(List.of("A","B","C"))
C.List.of("A","B","C")
D.Collections.unmodifiableList(new ArrayList<>(List.of("A","B","C")))
E.None of the above
AnswerC

Correct: List.of returns an immutable list.

Why this answer

Option C is correct because `List.of("A","B","C")` returns an unmodifiable list containing exactly three elements, as specified by the Java 9+ static factory method. It compiles without error and any attempt to modify the list will throw an `UnsupportedOperationException`.

Exam trap

The trap here is that candidates often confuse `Arrays.asList()` with an unmodifiable list, not realizing that `set()` is still permitted, while `List.of()` is truly immutable and the correct choice for an unmodifiable list in modern Java.

How to eliminate wrong answers

Option A is wrong because `Arrays.asList("A","B","C")` returns a fixed-size list backed by the array, but it is not truly unmodifiable — you can still call `set()` to change elements, so it does not produce an unmodifiable list. Option B is wrong because `new ArrayList<>(List.of("A","B","C"))` creates a mutable `ArrayList` that can be modified via `add()` or `remove()`, so it is not unmodifiable. Option D is wrong because `Collections.unmodifiableList(new ArrayList<>(List.of("A","B","C")))` does produce an unmodifiable view, but it is not the simplest or most direct way; the question asks for an option that 'will compile without error and produce an unmodifiable list', and while D technically works, it is not the best answer because it involves extra wrapping and the question implies a single method call.

Option E is wrong because option C is correct.

160
Multi-Selecthard

Which TWO statements about Java serialization are true?

Select 2 answers
A.The serialVersionUID must be explicitly declared in every serializable class.
B.During deserialization, the constructor of the serialized class is not invoked.
C.A class that implements Externalizable does not need to implement Serializable.
D.Static fields are not serialized during serialization.
E.Fields marked as transient are serialized by default.
AnswersB, D

Deserialization uses special mechanism without constructor.

Why this answer

Option B is correct because during deserialization, Java does not invoke the constructor of the class being deserialized. Instead, the object is reconstructed from the serialized stream data using the no-arg constructor of the first non-serializable superclass (if any), and the serialized class's fields are populated via reflection or readObject() methods. This avoids re-executing initialization logic that may have side effects or depend on runtime state.

Exam trap

The trap here is that candidates often assume constructors are always called during object creation, but Java serialization bypasses constructors for the serialized class, which can lead to unexpected behavior if initialization logic is missing.

161
MCQeasy

Refer to the exhibit. What is the output?

A.compile error
B.null
C.false
D.true
AnswerD

Correct: Both return Boolean.TRUE, so == compares reference and is true.

Why this answer

Option D is correct because the code uses `Boolean.valueOf(true)` which returns the `Boolean` constant `Boolean.TRUE`, and `Boolean.TRUE` is a singleton object that is `==` to itself. The `==` operator compares object references, not values, so the comparison `Boolean.valueOf(true) == Boolean.TRUE` evaluates to `true` because both refer to the same cached `Boolean` instance from the `Boolean` class's static final fields.

Exam trap

The trap here is that candidates mistakenly think `Boolean.valueOf(true)` returns a primitive `boolean` or a new object each time, leading them to believe `==` compares values or that the result is `false`, when in fact `valueOf` returns the cached singleton `Boolean.TRUE`.

How to eliminate wrong answers

Option A is wrong because the code compiles without error; `Boolean.valueOf(boolean)` is a valid static method that returns a `Boolean` object, and the `==` operator is valid for reference comparison. Option B is wrong because the output is not `null`; `Boolean.valueOf(true)` never returns `null`—it returns a non-null `Boolean` object. Option C is wrong because `false` would only occur if the `==` comparison evaluated to `false`, but since `Boolean.valueOf(true)` returns the same singleton as `Boolean.TRUE`, the reference equality is `true`.

162
Multi-Selecthard

Which TWO are true about HashSet and TreeSet?

Select 2 answers
A.HashSet maintains elements in insertion order.
B.HashSet uses equals() and hashCode() for uniqueness, TreeSet uses compareTo() or Comparator.
C.Both implement the List interface.
D.Both guarantee constant-time performance for basic operations (add, remove, contains).
E.TreeSet requires elements to be mutually comparable, unless a Comparator is provided.
AnswersB, E

Correct.

Why this answer

Option B is correct because HashSet relies on the equals() and hashCode() methods to determine element uniqueness, while TreeSet uses the natural ordering (compareTo()) or a provided Comparator to maintain sorted order and check for duplicates. This distinction is fundamental to how these Set implementations enforce uniqueness.

Exam trap

The trap here is that candidates often confuse the performance guarantees of HashSet (constant-time average) with TreeSet (logarithmic time), or mistakenly think both maintain insertion order, when in fact only LinkedHashSet does.

163
MCQmedium

What does the following code print? List<Integer> list = new ArrayList<>(List.of(1,2,3)); list.replaceAll(x -> x * 2); System.out.println(list);

A.[2,3,4]
B.[2,4,6]
C.Compilation fails
D.[1,4,9]
E.[1,2,3]
AnswerB

Correct: each element is doubled.

Why this answer

The `replaceAll` method on a `List` applies the given `UnaryOperator` to each element, replacing it with the result. Here, `x -> x * 2` multiplies each integer by 2, so the list becomes `[2, 4, 6]`. Option B is correct because the code compiles and runs, producing that output.

Exam trap

The trap here is that candidates may think `replaceAll` doesn't exist on `List` or that it requires a `Comparator`, or they may confuse it with `replaceAll` on `Map` or `String`, leading them to incorrectly choose compilation failure (Option C).

How to eliminate wrong answers

Option A is wrong because it suggests the output is `[2,3,4]`, which would result from adding 1 to each element, not multiplying by 2. Option C is wrong because the code compiles successfully; `List.replaceAll` accepts a `UnaryOperator` lambda, and `List.of(1,2,3)` returns an immutable list, but `new ArrayList<>(List.of(1,2,3))` creates a mutable copy, so no compilation error occurs. Option D is wrong because it implies squaring each element (`x -> x * x`), not doubling.

Option E is wrong because it shows the original list unchanged, ignoring the effect of `replaceAll`.

164
MCQmedium

Refer to the exhibit. A Java application is deployed in /opt/app/lib/ and attempts to perform the following operations: 1) Read the file /data/config/settings.xml 2) Write to the file /logs/app.log 3) Read the file /data/config/subdir/extra.conf Which statement is true?

A.All three operations are allowed because the code base matches.
B.Operations 1 and 2 are allowed; operation 3 is denied.
C.Only operation 1 is allowed; operations 2 and 3 are denied.
D.Operations 1 and 3 are allowed; operation 2 is denied.
AnswerB

Operation 1 is allowed by "/data/config/*" (file in /data/config/). Operation 2 is explicitly granted. Operation 3 is in a subdirectory, not matched by *.

Why this answer

The grant applies to code from /opt/app/lib/* (all jars in that directory). The first FilePermission "/data/config/*" grants read access to /data/config/settings.xml but not to /data/config/subdir/extra.conf because * only matches files in the directory, not subdirectories. The second permission grants write to /logs/app.log exactly.

So only operations 1 and 2 are allowed.

165
MCQhard

A team is developing a large enterprise application using Java 17. The application consists of multiple modules: core (provides logging and configuration), services (business logic), and web (REST endpoints). The modules are packaged as separate JAR files and deployed on a server. During runtime, the web module throws a java.lang.ClassNotFoundException for a class that is part of the core module. The core module's module-info.java exports the package containing the missing class. The web module's module-info.java requires core. However, the services module also needs the same class but uses a different version of it, causing conflicts. The team decides to use the class path for the conflicting package and the module path for the rest. They add the conflicting JAR to the class path and keep the other JARs on the module path. After this change, the web module still cannot find the class, but the services module works fine. What is the most likely cause of the issue?

A.The services module is using an automatic module, which automatically reads the unnamed module, while the web module is a named module that does not.
B.The class path is not scanned for JAR files unless the module path is empty.
C.The web module is a named module and cannot access classes from a split package that is also in the unnamed module.
D.The core module's module-info.java does not export the package to the web module; it only exports it to all modules.
AnswerC

The module system prevents named modules from accessing split packages from the class path to maintain reliable configuration.

Why this answer

Option C is correct because when a named module (the web module) is on the module path, it cannot access classes from the unnamed module (the class path) if those classes belong to a package that is also exported by another named module on the module path. This creates a split package, which is forbidden by the Java module system. The core module exports the package, so the web module cannot load the class from the class path JAR, resulting in ClassNotFoundException.

Exam trap

The trap here is that candidates often think the issue is about module visibility (exports) or class path scanning order, but the real constraint is the split package rule, which prevents a named module from accessing a package that is already defined by another named module on the module path.

How to eliminate wrong answers

Option A is wrong because the services module is not necessarily an automatic module; the scenario states it uses a different version of the class from the class path, and automatic modules can read the unnamed module, but the core issue is about split packages, not automatic module behavior. Option B is wrong because the class path is scanned for JAR files even when the module path is non-empty; the unnamed module is always present and accessible to named modules only for packages not exported by any named module. Option D is wrong because the core module's module-info.java exports the package to all modules (implied by 'exports' without a 'to' clause), so it does export to the web module; the problem is the split package, not insufficient exports.

166
MCQmedium

A developer wants to traverse a directory tree to find all files that are symbolic links. Which NIO.2 method should be used to follow symbolic links during traversal?

A.Files.newDirectoryStream(Path)
B.Files.list(Path)
C.Files.walk(Path) without options
D.Files.walk(Path, FileVisitOption.FOLLOW_LINKS)
AnswerD

This method with FOLLOW_LINKS will follow symbolic links during directory traversal.

Why this answer

The correct answer is D because `Files.walk(Path, FileVisitOption.FOLLOW_LINKS)` is the only method among the options that both traverses a directory tree recursively and explicitly follows symbolic links. The `FileVisitOption.FOLLOW_LINKS` enum constant instructs the walk to follow symbolic links, allowing the traversal to detect files that are themselves symbolic links. Without this option, `Files.walk` treats symbolic links as regular files and does not follow them, which would miss the target of the link.

Exam trap

The trap here is that candidates often assume `Files.walk(Path)` without options follows symbolic links by default, but the default behavior is to NOT follow links, and the `FOLLOW_LINKS` option must be explicitly provided to enable that behavior.

How to eliminate wrong answers

Option A is wrong because `Files.newDirectoryStream(Path)` returns a `DirectoryStream` that only lists the immediate entries of a single directory, not a recursive traversal, and it does not have any option to follow symbolic links. Option B is wrong because `Files.list(Path)` also only returns a stream of entries in a single directory (non-recursive) and cannot follow symbolic links. Option C is wrong because `Files.walk(Path)` without options performs a recursive traversal but does not follow symbolic links by default; it treats symbolic links as files and does not descend into directories that are symbolic links, so it would not find all files that are symbolic links in the sense of following them.

167
Multi-Selecteasy

Which TWO of the following are characteristics of a well-designed lambda expression? (Choose two.)

Select 2 answers
A.Is stateless
B.Throws exceptions that are not declared in the functional interface's abstract method
C.Uses the same variable name as a parameter in the enclosing scope (shadowing)
D.Uses only effectively final variables from the enclosing scope
E.Modifies local variables of the enclosing method
AnswersA, D

Stateless lambdas are safer, especially in parallel streams, as they avoid race conditions.

Why this answer

A well-designed lambda should be stateless and use effectively final variables to avoid side effects and ensure predictability.

168
Multi-Selectmedium

Which two statements are true about records in Java? (Choose two.)

Select 2 answers
A.Records provide a canonical constructor that initializes all components.
B.Records can be abstract.
C.Records can extend other classes.
D.Records can have instance fields that are not part of the record component list.
E.Records are implicitly final.
AnswersA, E

The canonical constructor initializes all record components.

Why this answer

Records are implicitly final and provide a canonical constructor that initializes all components. They cannot extend other classes, cannot have instance fields outside the component list, and cannot be abstract.

169
Multi-Selecthard

Which THREE practices are recommended for effective exception handling? (Choose three.)

Select 3 answers
A.Throw exceptions early, catch them late, but handle them at the appropriate level.
B.Define custom exceptions without providing any additional context.
C.Use try-with-resources for automatic resource management instead of manual close in finally.
D.Catch exceptions at the highest level of the application and log them generically.
E.Use specific exception types in catch blocks rather than catching Exception.
AnswersA, C, E

Best practice: throw at point of error, catch where recovery is possible.

Why this answer

Option A is correct because effective exception handling in Java recommends throwing exceptions as soon as an error is detected (fail-fast), catching them at a level where the error can be meaningfully handled (not too early), and handling them at the appropriate layer of abstraction. This prevents swallowing exceptions or losing context, and aligns with the principle of separation of concerns.

Exam trap

Oracle often tests the misconception that catching exceptions at the highest level with generic logging is a good practice, when in fact it hides errors and violates the principle of handling exceptions at the appropriate level.

170
MCQmedium

A class implements Serializable. Which modification ensures that a specific field (password) is not included in the serialized stream?

A.Declare the field as volatile
B.Declare the field as transient
C.Declare the field as static
D.Declare the field as final
AnswerB

Transient fields are skipped during serialization.

Why this answer

Option C is correct because the transient keyword prevents serialization of that field. Option A is wrong because final does not affect serialization. Option B is wrong because static fields are not serialized anyway, but that changes the field's nature.

Option D is wrong because volatile affects concurrency, not serialization.

171
MCQmedium

A web server logs user sessions. Each session has a unique session ID (String) and a last access time (long). The system needs to evict sessions that have been inactive for more than 30 minutes. The current implementation uses a HashMap<String, Long> to store session IDs and last access times. A scheduled task iterates over all entries and removes those where currentTime - lastAccess > 30 minutes. However, this iteration is becoming slow as the number of sessions grows (millions). The developer wants to improve the eviction performance without affecting the O(1) put and get operations. Which approach should be taken?

A.Use PriorityQueue<Session> ordered by last access time and update the time when accessed.
B.Use ConcurrentHashMap<String, Long> and use parallel streams to remove expired entries.
C.Use LinkedHashMap<String, Long> with access-order=true and override removeEldestEntry() to evict entries older than 30 minutes.
D.Use TreeMap<String, Long> sorted by last access time and poll the first entry if too old.
AnswerC

Efficiently maintains access order and automatically evicts eldest.

Why this answer

Option C is correct because LinkedHashMap with access-order=true and a custom removeEldestEntry() method provides O(1) amortized put/get operations while automatically evicting the least-recently accessed entry when a condition is met. By overriding removeEldestEntry() to check if the eldest entry's last access time is older than 30 minutes, the eviction happens during put operations without requiring a separate iteration over all entries, thus solving the performance issue.

Exam trap

The trap here is that candidates may think a sorted structure like TreeMap or PriorityQueue is needed for time-based eviction, but they overlook the O(1) access-time requirement and the fact that LinkedHashMap's access-order mode provides automatic LRU eviction without explicit iteration.

How to eliminate wrong answers

Option A is wrong because PriorityQueue does not support O(1) updates to the ordering key; updating the last access time would require removing and reinserting the element, which is O(log n) and disrupts the O(1) requirement for get operations. Option B is wrong because using parallel streams to iterate over a ConcurrentHashMap still requires scanning all entries, which is O(n) and does not improve the fundamental iteration cost; it also introduces thread-safety overhead without solving the algorithmic inefficiency. Option D is wrong because TreeMap maintains order by key (session ID), not by last access time; sorting by last access time would require a custom comparator that cannot be updated efficiently, and polling the first entry would not guarantee it is the oldest by access time.

172
Multi-Selecthard

Which THREE are valid ways to read the contents of a text file into a String in Java?

Select 3 answers
A.String content = Files.readString(Path.of("file.txt"));
B.String content = new FileReader("file.txt").readString();
C.String content = Files.readAllLines(Path.of("file.txt"));
D.String content = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
E.String content = Files.lines(Path.of("file.txt")).collect(Collectors.joining("\n"));
AnswersA, D, E

Files.readString() reads entire file into a String.

Why this answer

Option A is correct because `Files.readString()` (introduced in Java 11) reads the entire content of a text file into a `String` in one call, handling charset encoding (default UTF-8) and closing the file automatically. It is the simplest and most direct method for this task.

Exam trap

The trap here is that candidates may confuse `Files.readAllLines()` (which returns a `List`) with `Files.readString()` (which returns a `String`), or assume `FileReader` has a `readString()` method when it does not.

173
Multi-Selecthard

Which TWO statements about creating custom exceptions are correct? (Choose two.)

Select 2 answers
A.Custom exceptions should extend Error to indicate fatal errors.
B.Custom exception classes should be declared final to prevent subclassing.
C.Custom exceptions must implement the Exception interface.
D.It is good practice to provide a constructor that takes a String message and a Throwable cause.
E.When calling super(cause) in a custom exception constructor, the cause is automatically set.
AnswersD, E

Common to have such constructor.

Why this answer

Option D is correct because it is a well-established best practice in Java to provide a constructor that accepts both a String message and a Throwable cause, enabling precise error reporting and chaining of exceptions. This allows developers to pass a human-readable description along with the underlying cause, which is essential for debugging and logging.

Exam trap

The trap here is that candidates often confuse the requirement to extend Throwable (or a subclass) with implementing a nonexistent Exception interface, or they mistakenly think that custom exceptions must be declared final to prevent misuse, when in fact Java allows and encourages subclassing of custom exceptions for more granular error handling.

174
MCQhard

Assuming the code runs in a multithreaded environment, which statement best describes the behavior?

A.The code will compile but throw an exception at runtime because of the use of parallel stream with stateful lambda.
B.It prints the doubled numbers in order (2, 4, 6, 8) and results contains [1,2,3,4] in that order.
C.It may produce a ConcurrentModificationException because results is modified while iterating.
D.It prints the doubled numbers in a non-deterministic order and results may contain missing or duplicate entries.
AnswerD

Correct: Parallel stream processes elements concurrently, so the order of map execution is non-deterministic. The shared results list is not thread-safe, leading to data corruption.

Why this answer

The lambda in map is stateful (modifying results list) and not thread-safe. This can cause race conditions and non-deterministic output. Additionally, forEachOrdered does not make the preceding stateful operation safe.

175
MCQeasy

Examine the code: List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); for (String s : list) { list.remove(s); } What is the outcome?

A.A ConcurrentModificationException is thrown
B.The loop completes successfully and list becomes empty
C.An IllegalStateException is thrown
D.The loop completes successfully and list contains [B]
AnswerA

Modifying list during iteration with for-each throws exception.

Why this answer

The for-each loop internally uses an Iterator to traverse the list. When the list is structurally modified (via `list.remove()`) during iteration without using the iterator's own `remove()` method, the iterator detects a concurrent modification and throws a `ConcurrentModificationException`. This is a fail-fast behavior of the `ArrayList` iterator.

Exam trap

The trap here is that candidates often assume the for-each loop will safely remove elements one by one, not realizing that the implicit iterator throws an exception on structural modification.

How to eliminate wrong answers

Option B is wrong because the loop does not complete successfully; the exception is thrown before the list becomes empty. Option C is wrong because `IllegalStateException` is not thrown in this scenario; it is typically thrown when calling `remove()` on an iterator without a preceding `next()`. Option D is wrong because the loop does not complete and the list is not left containing [B]; the exception interrupts execution before any such state is reached.

176
Multi-Selecteasy

Which TWO statements are true about ArrayList in Java 17? (Choose two.)

Select 2 answers
A.It implements the List interface
B.It implements the Set interface
C.It implements the Queue interface
D.It extends AbstractList
E.It is synchronized
AnswersA, D

ArrayList implements List.

Why this answer

Option A is correct because ArrayList implements the List interface, which is a core part of the Java Collections Framework. This allows ArrayList to be used polymorphically wherever a List is expected, providing ordered, index-based access to elements.

Exam trap

The trap here is that candidates often confuse ArrayList's lack of synchronization with thread safety, or mistakenly think it implements Set or Queue due to its membership in the Collections Framework, but ArrayList is strictly a List implementation.

177
Multi-Selectmedium

Which TWO of the following are checked exceptions in Java?

Select 2 answers
A.SQLException
B.ArithmeticException
C.ArrayIndexOutOfBoundsException
D.NullPointerException
E.IOException
AnswersA, E

SQLException is a checked exception.

Why this answer

A is correct because `SQLException` is a subclass of `java.lang.Exception` (which is a checked exception class) and does not extend `RuntimeException`. Checked exceptions must be either caught or declared in the method signature; `SQLException` is commonly thrown when database access errors occur, such as connection failures or SQL syntax errors.

Exam trap

The trap here is that candidates often confuse runtime exceptions (unchecked) with checked exceptions, mistakenly thinking that any exception that can occur at runtime is checked, but the key distinction is whether the exception class extends `RuntimeException` or not.

178
MCQhard

A serialized object has an explicitly declared serialVersionUID of 123L. After a code change, a new field is added to the class but the serialVersionUID is left unchanged. What happens when deserializing an old stream?

A.Deserialization succeeds and the new field is set to its default value.
B.Deserialization succeeds only if the new field is marked transient.
C.Deserialization throws StreamCorruptedException due to missing field.
D.Deserialization throws InvalidClassException because the class definition has changed.
AnswerA

With matching serialVersionUID, deserialization maps fields; new fields get default values.

Why this answer

Option A is correct because when a serialized object has an unchanged serialVersionUID, the Java deserialization mechanism treats the class as compatible. The new field is not present in the old stream, so it is simply initialized to its default value (e.g., null for objects, 0 for primitives) without throwing an exception. This behavior is defined by the Java Object Serialization Specification, which allows forward compatibility as long as the serialVersionUID matches.

Exam trap

The trap here is that candidates often assume any class change (like adding a field) will break deserialization, but the exam tests that a matching serialVersionUID allows the new field to be silently defaulted, not that it causes an exception.

How to eliminate wrong answers

Option B is wrong because marking the new field transient is not required for deserialization to succeed; the field will be set to its default value regardless of the transient modifier. Option C is wrong because StreamCorruptedException is thrown only when the stream data is corrupted or the stream header is invalid, not when a field is missing due to a class evolution. Option D is wrong because InvalidClassException is thrown only when the serialVersionUIDs differ between the local class and the stream, not when fields are added or removed while the UID remains the same.

179
MCQeasy

Which resource declaration order in try-with-resources is valid when both a FileInputStream and a BufferedInputStream wrapping it need to be closed automatically?

A.try (FileInputStream fis = new FileInputStream("a")) { BufferedInputStream bis = new BufferedInputStream(fis); ... }
B.try (FileInputStream fis = new FileInputStream("a"); BufferedInputStream bis = new BufferedInputStream(fis)) { ... }
C.try (BufferedInputStream bis = new BufferedInputStream(fis); FileInputStream fis = new FileInputStream("a")) { ... }
D.try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a"))) { ... }
AnswerB

Both resources are declared in order; fis is closed after bis as resources are closed in reverse order.

Why this answer

Option A is correct: Both resources are declared in the try header, with fis declared before bis. Option B has a forward reference error. Option C does not include bis in the try header, so it won't be automatically closed.

Option D only declares one resource, not both.

180
Multi-Selecthard

Which two statements are true about FileInputStream? (Select two.)

Select 2 answers
A.It supports mark() and reset().
B.It extends java.io.InputStream.
C.It implements java.io.Closeable.
D.It reads data in big-endian order.
E.It can be used to read characters.
AnswersB, C

FileInputStream is a subclass of InputStream.

Why this answer

Option B is correct because FileInputStream directly extends java.io.InputStream, inheriting its abstract methods for reading bytes from a file. Option C is correct because FileInputStream implements java.io.Closeable, which extends AutoCloseable, allowing it to be used in try-with-resources statements for automatic resource management.

Exam trap

The trap here is that candidates often confuse FileInputStream with BufferedInputStream or DataInputStream, assuming it supports mark/reset or reads data in a specific byte order, when in fact it is a simple unbuffered byte stream with no such capabilities.

181
MCQmedium

A developer is tasked with reading a large binary file (1 GB) from a network share using the least amount of memory possible. Which approach should be used?

A.Use a FileInputStream wrapped in a BufferedInputStream with a 8 KB buffer
B.Read the entire file into a byte array using Files.readAllBytes()
C.Use a FileReader wrapped in a BufferedReader to read lines
D.Use a RandomAccessFile to read the file in segments
AnswerA

This reads the file in chunks with a small buffer, minimizing memory footprint.

Why this answer

Option A is correct because using a FileInputStream wrapped in a BufferedInputStream with a small buffer (e.g., 8 KB) allows reading the file in chunks without loading the entire 1 GB into memory. This approach minimizes heap usage by processing data incrementally, which is essential for large binary files over a network share where memory constraints are critical.

Exam trap

The trap here is that candidates often confuse 'least memory' with 'fastest performance' and choose Files.readAllBytes() for simplicity, or they incorrectly assume RandomAccessFile is more memory-efficient, when in fact buffered streaming is the standard low-memory approach for large binary files.

How to eliminate wrong answers

Option B is wrong because Files.readAllBytes() reads the entire file into a single byte array, which would require at least 1 GB of heap memory, defeating the goal of minimal memory usage. Option C is wrong because FileReader and BufferedReader are designed for character-based text files, not binary data; reading a binary file as characters would corrupt the data and still buffer large amounts unnecessarily. Option D is wrong because RandomAccessFile is primarily for random access and seeking within a file, not for sequential streaming; it still requires managing file pointers and does not inherently reduce memory usage compared to a buffered stream.

182
MCQeasy

You are designing a logging framework for a distributed application. The framework must support multiple output destinations (console, file, network socket) and allow clients to dynamically add new destinations at runtime without modifying existing code. Currently, the application uses a single static Logger class with methods like logToConsole(String msg) and logToFile(String msg). The team needs to refactor the code to adhere to the Open/Closed Principle and support extensibility. After reviewing the requirements, you propose using a combination of an interface and a strategy pattern. However, a senior developer argues that using a simple enum with abstract methods would be sufficient. Which course of action best adheres to object-oriented design principles and allows the most flexibility for future extensions?

A.Keep the existing static methods but add a new method for each destination as needed. Use conditional logic to select the destination at runtime.
B.Refactor Logger to be an interface, and implement concrete destination classes (ConsoleLogger, FileLogger, SocketLogger). Use dependency injection to pass the desired destination to the Logger client.
C.Create an enum LogDestination with values CONSOLE, FILE, SOCKET, each overriding an abstract log(String) method. The Logger class uses a static method that accepts a LogDestination and calls its log method.
D.Refactor Logger to be an abstract class with an abstract log method, and create subclasses for each destination. Use a factory method to instantiate the correct subclass.
AnswerB

This follows the strategy pattern and Open/Closed Principle, allowing new destinations to be added without modifying existing code.

Why this answer

Option A uses an interface and dependency injection, which allows new destinations to be added without modifying existing code, fully adhering to the Open/Closed Principle. Option B (enum) requires modifying the enum to add new destinations, violating Open/Closed. Option C (adding methods) also requires modification.

Option D (abstract class with subclasses) still requires a factory modification. Therefore, A is the best.

183
MCQmedium

A program reads user input as a string and needs to parse it into an integer, handling invalid input gracefully. Which code snippet correctly uses try-catch to parse and prints the result or 'Invalid number'?

A.try { int num = Integer.valueOf(input).intValue(); System.out.println(num); } catch (Exception e) { System.out.println("Invalid number"); }
B.int num = Integer.parseInt(input); System.out.println(num);
C.if (input.matches("\\d+")) { int num = Integer.parseInt(input); System.out.println(num); } else { System.out.println("Invalid number"); }
D.try { int num = Integer.parseInt(input); System.out.println(num); } catch (NumberFormatException e) { System.out.println("Invalid number"); }
AnswerD

Correct: Catches the specific exception and prints an error message.

Why this answer

Option D is correct because it uses `Integer.parseInt(input)` which throws a `NumberFormatException` for invalid input, and the catch block specifically catches that exception to print 'Invalid number'. This is the standard, idiomatic Java approach for parsing integers with error handling, as it directly addresses the requirement without unnecessary overhead or false positives.

Exam trap

The trap here is that candidates often choose Option C (regex validation) thinking it's more efficient or 'cleaner', but they overlook that the regex `\d+` fails for negative numbers and other valid integer formats, while the try-catch approach in D is both correct and idiomatic for Java.

How to eliminate wrong answers

Option A is wrong because `Integer.valueOf(input).intValue()` is redundant (valueOf returns an Integer, then intValue unboxes it) and catches the overly broad `Exception` type, which is poor practice and could mask unrelated errors. Option B is wrong because it has no error handling at all; if the input is not a valid integer, `Integer.parseInt` will throw a `NumberFormatException` and the program will crash. Option C is wrong because the regex `\d+` does not account for optional leading minus signs (negative numbers) or leading zeros, so it would incorrectly reject valid integers like '-5' or accept invalid strings like empty input (if input is empty, matches returns false, but the logic is still flawed for negative numbers).

184
MCQeasy

Given the code snippet: List<String> list = new ArrayList<>(List.of("A","B","C")); list.add("D"); System.out.println(list.size()); What is the result?

A.5
B.UnsupportedOperationException
C.4
D.Compilation fails
E.3
AnswerC

Correct: the new ArrayList is mutable, so add works, size is 4.

Why this answer

Option C is correct because the code creates an ArrayList from a fixed-size list returned by List.of() using the ArrayList constructor, which creates a new mutable list containing the elements "A", "B", "C". The subsequent call to list.add("D") successfully appends the element, resulting in a list of size 4. The ArrayList constructor copies the elements, so the original immutable list is not modified.

Exam trap

The trap here is that candidates mistakenly think the list returned by List.of() is directly used, leading them to expect an UnsupportedOperationException, but the ArrayList constructor creates a separate mutable copy, so the add() succeeds.

How to eliminate wrong answers

Option A is wrong because the list contains only 4 elements after adding "D", not 5. Option B is wrong because UnsupportedOperationException would occur if add() were called directly on the list returned by List.of(), but here the list is wrapped in a new ArrayList, which is fully mutable. Option D is wrong because the code compiles without errors; all types and method calls are valid.

Option E is wrong because the list initially has 3 elements from List.of(), but after adding "D", the size becomes 4, not 3.

185
MCQhard

Which statement about the code is correct?

A.A compilation error occurs in the Triangle class because Triangle is not listed in the permits clause.
B.A compilation error occurs because Circle must be declared final.
C.A compilation error occurs because Shape must be declared abstract.
D.The code compiles successfully.
AnswerA

Sealed classes require that all direct subclasses be listed in the permits clause.

Why this answer

The Triangle class is not listed in the permits clause of Shape, so it cannot extend Shape. This causes a compilation error.

186
Multi-Selectmedium

Which two statements are true about the java.util.Comparator and java.lang.Comparable interfaces? (Choose two.)

Select 2 answers
A.Comparator's compare method returns a boolean.
B.Comparator can be used to sort a list in multiple ways.
C.A class implementing Comparable must override equals().
D.Comparable is used to define a natural ordering of objects.
E.Comparator is in java.lang package.
AnswersB, D

True: Multiple Comparators can define different orderings.

Why this answer

Options A and C are correct. Comparable is used to define a natural ordering (A). Comparator can be used to sort a list in multiple ways (C).

Option B is false because Comparator is in java.util. Option D is false because overriding equals is not required. Option E is false because Comparator's compare method returns an int, not boolean.

187
MCQhard

A company runs a Java 17 microservice that processes real-time financial transactions. The application receives a large number of transactions per second, each with a timestamp, amount, and type. The current implementation uses a sequential stream to filter and aggregate transactions into a Map<TransactionType, DoubleSummaryStatistics>. The team observes high latency and CPU spikes during peak loads. They suspect the stream pipeline is inefficient. The pipeline code is: Map<TransactionType, DoubleSummaryStatistics> stats = transactions.stream() .filter(t -> t.getTimestamp().isAfter(Instant.now().minusSeconds(60))) .collect(Collectors.groupingBy(Transaction::getType, Collectors.summarizingDouble(Transaction::getAmount))); The transactions list is an ArrayList that is frequently modified by other threads (adding new transactions). The system has multiple CPU cores available. Which of the following changes is the MOST effective way to improve performance while maintaining correctness?

A.Use .stream().parallel() with a custom thread pool and ensure the stream source is not modified during operation.
B.Use .parallelStream() on a snapshot (new ArrayList<>(transactions)) and keep the same collector.
C.Replace ArrayList with CopyOnWriteArrayList and use .parallelStream() with the same collector.
D.Replace the collector with Collectors.groupingByConcurrent() and use .parallelStream() directly on the original list.
AnswerB

Correct. The snapshot eliminates concurrent modification issues, and parallel processing improves throughput.

Why this answer

Creating a snapshot (new ArrayList<>(transactions)) ensures the stream operates on a consistent, immutable view, avoiding ConcurrentModificationException. Using parallelStream then leverages multiple cores. The groupingBy collector works correctly in parallel because it has a combiner.

This combination balances performance and safety.

188
Multi-Selectmedium

Which TWO statements about try-with-resources are true? (Choose two.)

Select 2 answers
A.Resources are closed in the order they are declared.
B.If both the try block and the close method throw exceptions, the close exception is suppressed.
C.Only a single resource can be managed in a try-with-resources statement.
D.Resources must implement AutoCloseable.
E.Resources are closed after the catch block if an exception occurs.
AnswersB, D

Suppressed exception mechanism.

Why this answer

Option B is correct because when both the try block and the close method throw exceptions, the exception from the close method is suppressed and added to the suppressed exceptions list of the exception thrown by the try block. This behavior is defined by the try-with-resources specification in Java, ensuring that the primary exception is not masked by resource-closing exceptions.

Exam trap

The trap here is that candidates often assume resources close in declaration order (A) or that only one resource is allowed (C), but the exam tests the reverse close order and the ability to manage multiple resources, as well as the precise timing of resource closure relative to catch blocks.

189
MCQeasy

What is the result of attempting to compile and run the above code?

A.[A, B]
B.[A]
C.[B]
D.Compilation fails
E.Runtime exception
AnswerD

Correct: cannot add non-null to a List<?>.

Why this answer

The code attempts to use `removeIf` on a list created with `Arrays.asList`, which returns a fixed-size list backed by the array. The `removeIf` method modifies the list by removing elements, but the fixed-size list does not support structural modification, resulting in an `UnsupportedOperationException` at runtime. However, the question asks for the result of attempting to compile and run, and since the code compiles without errors, the correct answer is 'D.

Compilation fails'? Wait — the code does compile; the issue is a runtime exception. The correct answer should be 'E. Runtime exception'.

Let me re-evaluate: The code `List<String> list = Arrays.asList("A", "B"); list.removeIf(s -> s.equals("A"));` compiles fine because `removeIf` is a valid method on `List`. At runtime, `Arrays.asList` returns a fixed-size list, and `removeIf` attempts to modify the list structurally, throwing `UnsupportedOperationException`. Therefore, the correct answer is E, not D.

I must correct this: The answer is E. The explanation should reflect that.

Exam trap

The trap here is that candidates often assume `Arrays.asList` returns a regular `ArrayList` and forget that it returns a fixed-size list that does not support structural modification, leading them to expect a successful removal rather than a runtime exception.

How to eliminate wrong answers

Option A is wrong because the list does not become [A, B] after removal; the code throws an exception before any removal. Option B is wrong because the list does not become [A]; the exception prevents any modification. Option C is wrong because the list does not become [B]; the exception occurs before the removal operation completes.

Option D is wrong because the code compiles successfully; `removeIf` is a valid method on `List` and the lambda is syntactically correct.

190
MCQhard

A financial application uses Java SE 17 with a custom date format. The requirement is to parse strings like "2023-12-31T23:59:59.999Z" into an Instant. The existing code uses SimpleDateFormat with pattern "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" and then calls parse(). It works fine in single-threaded testing, but in production under load, intermittent parsing failures occur with DateTimeParseException or wrong values. The application is multi-threaded and reuses the same formatter instance. Which single change should be made to fix the issue while maintaining performance?

A.Wrap the parse call in a synchronized block
B.Use a ThreadLocal<SimpleDateFormat> to give each thread its own instance
C.Replace SimpleDateFormat with DateTimeFormatter.ISO_INSTANT and use Instant.from()
D.Create a new SimpleDateFormat instance for each parse call
AnswerC

Thread-safe and correct for ISO 8601.

Why this answer

Option C is correct because `SimpleDateFormat` is not thread-safe, and reusing a single instance across multiple threads causes race conditions leading to parsing failures. Replacing it with `DateTimeFormatter.ISO_INSTANT` (which is immutable and thread-safe) and using `Instant.from()` directly parses the ISO 8601 string without any synchronization overhead, maintaining performance while fixing the concurrency bug.

Exam trap

The trap here is that candidates often choose `ThreadLocal<SimpleDateFormat>` (Option B) because it technically fixes the thread-safety issue, but they overlook that the modern `java.time` API is the recommended, simpler, and more performant solution for Java SE 17, and that the exam expects you to prefer the new API over patching the old one.

How to eliminate wrong answers

Option A is wrong because wrapping the parse call in a `synchronized` block would serialize all parsing operations, severely degrading performance under load and defeating the purpose of multi-threading. Option B is wrong because while `ThreadLocal<SimpleDateFormat>` would fix thread-safety, it still uses the legacy `SimpleDateFormat` class which is error-prone and less efficient than the modern `java.time` API; it also adds unnecessary complexity. Option D is wrong because creating a new `SimpleDateFormat` instance for each parse call would work but imposes significant object creation overhead and garbage collection pressure, harming performance in a high-throughput production environment.

191
Multi-Selecthard

Which two statements about the enhanced for-each loop in Java are true? (Choose two.)

Select 2 answers
A.It requires the target to implement the Iterable interface, except for arrays.
B.It can safely modify the underlying collection during iteration.
C.It can be used to iterate directly over a Stream object.
D.It can be used to iterate over an array.
E.It provides an implicit counter variable that can be accessed.
AnswersA, D

For arrays, the loop works directly; for other objects, they must implement Iterable.

Why this answer

Options A and C are correct. The for-each loop can iterate over arrays and any object that implements java.lang.Iterable, including common collection classes. Option B is false because modifying the underlying collection during iteration (except through the iterator's own remove method) can cause a ConcurrentModificationException.

Option D is false because the for-each loop does not provide an explicit counter; you must use a traditional for loop for that. Option E is false because Stream does not implement Iterable, so you cannot use for-each directly on a Stream; you would need to convert it to a collection or use forEach().

192
MCQeasy

A developer is designing a loop to iterate through an array of integers and stop processing when the value -1 is encountered. Which loop construct should be used?

A.for(int i : array) { if(i == -1) exit; }
B.for(int i : array) { if(i == -1) return; }
C.for(int i : array) { if(i == -1) break; }
D.for(int i : array) { if(i == -1) continue; }
AnswerC

The break statement immediately exits the loop, which is the correct way to stop processing upon encountering -1.

Why this answer

Option C is correct because the `break` statement immediately terminates the loop when the value -1 is encountered, which is exactly what the requirement specifies. In Java, `break` exits the innermost loop or switch statement, making it the appropriate control flow mechanism for stopping iteration upon a condition.

Exam trap

The trap here is that candidates often confuse `break` with `continue` or mistakenly use `return` or `exit` to exit a loop, not realizing that `break` is the precise mechanism for loop termination without affecting the rest of the method or JVM.

How to eliminate wrong answers

Option A is wrong because `exit` is not a valid Java keyword or statement; the correct syntax would be `System.exit(0)`, but that would terminate the entire JVM, not just the loop. Option B is wrong because `return` exits the current method, not just the loop, which would prematurely end the enclosing method and is too broad for simply stopping iteration. Option D is wrong because `continue` skips the current iteration and proceeds to the next element, which does not stop the loop when -1 is found.

193
MCQmedium

What is the output of the code in the exhibit?

A.1,234.57 €
B.€1,234.57
C.€ 1.234,57
D.1.234,57 €
AnswerD

Correct: German format with comma as decimal.

Why this answer

Option B is correct. In Germany, the currency symbol is €, and the format uses comma as decimal separator and dot as group separator, resulting in '1.234,57 €'. Option A uses wrong symbol and grouping.

Option C uses wrong decimal separator. Option D is a different locale format.

194
MCQmedium

What is the output of the following code? int i=5; do { System.out.print(i); i--; } while(i>0);

A.54321
B.Compilation error
C.543210
D.5432
AnswerA

The loop prints each number from 5 down to 1.

Why this answer

The do-while loop executes the body first, then checks the condition. Starting with i=5, it prints 5, decrements to 4, checks condition (4>0 true), continues. It prints 5,4,3,2,1.

When i becomes 0, the condition fails. So output is '54321'. Option A is correct.

195
MCQhard

Your team manages a high-throughput financial transaction system running on Java 17. Recently, the application experiences intermittent slowdowns and increased CPU usage during peak hours. Monitoring reveals that exception handling code is invoked frequently due to validation errors in incoming data. The system uses a central exception handler that logs every exception and throws a custom ApplicationException. In many places, the code catches generic Exception and rethrows the custom exception after logging. Additionally, method signatures include throws Exception. The team wants to improve performance and maintainability without changing the external behavior significantly. Which course of action best addresses the performance and maintainability issues?

A.Change all catch blocks to catch Throwable and ignore irrecoverable errors to reduce logging.
B.Add a try-catch block around every method call that might throw an exception to handle locally.
C.Define specific custom checked exception classes for each validation error and catch them precisely, avoiding generic Exception catches.
D.Wrap all exceptions in a single custom unchecked exception to simplify exception handling.
AnswerC

Precise catch reduces unnecessary handling and improves performance.

Why this answer

Option C is correct because catching generic `Exception` forces the JVM to build a full stack trace for every validation error, which is expensive in a high-throughput system. By defining specific custom checked exception classes and catching them precisely, the team reduces unnecessary stack trace generation and makes the code more maintainable by clearly documenting which errors are expected. This approach aligns with Java best practices for exception handling, improving both performance and code clarity without altering external behavior.

Exam trap

The trap here is that candidates often think wrapping all exceptions in a single unchecked exception simplifies code (Option D), but the exam tests the principle that precise exception handling improves both performance and maintainability, while broad catches or unchecked wrappers degrade them.

How to eliminate wrong answers

Option A is wrong because catching `Throwable` includes `Error` subclasses (e.g., `OutOfMemoryError`), which are irrecoverable and should not be caught or ignored; doing so can mask critical JVM failures and violate Java's exception hierarchy design. Option B is wrong because adding a try-catch around every method call that might throw an exception leads to excessive nesting, code duplication, and still does not address the root cause of generic `Exception` catches; it also degrades performance by adding unnecessary control flow overhead. Option D is wrong because wrapping all exceptions in a single custom unchecked exception (e.g., extending `RuntimeException`) eliminates compile-time checking, making it harder to handle specific validation errors and potentially hiding bugs; it also forces callers to either catch a broad type or let exceptions propagate unchecked, which is the opposite of maintainability.

196
MCQhard

Which is true about CopyOnWriteArrayList?

A.It is not thread-safe.
B.Iterators reflect concurrent modifications.
C.Modifications are expensive as they create a new array.
D.It is optimized for frequent modifications.
AnswerC

Each modification copies the underlying array.

Why this answer

CopyOnWriteArrayList is a thread-safe variant of ArrayList where all mutative operations (add, set, remove, etc.) are implemented by making a fresh copy of the underlying array. This design makes modifications expensive because each modification requires copying the entire array, but it provides safe iteration without locking. Option C correctly identifies that modifications are expensive due to the array copy.

Exam trap

The trap here is that candidates often assume 'thread-safe' collections like CopyOnWriteArrayList allow iterators to see concurrent modifications (like ConcurrentHashMap does), but CopyOnWriteArrayList iterators are snapshot-based and do not reflect modifications after creation.

How to eliminate wrong answers

Option A is wrong because CopyOnWriteArrayList is explicitly thread-safe; it uses a volatile reference and a copy-on-write strategy to ensure visibility and atomicity without external synchronization. Option B is wrong because iterators on CopyOnWriteArrayList reflect a snapshot of the array at the time the iterator was created; they do not see concurrent modifications after creation. Option D is wrong because CopyOnWriteArrayList is optimized for frequent reads and infrequent modifications; modifications are expensive due to array copying, so it is not optimized for frequent modifications.

197
MCQhard

A Java application uses FileChannel to copy a file to a remote network drive. The developer wants to ensure atomic file replacement on the destination. Which approach is correct?

A.Delete the destination file, then rename the temporary file.
B.Use Files.move() with StandardCopyOption.ATOMIC_MOVE.
C.Use FileChannel.transferTo() to write directly.
D.Use Files.copy() with REPLACE_EXISTING option.
AnswerB

Requests atomic move; throws exception if not supported.

Why this answer

Option B is correct because `Files.move()` with `StandardCopyOption.ATOMIC_MOVE` guarantees that the file replacement on the destination file system is atomic — either the entire move succeeds or the original state remains intact. This is essential for remote network drives where partial writes or concurrent access could leave the destination in an inconsistent state. The `ATOMIC_MOVE` option leverages file system–level atomic rename operations (e.g., NFS or SMB support) to ensure no intermediate state is visible.

Exam trap

The trap here is that candidates often assume `Files.copy()` with `REPLACE_EXISTING` or `FileChannel.transferTo()` provides atomicity because they replace the destination, but neither guarantees that the replacement is atomic — only `ATOMIC_MOVE` ensures the entire operation is indivisible at the file system level.

How to eliminate wrong answers

Option A is wrong because deleting the destination file and then renaming a temporary file is not atomic — a crash or concurrent access between the delete and rename can leave the destination missing or in an inconsistent state. Option C is wrong because `FileChannel.transferTo()` performs a direct, non-atomic copy that does not guarantee atomic replacement; it writes data in chunks and can leave a partial file on the destination if interrupted. Option D is wrong because `Files.copy()` with `REPLACE_EXISTING` replaces the destination file but does so as a non-atomic copy operation, meaning the destination may be overwritten partially or left in an inconsistent state if the copy fails.

198
MCQeasy

A developer creates a Java application that uses the new 'jpackage' tool to create an installer for Windows. The application is modular and has a main class declared in module-info. Which option is required to specify the main class when using jpackage?

A.-classpath
B.--module-path
C.--main-jar
D.--module
AnswerD

For modular applications, jpackage uses --module to specify the main module, and the application's main class is derived from the module descriptor.

Why this answer

For a modular application with a main class declared in module-info, jpackage requires the `--module` option to specify the module name and, optionally, the main class (e.g., `--module com.example/com.example.Main`). This is because jpackage uses the module system to resolve the entry point, not a classpath or JAR-based approach.

Exam trap

The trap here is that candidates confuse `--module` with `--module-path` or `--main-jar`, mistakenly thinking the main class must be specified via a JAR or classpath even when the module system already declares it.

How to eliminate wrong answers

Option A is wrong because `-classpath` is a legacy option for specifying class paths in non-modular applications, and jpackage does not support it for modular applications. Option B is wrong because `--module-path` is used to specify the location of module directories or JARs, not to declare the main class. Option C is wrong because `--main-jar` is used for non-modular applications packaged as JARs, not for modular applications where the main class is defined in module-info.

199
MCQmedium

Given an enum Direction { NORTH, SOUTH, EAST, WEST } and a variable d of type Direction, which code snippet correctly uses a switch expression to map each direction to an abbreviation (N, S, E, W) without using a default branch?

A.switch (d) { case NORTH -> "N"; case SOUTH -> "S"; case EAST -> "E"; case WEST -> "W"; }
B.switch (d) { case NORTH: yield "N"; case SOUTH: yield "S"; case EAST: yield "E"; case WEST: yield "W"; }
C.switch (d) { case NORTH -> "N"; case SOUTH -> "S"; case EAST -> "E"; }
D.switch (d) { case NORTH: yield "N"; case SOUTH: yield "S"; case EAST: yield "E"; default: yield "W"; }
AnswerA

Correct arrow syntax covering all enum values.

Why this answer

Option C is correct because it covers all enum constants with arrow cases, and no default is needed because the switch is exhaustive. Option A is wrong because it uses colon syntax and yields are not used correctly in switch expressions with colon syntax. Option B is wrong because it uses a default which is unnecessary and not allowed in exhaustive switch expressions? Actually default is allowed but not needed; however the question specifically says without using default.

Option D is wrong because it doesn't handle all constants, so it doesn't compile.

200
MCQmedium

A developer creates a module `com.example.app` that requires `java.sql` and `com.example.util`. The module is compiled and packaged into a JAR. When launching the application with `java --module-path app.jar:lib --module com.example.app`, it fails with `java.lang.module.ResolutionException: Module com.example.util not found`. What is the most likely cause?

A.The module `com.example.util` is an automatic module and requires specific flags.
B.The module `com.example.util` is not in the module path.
C.The module `com.example.util` is a named module but not exported.
D.The module `com.example.util` is on the classpath and not visible to module system.
AnswerB

The module path must include all required modules explicitly.

Why this answer

The error `Module com.example.util not found` indicates that the module system cannot locate `com.example.util` on the module path. Since the command specifies `--module-path app.jar:lib`, the JAR for `com.example.util` must be present in the `lib` directory (or another directory on that path). If it is missing or not in the correct location, the module resolution fails.

Option B correctly identifies that the module is simply not on the module path.

Exam trap

Oracle often tests the distinction between module resolution failures (missing module) and access control failures (module found but not exported), so candidates may incorrectly choose an option about exports or classpath visibility when the actual issue is that the module JAR is simply not present on the module path.

How to eliminate wrong answers

Option A is wrong because automatic modules do not require special flags to be found; they are resolved automatically when placed on the module path. Option C is wrong because a named module that is not exported would cause an `IllegalAccessError` at runtime, not a `ResolutionException` at startup. Option D is wrong because placing a module on the classpath makes it invisible to the module system for `requires` directives; the module system only resolves modules from the module path, not the classpath.

201
Multi-Selectmedium

Which TWO are valid ways to create an immutable list in Java 17? (Choose two.)

Select 2 answers
A.Arrays.asList("a", "b")
B.List.of(List.of("a", "b"))
C.Collections.unmodifiableList(new ArrayList<>(List.of("a", "b")))
D.List.copyOf(Arrays.asList("a", "b"))
E.new ArrayList<>(List.of("a", "b"))
AnswersC, D

Wraps list to be unmodifiable.

Why this answer

Option C is correct because `Collections.unmodifiableList()` wraps a mutable list in an unmodifiable view, preventing any structural modifications. Option D is correct because `List.copyOf()` creates an immutable list from an existing collection, throwing `NullPointerException` if any element is null. Both produce lists that cannot be modified after creation.

Exam trap

Oracle often tests the distinction between an unmodifiable view (which can be circumvented if the backing list is accessible) and a truly immutable list (which cannot be changed by any means), and candidates mistakenly think `Arrays.asList()` or `new ArrayList<>()` are immutable.

202
Multi-Selecthard

Which TWO statements about the try-with-resources statement are correct? (Choose two.)

Select 2 answers
A.The resource class must implement AutoCloseable.
B.The resource variable must be declared as final.
C.Resources are closed in the reverse order of their declaration.
D.A try-with-resources statement cannot have a finally block.
E.Resources are closed before the try block executes.
AnswersA, C

Correct: only AutoCloseable resources are allowed.

Why this answer

Option A is correct because the try-with-resources statement requires that each resource implements the AutoCloseable interface (or its subinterface Closeable). This interface defines the close() method, which is automatically invoked by the JVM when the try block completes, ensuring proper resource management without explicit finally blocks.

Exam trap

The trap here is that candidates often think resources must be declared with the final keyword (Option B) or that finally blocks are prohibited (Option D), but the exam tests the exact JLS rules: resources are effectively final, and finally blocks are allowed but execute after resource closure.

203
MCQeasy

What happens when a finally block throws an exception?

A.The JVM logs both exceptions and then terminates the thread.
B.The exception from the try block is propagated and the finally exception is ignored.
C.Both exceptions are reported as suppressed exceptions of a new exception.
D.The exception from the try block is suppressed and the finally exception is reported.
AnswerD

The exception from finally takes precedence, the try exception is lost unless caught as suppressed.

Why this answer

Option D is correct because when a finally block throws an exception, the JVM suppresses the exception that was thrown from the try block (if any) and propagates the exception thrown from the finally block. This behavior is defined in the Java Language Specification (JLS §14.20.2) and ensures that the finally block's exception takes precedence, as the finally block is executed after the try block completes abruptly.

Exam trap

The trap here is that candidates often assume both exceptions are lost or that the try-block exception always propagates, but the Java Language Specification mandates that the finally-block exception takes precedence, with the try-block exception being suppressed.

How to eliminate wrong answers

Option A is wrong because the JVM does not log both exceptions and terminate the thread; instead, it suppresses the try-block exception and propagates the finally-block exception. Option B is wrong because the exception from the try block is not propagated; it is suppressed, and the finally exception is reported instead. Option C is wrong because both exceptions are not reported as suppressed exceptions of a new exception; only the try-block exception is suppressed, and the finally-block exception is the one thrown, with the try-block exception added as a suppressed exception to the finally-block exception (if the finally-block exception is a subtype of Throwable that supports suppression).

204
Multi-Selecthard

Which two of the following are valid ways to create a LocalDate representing the current date in the system's default timezone? (Choose two.)

Select 2 answers
A.LocalDate.from(Instant.now())
B.new LocalDate()
C.LocalDate.now()
D.LocalDate.ofEpochDay(System.currentTimeMillis() / (24*60*60*1000))
E.LocalDate.ofInstant(Instant.now(), ZoneId.systemDefault())
AnswersC, E

Correct: Uses the system's default timezone.

Why this answer

Option C is correct because `LocalDate.now()` is the standard, straightforward method to obtain the current date in the system's default timezone, as defined in the Java Time API (JSR-310). It internally uses the system clock and the default timezone to return a `LocalDate` instance without requiring any additional parameters.

Exam trap

The trap here is that candidates often assume `LocalDate.from(Instant.now())` should work because both are date/time types, but they fail to recognize that `Instant` lacks timezone and date fields, causing a runtime exception, while `new LocalDate()` is a common misconception from other Java classes that have public constructors.

205
MCQmedium

Given the exhibit showing a compilation error at line 5 of Test.java, which of the following code fragments could be at that line?

A.FileInputStream fis = new FileInputStream("test.txt");
B.int x = 5;
C.try { ... } catch (Exception e) { }
D.System.out.println("Hello");
AnswerA

FileInputStream constructor throws FileNotFoundException (subclass of IOException).

Why this answer

Option A is correct because the code at line 5 is a checked exception (FileNotFoundException) that must be handled or declared. The compilation error indicates that the method containing line 5 does not handle or declare this checked exception, which is required by the Java compiler.

Exam trap

The trap here is that candidates often forget that checked exceptions must be handled or declared, and mistakenly think any code that throws an exception will compile as long as it is inside a method, ignoring the compiler's requirement for checked exception handling.

How to eliminate wrong answers

Option B is wrong because assigning an int literal to a variable does not throw any checked exception and would not cause a compilation error at line 5. Option C is wrong because a try-catch block is syntactically valid and would not cause a compilation error on its own; the error is likely due to an unhandled checked exception inside the try block, not the catch clause itself. Option D is wrong because printing a string literal does not throw any checked exception and would compile without error.

206
MCQmedium

A team implements a stream pipeline that processes a large dataset in parallel. They use a stateful lambda expression inside the map operation to maintain a count. What is the most likely outcome?

A.The pipeline will produce correct results if the stateful lambda is synchronized.
B.The pipeline will produce non-deterministic results due to race conditions.
C.The pipeline will throw a ConcurrentModificationException.
D.The pipeline will always produce the same result regardless of parallelism.
AnswerB

Stateful lambdas in parallel streams are discouraged because they introduce shared mutable state that leads to race conditions and unpredictable results.

Why this answer

Option B is correct because using a stateful lambda (one that mutates shared mutable state) inside a parallel stream's map operation introduces race conditions. The map operation is intended to be stateless and non-interfering; when multiple threads concurrently update a shared counter without proper synchronization, the result becomes non-deterministic and unpredictable.

Exam trap

The trap here is that candidates assume synchronization or thread-safety fixes the issue, but the Streams API's contract requires stateless lambdas for correctness in parallel pipelines, and synchronization does not restore deterministic behavior or guarantee correct results.

How to eliminate wrong answers

Option A is wrong because even if the stateful lambda is synchronized, the synchronization will cause severe contention and may still produce incorrect results if the lambda is not properly thread-safe or if the ordering of updates is not guaranteed; the Java Streams API explicitly discourages stateful lambdas in parallel pipelines. Option C is wrong because ConcurrentModificationException is thrown when a collection is structurally modified while being iterated, not from a stateful lambda in a map operation that merely updates a counter. Option D is wrong because the pipeline will not always produce the same result; the non-determinism arises from the unpredictable interleaving of thread updates to the shared mutable state.

207
Multi-Selecthard

Which three of the following statements about the switch expression in Java 17 are correct?

Select 3 answers
A.A switch expression with arrow syntax does not require break.
B.A switch expression with colon syntax can use yield to return a value.
C.A switch expression cannot be used with an enum type.
D.A switch expression must include a default branch even if all cases are covered.
E.A switch expression must be exhaustive.
AnswersA, B, E

Arrow syntax implicitly prevents fall-through, so break is unnecessary.

Why this answer

Option A is correct because in a switch expression with arrow syntax (->), each branch is a single expression or block that is automatically terminated, eliminating the need for a break statement. The arrow syntax implicitly prevents fall-through, making the code more concise and less error-prone.

Exam trap

The trap here is that candidates often confuse the requirement for a default branch in switch expressions with the behavior of switch statements, mistakenly thinking a default is always mandatory even when all cases are covered.

208
MCQhard

A financial application processes transactions in batches. Each transaction is represented as a Transaction object with fields: long id, BigDecimal amount, LocalDateTime timestamp. Transactions are stored in a List<Transaction> in the order they arrive. The system needs to frequently check if a transaction with a specific id exists, and also needs to iterate through transactions in chronological order. The list currently contains millions of transactions, and the existence check is becoming a performance bottleneck because it currently uses a linear search. The system must also maintain insertion order for iteration. Which approach best improves the performance of the existence check while maintaining the required iteration order?

A.Keep List<Transaction> and add a separate HashSet<Long> of ids for fast lookup. Use the list for iteration.
B.Replace List<Transaction> with LinkedHashMap<Long, Transaction> mapping id to transaction. Iterate using values() which preserves insertion order.
C.Keep List<Transaction> and sort it by id. Use Collections.binarySearch() for lookup.
D.Replace List<Transaction> with TreeMap<Long, Transaction> mapping id to transaction. Iterate using values() which returns in natural key order.
AnswerB

LinkedHashMap provides O(1) lookup and maintains insertion order.

Why this answer

Option B is correct because LinkedHashMap maintains insertion order for iteration via its values() view, while providing O(1) key-based lookup for the existence check. This directly addresses the performance bottleneck of linear search in a List without sacrificing the required chronological iteration order.

Exam trap

The trap here is that candidates may confuse TreeMap's natural ordering with insertion order, or assume that sorting a List and using binary search is the best optimization, overlooking the O(1) lookup advantage of hash-based structures like LinkedHashMap.

How to eliminate wrong answers

Option A is wrong because it introduces a separate HashSet<Long> for fast lookup, but this requires manual synchronization to keep the set and list consistent, and the existence check still needs to search the list if the set is not maintained correctly; it adds complexity without a built-in guarantee of order preservation. Option C is wrong because sorting a List by id and using binary search provides O(log n) lookup, which is slower than O(1) hash-based lookup, and sorting by id does not preserve insertion order for iteration unless the list is re-sorted after each addition, which is inefficient. Option D is wrong because TreeMap iterates in natural key order (sorted by id), not insertion order, which violates the requirement to iterate in chronological order.

209
MCQhard

A stream pipeline uses groupingBy with a downstream collector to count occurrences. The developer expects a Map<Integer, Long> but gets a compilation error. Which is the correct way to write the collector?

A.Collectors.toMap(Function.identity(), e -> 1L, Long::sum)
B.Collectors.groupingBy(Function.identity(), Collectors.count())
C.Collectors.groupingBy(Function.identity(), Collectors.counting())
D.Collectors.groupingBy(Function.identity(), Collectors.summingLong(e -> 1))
AnswerC

Correct: groupingBy with counting() returns Map<Integer, Long>.

Why this answer

Collectors.groupingBy(Function, Collectors.counting()) returns a Map<K, Long>.

210
MCQhard

A team is developing a real-time data processing pipeline that reads sensor data from a message queue. The pipeline uses a flatMap operation that calls an external geocoding service for each sensor reading. The external service has a rate limit of 10 requests per second and is slow (150ms average response time). The current code: sensorStream.parallelStream() .flatMap(reading -> getGeocode(reading).stream()) .forEach(system.out::println); The application is overloaded because parallel stream fires many concurrent requests, exceeding the rate limit and causing failures. They need to process all sensor data but must respect the rate limit. Which approach should they use?

A.Use a sequential stream with a custom rate limiter (e.g., a semaphore) that blocks when the limit is reached.
B.Reduce the parallelism level by using a custom thread pool with a fixed number of threads.
C.Use filter to drop some sensor readings to reduce the load.
D.Use a sequential stream and hope the processing completes within the time window.
AnswerA

A sequential stream combined with a rate limiter ensures requests are sent at a controlled pace, respecting the external service limits.

Why this answer

Option D is correct because using a sequential stream with a controlled batch size and throttling via a rate limiter (like a semaphore or Guava's RateLimiter) is the only way to reliably respect the external service's rate limit while not losing data. Options A and B only reduce parallelism but do not enforce a specific rate. Option C is wrong because it discards data.

211
MCQeasy

Which of the following correctly uses try-with-resources to ensure a FileInputStream is closed after use?

A.FileInputStream fis = new FileInputStream("file.txt"); try { ... } finally { fis.close(); }
B.try (FileInputStream fis = new FileInputStream("file.txt")) { ... }
C.try { FileInputStream fis = new FileInputStream("file.txt"); ... } finally { fis.close(); }
D.try (fis = new FileInputStream("file.txt")) { ... }
AnswerB

Correct syntax; resource is closed automatically.

Why this answer

Option B is correct because it uses the try-with-resources syntax (try (resource declaration) { ... }), which automatically closes the FileInputStream when the block exits, regardless of exceptions. This ensures the resource is closed without requiring an explicit finally block, as mandated by the AutoCloseable interface.

Exam trap

The trap here is that candidates often forget that try-with-resources requires the resource variable to be declared with its type inside the parentheses, and they mistakenly think a pre-declared variable or a variable without a type declaration is valid.

How to eliminate wrong answers

Option A is wrong because it uses a traditional try-finally block without try-with-resources, requiring manual close() call and risking resource leaks if an exception occurs before the finally block. Option C is wrong because it declares the FileInputStream inside the try block, making it inaccessible in the finally block for closing, leading to a compilation error. Option D is wrong because it omits the resource type declaration (FileInputStream) in the try-with-resources header, causing a compilation error as the variable must be declared with its type.

212
MCQeasy

A Java application packaged as a JAR file with a manifest containing `Main-Class: com.example.Main` is correctly run using `java -jar app.jar`. However, when run with `java -cp app.jar com.example.Main`, it throws a `NoClassDefFoundError` for a class `com.example.helper.Util`. What is the most likely cause?

A.The Util class is missing from the JAR.
B.The JAR's manifest Class-Path entry is not being honored when using -cp.
C.The -jar option automatically adds the JAR's dependencies to the classpath.
D.The main class name is misspelled.
AnswerB

When using -cp, the Class-Path from manifest is ignored; you must explicitly include dependencies.

Why this answer

When using `java -jar`, the JVM reads the manifest's `Class-Path` entry to locate dependencies. However, when using `-cp` (or `-classpath`), the manifest's `Class-Path` is ignored; the classpath is determined solely by the `-cp` argument. Since `com.example.helper.Util` is not on the explicit classpath, a `NoClassDefFoundError` occurs.

This is a fundamental difference in how the JVM resolves classpaths between the two launch modes.

Exam trap

Oracle often tests the misconception that the manifest's `Class-Path` is always honored regardless of how the JAR is launched, when in fact `-cp` completely overrides it.

How to eliminate wrong answers

Option A is wrong because if the Util class were missing from the JAR, the error would occur with both `-jar` and `-cp`; the fact that `-jar` works proves the class is present. Option C is wrong because `-jar` does not automatically add dependencies to the classpath; it only uses the manifest's `Class-Path` entries, which are not transitive or automatic. Option D is wrong because a misspelled main class would cause a `NoClassDefFoundError` for the main class itself, not for a helper class, and the question states the main class is correctly specified.

213
MCQeasy

A lambda expression that takes two integers and returns a boolean indicating whether the first is greater than the second is best represented by which functional interface?

A.BiFunction<Integer, Integer, Boolean>
B.Predicate<Integer>
C.BinaryOperator<Boolean>
D.BiPredicate<Integer, Integer>
AnswerD

Correct. BiPredicate<Integer, Integer> is the functional interface for two input arguments returning a boolean.

Why this answer

BiPredicate is designed for two arguments and returns a boolean. Option B correctly identifies this.

214
Multi-Selecteasy

Which TWO access modifiers can be applied to a top-level class in Java? (Choose two.)

Select 2 answers
A.static
B.package-private (no modifier)
C.protected
D.private
E.public
AnswersB, E

Top-level classes can have default access.

Why this answer

In Java, a top-level class can only have two access modifiers: public or package-private (no modifier). Package-private is the default access level when no modifier is specified, allowing the class to be accessible only within its own package. This is defined by the Java Language Specification (JLS §8.1.1).

Exam trap

Oracle often tests the misconception that static or protected can be applied to top-level classes, confusing them with modifiers for nested classes or class members, which is a common trap in Java access modifier questions.

215
MCQhard

Refer to the exhibit. A security policy file is configured as shown. The application in app.jar tries to read a file named "${user.home}/data/db.properties". What is the result?

A.Access is denied because the FilePermission for data files is missing.
B.Access is denied because app.jar's AllPermission is not sufficient.
C.Access is allowed because the first grant includes read permission for logs/-, which covers data.
D.Access is allowed because app.jar has AllPermission.
AnswerD

AllPermission overrides any restrictions.

Why this answer

Option D is correct because the security policy grants AllPermission to app.jar, which supersedes any specific file permissions. AllPermission implies every possible permission, including read access to any file, regardless of path restrictions. Therefore, the application can read '${user.home}/data/db.properties' without denial.

Exam trap

The trap here is that candidates focus on the specific FilePermission grants and miss that AllPermission in the second grant renders all other permission checks irrelevant, leading them to incorrectly choose options based on path mismatches.

How to eliminate wrong answers

Option A is wrong because the FilePermission for data files is irrelevant when AllPermission is granted; AllPermission overrides all specific permission checks. Option B is wrong because AllPermission is the most powerful permission in the Java security model, granting all access rights, so it is sufficient for any operation. Option C is wrong because the first grant's read permission for logs/- does not cover the data directory; 'logs/-' only applies to files under the logs directory, not 'data/db.properties', but this is moot due to AllPermission.

216
MCQmedium

A developer uses a parallel stream to process a large collection and wants to collect results into a List while preserving encounter order. Which of the following collectors will guarantee order preservation?

A.collect(Collectors.toUnmodifiableList())
B.collect(Collectors.toList())
C.collect(Collectors.toMap(Function.identity(), v->v))
D.collect(ArrayList::new, List::add, List::addAll)
E.collect(Collectors.toCollection(TreeSet::new))
AnswerD

This custom collector preserves encounter order because it adds elements sequentially in the accumulator and merges lists in order.

Why this answer

A custom collector using ArrayList::new, List::add, and List::addAll preserves insertion order even in parallel streams. Other collectors may not guarantee order.

217
Multi-Selecthard

Which TWO statements are true about the Stream API and lambda expressions in Java 17?

Select 2 answers
A.The Stream API does not modify the original data source.
B.Lambda expressions can capture variables that are effectively final.
C.A stream can be consumed by multiple terminal operations sequentially.
D.Intermediate operations on a stream are executed eagerly.
E.Lambda expressions introduce a new level of scope, similar to an anonymous inner class.
AnswersA, B

Streams operate on a view of the data; they do not modify the underlying collection or array.

Why this answer

Option A is correct because the Stream API is designed to work on a view of the data, not the data itself. Operations like filter, map, and collect produce new streams or results without altering the original collection, array, or I/O source. This non-interference guarantee is a core principle of the Stream API, ensuring safe parallel execution and functional programming style.

Exam trap

The trap here is that candidates often confuse the lazy evaluation of intermediate operations with eager execution, or mistakenly believe a stream can be reused after a terminal operation, leading them to select options C or D.

218
Multi-Selecteasy

Which TWO of the following are unchecked exceptions? (Choose two.)

Select 2 answers
A.SQLException
B.Exception
C.NullPointerException
D.ArrayIndexOutOfBoundsException
E.IOException
AnswersC, D

Unchecked runtime exception.

Why this answer

NullPointerException (option C) is an unchecked exception because it extends RuntimeException, which means it is not checked at compile time. The Java compiler does not require you to handle or declare NullPointerException, making it an unchecked exception.

Exam trap

The trap here is that candidates often confuse 'Exception' (the superclass) as unchecked, but Exception itself is a checked exception; only RuntimeException and its subclasses are unchecked.

219
Multi-Selecthard

Which THREE statements are true about the enhanced for loop in Java?

Select 3 answers
A.If the underlying collection is modified during iteration, the loop will continue without error.
B.The enhanced for loop internally uses an iterator for collections.
C.The enhanced for loop can iterate over arrays.
D.The loop variable cannot be modified inside the loop body.
E.The loop variable must be declared final in the loop header.
AnswersB, C, D

For Iterable objects, it uses Iterator.

Why this answer

Option B is correct because the enhanced for loop (for-each) over a collection internally uses an Iterator obtained from the collection's iterator() method. This is specified in the Java Language Specification (JLS 14.14.2) and is the mechanism that allows sequential access to each element without exposing the iterator directly.

Exam trap

The trap here is that candidates often confuse the enhanced for loop's inability to modify the loop variable with a requirement to declare it final, or they mistakenly believe that structural modifications during iteration are safe.

220
MCQmedium

Given two named modules where module com.example.app requires module com.example.lib, which packages of com.example.lib are readable by com.example.app?

A.All packages except those explicitly concealed
B.All packages of com.example.lib
C.Only the packages opened by com.example.lib
D.Only the packages exported by com.example.lib
AnswerD

A module reads only exported packages of required modules.

Why this answer

Option D is correct because in the Java module system, a module can only access packages from another module that are explicitly exported using the `exports` directive in the module's `module-info.java` file. Since `com.example.app` requires `com.example.lib`, only the packages exported by `com.example.lib` are readable; unexported packages remain encapsulated and inaccessible.

Exam trap

The trap here is that candidates confuse `opens` with `exports`, thinking that opening a package for reflection also makes it readable, but `opens` only grants reflective access and does not allow compile-time or direct read access.

How to eliminate wrong answers

Option A is wrong because the Java module system does not have a concept of 'concealed' packages; instead, packages are either exported or not, and all non-exported packages are implicitly encapsulated. Option B is wrong because requiring a module does not grant access to all its packages; only those explicitly exported are readable. Option C is wrong because 'opened' packages (via the `opens` directive) are for deep reflection at runtime, not for compile-time or read access; readability requires `exports`, not `opens`.

221
MCQeasy

You are developing a microservice that processes financial transactions. The service reads transaction data from a message queue, validates it, and writes results to a database. The code uses a try-with-resources statement to manage database connections. During testing, you notice that when a transaction fails validation, the service throws an IllegalStateException before closing the database connection, causing a resource leak. You need to ensure that the database connection is always closed properly, even if an exception is thrown during validation. The current code structure is: try (Connection conn = DriverManager.getConnection(url, user, pass)) { // read from queue // validate transaction // if invalid, throw new IllegalStateException("Invalid transaction"); // write to database } Which course of action would you recommend?

A.Move the connection creation outside the try-with-resources to manually manage it.
B.No change is needed; the try-with-resources ensures the connection is closed.
C.Replace the try-with-resources with a try-catch-finally block and close the connection in the finally block.
D.Add a catch block to catch the IllegalStateException and close the connection.
AnswerB

try-with-resources automatically closes the resource, even if an exception is thrown.

Why this answer

Option B is correct because try-with-resources automatically closes any resource that implements AutoCloseable (including Connection) when the try block exits, whether normally or via an exception. The IllegalStateException thrown during validation does not prevent the connection from being closed; the close() method is called as part of the implicit finally block generated by the compiler.

Exam trap

The trap here is that candidates mistakenly think an uncaught exception bypasses resource cleanup, but try-with-resources guarantees closure regardless of how the block exits, including exceptions.

How to eliminate wrong answers

Option A is wrong because moving the connection outside try-with-resources would require manual management and increase the risk of resource leaks if an exception occurs before the manual close. Option C is wrong because replacing try-with-resources with a try-catch-finally block is unnecessary and less concise; try-with-resources already guarantees closure without explicit finally code. Option D is wrong because adding a catch block to close the connection is redundant and could lead to double-close issues; try-with-resources handles closure automatically even without a catch.

222
Multi-Selecthard

Which THREE of the following are valid ways to create an infinite stream? (Choose three.)

Select 3 answers
A.IntStream.generate(() -> 0)
B.Stream.iterate(1, n -> n+1)
C.IntStream.range(0, Integer.MAX_VALUE)
D.Stream.generate(Math::random)
E.Stream.of(1,2,3)
AnswersA, B, D

Generates an infinite IntStream of zeros.

Why this answer

Option A is correct because `IntStream.generate(() -> 0)` uses a supplier that always returns 0, producing an infinite stream of zeros. The `generate` method creates an unordered infinite stream by repeatedly invoking the supplier, with no termination condition.

Exam trap

The trap here is that candidates mistakenly think `IntStream.range(0, Integer.MAX_VALUE)` is infinite because the upper bound is large, but it is actually a finite stream that terminates after producing Integer.MAX_VALUE elements.

Page 2

Page 3 of 7

Page 4

All pages