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

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

Page 5

Page 6 of 7

Page 7
376
MCQmedium

A method receives an InputStream and needs to compute its MD5 hash while reading the data. Which approach is most efficient?

A.Use DigestInputStream wrapping the original stream, then read the stream
B.Read all bytes into a byte array, then compute hash using MessageDigest
C.Use a custom filter that hashes bytes during read
D.Use Scanner to read tokens and update hash
AnswerA

DigestInputStream computes the hash as data is read, requiring no additional memory.

Why this answer

Option A is correct because `DigestInputStream` is a built-in Java class that computes a message digest (e.g., MD5) on the fly as data is read from the underlying stream. This avoids buffering the entire stream into memory, making it both memory-efficient and CPU-efficient for large or streaming data sources.

Exam trap

The trap here is that candidates may assume reading all bytes into memory first (Option B) is simpler or more straightforward, overlooking the memory and performance implications for large streams, and fail to recognize that `DigestInputStream` is the standard, efficient solution in the Java I/O API.

How to eliminate wrong answers

Option B is wrong because reading all bytes into a byte array before computing the hash requires O(n) memory, which is inefficient for large streams and may cause OutOfMemoryError. Option C is wrong because implementing a custom filter that hashes bytes during read is redundant and error-prone; `DigestInputStream` already provides this exact functionality with a well-tested, optimized implementation. Option D is wrong because `Scanner` is designed for tokenizing text input, not for binary hashing, and using it would introduce unnecessary overhead and potential data corruption for binary streams.

377
MCQeasy

A developer places a non-modular JAR file on the module path. What type of module does this JAR become?

A.Open module
B.Named module
C.Automatic module
D.Unnamed module
AnswerC

A JAR on the module path without module-info becomes an automatic module.

Why this answer

When a non-modular JAR is placed on the module path, the Java module system automatically derives a module from it, known as an automatic module. This is because the JAR lacks a module-info.class, so the system infers a module name from the JAR filename (e.g., using the Main-Class attribute or the JAR's name) and exports all packages, giving it access to all other modules. Option C is correct because the JAR becomes an automatic module, not a named or unnamed module.

Exam trap

The trap here is that candidates confuse the module path with the classpath, mistakenly thinking a non-modular JAR on the module path becomes an unnamed module, when in fact it becomes an automatic module with special privileges like reading all other modules.

How to eliminate wrong answers

Option A is wrong because an open module is a named module that explicitly uses the 'open' keyword in its module-info.java to allow deep reflection at runtime, which is not applicable to a non-modular JAR. Option B is wrong because a named module requires a module-info.class file (either compiled from module-info.java or a module-info.class in the JAR), which a non-modular JAR does not have. Option D is wrong because an unnamed module is created when a JAR is placed on the classpath, not the module path; placing a JAR on the module path triggers automatic module creation, not unnamed module behavior.

378
MCQhard

Given the above Java version, which of the following is NOT a standard Java 17 feature?

A.All of the above are standard
B.Sealed classes
C.Text blocks
D.Pattern matching for switch (preview)
E.Records
AnswerD

Correct: This is a preview feature in Java 17, not standard.

Why this answer

Option D is correct because pattern matching for switch is a preview feature in Java 17, not a standard feature. It was introduced as a preview under JEP 406 and requires the --enable-preview flag to be used. Standard features in Java 17 are finalized and do not require any preview flags.

Exam trap

The trap here is that candidates may assume pattern matching for switch is a standard feature because it is widely discussed and similar to other finalized features like records or sealed classes, but Oracle deliberately kept it in preview in Java 17 to test further refinements.

How to eliminate wrong answers

Option A is wrong because it claims all options are standard, but D is a preview feature, so A is false. Option B is wrong because sealed classes are a standard feature in Java 17 (JEP 409), finalized and available without flags. Option C is wrong because text blocks are a standard feature since Java 15 (JEP 378), fully supported in Java 17.

Option E is wrong because records are a standard feature since Java 16 (JEP 395), finalized and included in Java 17.

379
Multi-Selecteasy

Which TWO are terminal operations on the Stream interface? (Choose two.)

Select 2 answers
A.count()
B.forEach()
C.filter()
D.map()
E.sorted()
AnswersA, B

Terminal operation that returns the count of elements.

Why this answer

A is correct because `count()` is a terminal operation that reduces the stream to a single `long` value by counting the number of elements after processing the pipeline. It triggers the stream pipeline execution and consumes the stream, making it a terminal operation per the `Stream` interface specification.

Exam trap

The trap here is that candidates often confuse intermediate operations (like `filter`, `map`, `sorted`) with terminal operations because they are commonly chained together, but only terminal operations produce a non-stream result or side effect and close the stream.

380
MCQhard

An application deserializes objects from a network stream. To protect against deserialization attacks, which approach is most effective in Java 17?

A.Declare all fields as transient
B.Set an ObjectInputFilter on the ObjectInputStream
C.Use try-with-resources to auto-close the stream
D.Mark the class as final
AnswerB

Allows rejection of classes based on criteria, preventing attacks.

Why this answer

Option B is correct because setting an ObjectInputFilter on the ObjectInputStream allows you to define a filter that can reject deserialization of arbitrary or malicious classes, which is the primary defense against deserialization attacks. This mechanism, introduced in Java 9 and enhanced in later versions, lets you whitelist or blacklist classes based on patterns, limits on array sizes, or depth of object graphs, directly mitigating the risk of remote code execution or denial-of-service via crafted serialized data.

Exam trap

Oracle often tests the misconception that making fields transient or closing streams properly is sufficient to prevent deserialization attacks, when in reality the core vulnerability lies in the deserialization process itself, which must be actively filtered.

How to eliminate wrong answers

Option A is wrong because declaring all fields as transient prevents their serialization but does not protect against deserialization of malicious data; the attacker can still trigger the deserialization process and exploit the constructor or readObject method of the class. Option C is wrong because try-with-resources ensures the stream is closed after use, which is good resource management but does not inspect or filter the incoming serialized data, leaving the application vulnerable to attacks. Option D is wrong because marking a class as final prevents subclassing but does not restrict which classes can be deserialized; an attacker can still deserialize any class that implements Serializable, including final ones.

381
MCQhard

A company's Java application processes time-sensitive data from IoT sensors. The system must handle timestamps across multiple time zones. The application runs on a server set to UTC. Developers have been using java.util.Date and SimpleDateFormat for date parsing. Recently, there have been intermittent failures where timestamps from sensors in the America/New_York time zone are parsed incorrectly around daylight saving time transitions. Specifically, during the spring forward (March 12, 2023, at 2:00 AM EST to 3:00 AM EDT), timestamps like "2023-03-12 02:30:00" are being interpreted as times that do not exist, causing DateTimeParseException. The team decides to migrate to the java.time API. They need to parse sensor timestamps that include a time zone offset (e.g., "2023-03-12 02:30:00 -05:00") into an OffsetDateTime. Which course of action correctly parses the timestamp and handles the DST issue?

A.Use LocalDateTime.parse(timestamp, formatter) and then apply a ZoneOffset.
B.Use ZonedDateTime.parse(timestamp, formatter) with a formatter that includes time zone ID, then convert to OffsetDateTime.
C.Use DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX") and OffsetDateTime.parse(timestamp, formatter).
D.Keep using SimpleDateFormat but set the time zone of the parser to America/New_York.
AnswerC

Correctly parses a timestamp with offset into OffsetDateTime, avoiding DST ambiguity.

Why this answer

Option C is correct because the timestamp includes an explicit offset (-05:00), which makes it directly parseable into an OffsetDateTime using a DateTimeFormatter with the XXX pattern for the offset. OffsetDateTime.parse() handles the offset directly without any DST ambiguity, as the offset is explicitly provided in the string, avoiding the nonexistent time issue during spring-forward transitions.

Exam trap

The trap here is that candidates may think ZonedDateTime is always needed for time zone handling, but when the timestamp includes an explicit offset rather than a zone ID, OffsetDateTime is the correct and simpler choice to avoid DST-related parsing issues.

How to eliminate wrong answers

Option A is wrong because LocalDateTime.parse() does not parse an offset; it would ignore the offset or fail, and applying a ZoneOffset afterward would not resolve the DST ambiguity since LocalDateTime has no time zone context. Option B is wrong because ZonedDateTime.parse() expects a time zone ID (e.g., 'America/New_York') in the string, not an offset; using a formatter with an offset pattern would not match a zone ID, causing a parse error. Option D is wrong because SimpleDateFormat with a fixed time zone still relies on lenient parsing that can silently map nonexistent times (like 02:30:00 on spring-forward day) to a different moment, leading to incorrect data rather than an exception.

382
MCQmedium

A Java team is processing a large dataset with parallel streams. They notice inconsistent results due to non-atomic operations on shared mutable state. Which approach should they use to ensure thread-safety while maximizing performance?

A.Use the collect method with a concurrent Collector such as toConcurrentMap().
B.Use forEach with AtomicInteger and update atomically.
C.Use synchronized blocks inside the lambda expression.
D.Use ConcurrentHashMap for accumulation, but collect using toList().
AnswerA

Concurrent Collectors are designed for parallel reduction, using internal synchronization and efficient merging.

Why this answer

Option C is correct because using a concurrent Collector (like toConcurrentMap or groupingByConcurrent) ensures both thread-safety and efficiency in parallel processing. Option A is wrong because synchronized blocks inside lambdas can cause contention and undermine parallelism. Option B is wrong because ConcurrentHashMap alone does not guarantee atomicity of compound operations.

Option D is wrong because forEach with AtomicInteger still requires careful coordination and may not be optimal.

383
MCQmedium

A developer is writing a method that reads a file and processes its content. The method must ensure that if an IOException occurs during reading, the method throws a custom ApplicationException that wraps the original IOException, and that any resources opened are closed properly. Which approach correctly implements this requirement?

A.try { ... } catch (IOException e) { System.err.println(e); } finally { reader.close(); }
B.catch (Exception e) { throw new ApplicationException(e); } finally { reader.close(); }
C.try (BufferedReader reader = Files.newBufferedReader(path)) { ... } catch (IOException e) { throw new ApplicationException(e); }
D.try { ... reader.close(); } catch (IOException e) { throw new ApplicationException(e); }
AnswerC

Uses try-with-resources for automatic closure and wraps only IOException.

Why this answer

Option C is correct because it uses a try-with-resources statement, which automatically closes the BufferedReader (which implements AutoCloseable) when the block exits, whether normally or exceptionally. The catch clause then catches any IOException and wraps it in a custom ApplicationException, satisfying both the resource-closing and exception-wrapping requirements without manual cleanup.

Exam trap

The trap here is that candidates often think a finally block is required for resource cleanup, but the try-with-resources statement handles it automatically, and they may overlook that placing close() in the try block (as in D) does not guarantee execution if an exception occurs before that line.

How to eliminate wrong answers

Option A is wrong because it only prints the IOException to stderr instead of wrapping it in an ApplicationException, and it manually closes the reader in a finally block, which is error-prone if reader is null or close() throws another exception. Option B is wrong because it catches Exception (too broad) and lacks a try block, making it syntactically invalid; also, it does not ensure resources are closed properly. Option D is wrong because it places reader.close() inside the try block before the catch, meaning if an IOException occurs during reading, close() may not be executed, and if close() itself throws an IOException, it is not handled correctly.

384
Multi-Selectmedium

Which THREE are benefits of using the NIO.2 API over the java.io API?

Select 3 answers
A.Better performance for all I/O operations compared to java.io.
B.Simplified recursive file operations using FileVisitor.
C.Access to file attributes like creation time, owner, and permissions.
D.Automatic file compression when writing.
E.Support for symbolic links and other file system features.
AnswersB, C, E

walkFileTree and SimpleFileVisitor simplify recursive traversal.

Why this answer

Option B is correct because the NIO.2 API introduces the `FileVisitor` interface, which simplifies recursive file operations by allowing you to implement methods like `preVisitDirectory`, `visitFile`, and `visitFileFailed` that are automatically called during a tree walk. This eliminates the need for manual recursion and boilerplate code required in the `java.io` API, making directory traversal more efficient and less error-prone.

Exam trap

The trap here is that candidates assume NIO.2 always outperforms `java.io` (Option A) or conflate its channel-based I/O with automatic compression (Option D), when the exam specifically tests understanding of NIO.2's unique file system features like `FileVisitor`, symbolic links, and attribute access.

385
MCQmedium

Refer to the exhibit. Assuming the application is running from /home/application/lib/myapp.jar, which of the following actions is allowed by the policy?

A.All of the above
B.Write to the file /var/log/app.log
C.Queue a print job using the system printer
D.Read the file /etc/config/application.properties
AnswerA

All three actions are explicitly granted by the policy.

Why this answer

The policy grants all permissions (java.security.AllPermission) to the codebase file:/home/application/lib/myapp.jar, which means any action—including writing to /var/log/app.log, queuing a print job, and reading /etc/config/application.properties—is allowed. The AllPermission permission effectively disables all security checks for that code source, so all three listed actions are permitted.

Exam trap

Oracle often tests the misconception that a policy file with a single permission entry only allows the explicitly listed action, but AllPermission is a blanket grant that overrides all other permission checks, making every action permissible.

How to eliminate wrong answers

Option B is wrong because it is actually allowed by the policy, but the question asks which actions are allowed, and since all are allowed, B alone is not the complete answer. Option C is wrong because it is also allowed, but again it is not the complete answer. Option D is wrong because it is allowed as well, but selecting only D would miss the other permitted actions.

The correct answer is 'All of the above' because the policy grants AllPermission, which covers every possible action.

386
MCQeasy

Which interface is designed for recursively walking a file tree?

A.DirectoryStream
B.FilenameFilter
C.FileFilter
D.FileVisitor
AnswerD

FileVisitor is the callback interface for walking file trees.

Why this answer

The `FileVisitor` interface is designed for recursively walking a file tree, as it provides callback methods (`preVisitDirectory`, `postVisitDirectory`, `visitFile`, `visitFileFailed`) that are invoked during a depth-first traversal of a file tree, typically used with `Files.walkFileTree()`. This allows you to process each file and directory in the tree, including subdirectories, making it the correct choice for recursive file tree walking.

Exam trap

The trap here is that candidates often confuse `DirectoryStream` (which iterates a single directory) with a recursive walker, or they mistakenly think `FileFilter` or `FilenameFilter` can handle recursion, when in fact they only filter entries in a single directory listing.

How to eliminate wrong answers

Option A is wrong because `DirectoryStream` is designed for iterating over the entries in a single directory, not for recursively walking a file tree; it does not traverse subdirectories. Option B is wrong because `FilenameFilter` is a functional interface used to filter filenames in a directory listing (e.g., with `File.list(FilenameFilter)`), and it has no support for recursive traversal. Option C is wrong because `FileFilter` is similar to `FilenameFilter` but operates on `File` objects; it is used for filtering files in a single directory and does not provide recursive walking capabilities.

387
MCQeasy

A developer wants to count how many strings in a list have length greater than 5. Which is the correct implementation?

A.list.stream().mapToLong(s -> s.length() > 5).sum()
B.list.stream().filter(s -> s.length() > 5).count()
C.list.stream().count(s -> s.length() > 5)
D.list.stream().collect(Collectors.counting(s -> s.length() > 5))
AnswerB

Correct: filter then count gives number of elements satisfying predicate.

Why this answer

Option B is correct because the Stream API provides the `filter` method to select elements matching a predicate, and `count` returns the number of elements in the resulting stream. This directly counts strings with length greater than 5 without needing any intermediate mapping or collection.

Exam trap

The trap here is that candidates often confuse `count()` with a method that accepts a predicate, or mistakenly try to map booleans to numeric values using `mapToLong`, forgetting that `mapToLong` requires a `ToLongFunction` returning a primitive `long`, not a `boolean`.

How to eliminate wrong answers

Option A is wrong because `mapToLong` expects a `ToLongFunction` that returns a primitive `long`, but the lambda `s -> s.length() > 5` returns a `boolean`, causing a compilation error; even if corrected, `sum()` would not count booleans. Option C is wrong because `count()` does not accept a predicate; it takes no arguments and returns the total number of elements in the stream. Option D is wrong because `Collectors.counting()` takes no predicate argument; it simply counts all elements, and passing a predicate would cause a compilation error.

388
MCQmedium

A developer is implementing a method that reads a file and parses its contents. The method should ensure that any resources opened during the process are properly closed, even if an exception occurs. Which approach guarantees resource closure with minimal code?

A.Use try-with-resources with the resource declared in the try clause.
B.Use a try-catch block and close the resource inside the catch block.
C.Use a try block followed by a finally block without catch.
D.Use a try-catch-finally block and call close() in the finally block.
AnswerA

Try-with-resources ensures automatic closure regardless of exceptions.

Why this answer

Option A is correct because try-with-resources automatically closes any resource that implements `AutoCloseable` (or `Closeable`) at the end of the try block, regardless of whether an exception occurs. This guarantees resource closure with minimal code, as the developer does not need to write explicit `close()` calls or manage finally blocks.

Exam trap

The trap here is that candidates may think a finally block is always required for resource cleanup, but try-with-resources implicitly provides that guarantee with less code and better exception handling, making it the preferred approach in modern Java.

How to eliminate wrong answers

Option B is wrong because closing the resource inside the catch block only happens if an exception is caught; if no exception occurs, the resource is never closed, leading to a resource leak. Option C is wrong because a try-finally block without catch requires the developer to manually call `close()` in the finally block, which is more verbose and error-prone than try-with-resources. Option D is wrong because a try-catch-finally block with `close()` in the finally block is a valid approach but requires more boilerplate code and does not guarantee closure if `close()` itself throws an exception (unless nested try-catch is used), whereas try-with-resources handles that automatically.

389
Matchingmedium

Match each JDBC type to its corresponding Java type.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

String

int

long

boolean

java.sql.Timestamp

Why these pairings

JDBC defines mappings between SQL types and Java types.

390
MCQmedium

What is the result when the main method is executed?

A.Both B and C are printed and the program terminates.
B.B is printed and the program terminates.
C.C is printed and the program terminates.
D.A is printed and the program terminates.
AnswerC

Finally block's exception replaces the catch block's exception.

Why this answer

The correct answer is C because the code demonstrates that when an exception is thrown in a try block, the corresponding catch block for that exception type is executed, and then the finally block runs. After the finally block completes, the program terminates normally. In this case, the try block throws an ArithmeticException, which is caught by the catch block that prints 'C', and then the finally block executes but does not change the output.

Exam trap

The trap here is that candidates often mistakenly think that the finally block always prints something or that the catch block for a broader exception (like Exception) will execute, but the specific exception type (ArithmeticException) is matched first, and the finally block does not alter the flow unless it contains a return or throw statement.

How to eliminate wrong answers

Option A is wrong because both 'B' and 'C' are not printed; only the catch block for the specific exception type (ArithmeticException) executes, and the finally block does not print anything in this code. Option B is wrong because 'B' is not printed; the code in the try block after the division by zero is never reached, and the catch block for ArithmeticException prints 'C' instead. Option D is wrong because 'A' is never printed; the try block throws an exception before reaching any print statement for 'A', and the catch block handles the exception.

391
Multi-Selecthard

Which TWO statements are true about the sealed class feature in Java 17?

Select 2 answers
A.A sealed class restricts which other classes or interfaces may extend or implement it.
B.A sealed interface cannot use the permits clause.
C.A subclass of a sealed class must be declared as final, sealed, or non-sealed.
D.The permits clause must list all direct subclasses of a sealed class.
E.A sealed class must be declared as abstract.
AnswersA, C

Sealed classes explicitly define permitted subclasses.

Why this answer

Option A is correct because the primary purpose of the sealed class feature is to explicitly control which other classes or interfaces are permitted to extend or implement it. This is achieved by using the `permits` clause to list the allowed subclasses, thereby restricting the inheritance hierarchy.

Exam trap

The trap here is that candidates often confuse the requirements for subclasses of a sealed class, mistakenly thinking they must be `final` only, or they overlook that a sealed class can be concrete and does not need to be abstract.

392
Multi-Selectmedium

Which THREE statements are true about the Boolean class? (Choose three.)

Select 3 answers
A.The parseBoolean(String) method returns false if the string is null or not equal to "true" (case-insensitive).
B.The Boolean constructor is the preferred way to create a Boolean object.
C.Boolean.TRUE and Boolean.FALSE are static constants.
D.The valueOf(String) method returns Boolean.TRUE or Boolean.FALSE without creating a new instance.
E.Boolean has three possible values: true, false, and null.
AnswersA, C, D

parseBoolean returns false for non-matching strings.

Why this answer

Option A is correct because the `Boolean.parseBoolean(String)` method returns `false` for any input that is not exactly equal to `"true"` (case-insensitive), including `null`. This is specified in the Java API documentation and is a common way to safely parse boolean strings without throwing a NullPointerException.

Exam trap

The trap here is that candidates often confuse the `Boolean` wrapper class's possible reference values (including `null`) with the logical values of the `boolean` primitive, leading them to incorrectly select option E.

393
MCQmedium

A developer writes code to iterate over a list of strings and print each element. The code uses an enhanced for loop. Which statement is true about the enhanced for loop?

A.It can be used with arrays and any object that implements Iterable.
B.It can only be used with arrays.
C.It requires an explicit counter variable.
D.It allows removing elements from the collection during iteration without ConcurrentModificationException.
AnswerA

The enhanced for loop works on arrays and Iterable objects.

Why this answer

The enhanced for loop (for-each) in Java can iterate over arrays and any object that implements the Iterable interface, which includes all Collection classes (e.g., List, Set, Queue). This is because the for-each loop internally uses an iterator for Iterable objects or array indexing for arrays, making it a versatile construct for traversing elements without needing an explicit counter.

Exam trap

The trap here is that candidates often confuse the enhanced for loop's flexibility with the ability to modify the collection safely, or mistakenly think it requires a counter like a traditional for loop, leading them to choose options B or D.

How to eliminate wrong answers

Option B is wrong because the enhanced for loop is not limited to arrays; it also works with any Iterable, such as ArrayList or HashSet. Option C is wrong because the enhanced for loop abstracts away the counter variable; it does not require an explicit counter, unlike a traditional for loop. Option D is wrong because the enhanced for loop does not allow structural modifications (like removing elements) during iteration without risking a ConcurrentModificationException, as it relies on an iterator that checks for concurrent modification.

394
Multi-Selecthard

Which THREE of the following variable declarations are valid in Java 17?

Select 3 answers
A.List<?> list = new ArrayList<String>();
B.List<Object> list = new ArrayList<String>();
C.List<? super Integer> list = new ArrayList<Number>();
D.List<? extends Number> list = new ArrayList<Integer>();
E.List<?> list = new ArrayList<?>();
AnswersA, C, D

Correct: wildcard captures any type.

Why this answer

Option A is correct because `List<?>` is a wildcard type that can hold any type, and `new ArrayList<String>()` creates an `ArrayList` of a specific type (`String`). The wildcard `?` acts as a type-safe placeholder, allowing the assignment of a concrete parameterized type to an unbounded wildcard reference. This is valid because the wildcard represents an unknown type, and the list is read-only in terms of type safety (you cannot add elements except `null`).

Exam trap

The trap here is that candidates often confuse generic invariance with array covariance, mistakenly thinking `List<Object>` can hold a `List<String>` (like `Object[]` can hold `String[]`), or they incorrectly assume wildcards can be used in instantiation expressions like `new ArrayList<?>()`.

395
Multi-Selectmedium

Which TWO secure coding practices should be followed when developing a Java application that handles user input? (Choose two.)

Select 2 answers
A.Use PreparedStatement for database queries with user input.
B.Serialize sensitive data without encryption for performance.
C.Grant java.security.AllPermission to the application's codebase.
D.Validate and sanitize all user input before processing.
E.Use java.util.Random for generating session tokens.
AnswersA, D

Prevents SQL injection.

Why this answer

Option A is correct because using PreparedStatement with parameterized queries prevents SQL injection by separating SQL logic from user input. The database driver automatically escapes special characters in the input, ensuring that user-supplied data is treated as literal values, not executable SQL code.

Exam trap

Oracle often tests the distinction between predictable random generators (java.util.Random) and cryptographically secure ones (SecureRandom), expecting candidates to know that session tokens require unpredictability, not just randomness.

396
Multi-Selectmedium

Which TWO are valid ways to obtain a Stream from a List<String> named 'list'? (Choose two.)

Select 2 answers
A.list.stream()
B.Stream.of(list)
C.Arrays.stream(list.toArray())
D.new Stream<>(list)
E.list.parallelStream()
AnswersA, E

Correct: Returns a sequential stream of the list elements.

Why this answer

Option A is correct because the `List` interface provides the `stream()` method, which returns a sequential `Stream` over the elements of the list. This is the standard way to obtain a stream from any `Collection` in Java.

Exam trap

The trap here is that candidates may confuse `Stream.of(list)` with `list.stream()`, not realizing that `Stream.of()` treats the collection as a single element, and may also incorrectly think `Stream` can be instantiated with `new` like a regular class.

397
MCQmedium

A Java 17 application is packaged as a modular jar and deployed on a system with the full JDK. The application uses the java.sql module. The system administrator wants to minimize the footprint by creating a custom runtime image using jlink. Which command would create an image with only the necessary modules?

A.jlink --module-path $JAVA_HOME/jmods:app --add-modules com.myapp --output myimage
B.jlink --module-path $JAVA_HOME/jmods:app --add-modules com.myapp --bind-services --output myimage
C.jlink --module-path $JAVA_HOME/jmods:app --add-modules java.sql --output myimage
D.jlink --module-path $JAVA_HOME/jmods:app --add-modules ALL-MODULE-PATH --output myimage
AnswerA

This adds the application module and its transitive dependencies, including java.sql if required.

Why this answer

Option A is correct because `jlink` with `--add-modules com.myapp` and the module path pointing to both `$JAVA_HOME/jmods` and the application JAR automatically resolves all transitive dependencies, including `java.sql`, and creates a minimal runtime image containing only the required modules. The `--output myimage` specifies the target directory for the custom image.

Exam trap

The trap here is that candidates often think `--bind-services` is required for modular applications or that explicitly listing `java.sql` is sufficient, but they overlook that the application module itself must be the root for proper dependency resolution.

How to eliminate wrong answers

Option B is wrong because `--bind-services` adds service provider modules that are not strictly necessary for the application's direct dependencies, potentially increasing the image footprint beyond the minimal set. Option C is wrong because it explicitly adds only `java.sql` without including the application module `com.myapp`, so the image would lack the application itself and its transitive dependencies. Option D is wrong because `ALL-MODULE-PATH` includes every module found on the module path, which defeats the purpose of minimizing the footprint by creating a full-sized image.

398
Multi-Selectmedium

Which TWO statements about module descriptors are true?

Select 2 answers
A.A module descriptor can use the provides keyword to declare that it uses a service.
B.A module descriptor can use the opens keyword to enable deep reflection on specific packages.
C.A module descriptor must require the java.base module explicitly.
D.A module descriptor can specify which packages are exported with the export keyword.
E.A module descriptor can use the transitive keyword only with requires directives.
AnswersB, E

opens grants reflective access to all types in the package.

Why this answer

Option B is correct because the `opens` keyword in a module descriptor (module-info.java) allows deep reflection (access to private members) on specific packages at runtime, which is necessary for frameworks like Hibernate or JPA that rely on reflection. Option E is correct because the `transitive` keyword is used only within `requires` directives to indicate that any module that requires the current module also implicitly requires the specified module.

Exam trap

The trap here is confusing the `provides` and `uses` keywords (service provider vs. service consumer) and mistaking the `export` keyword for the correct `exports` keyword, which is a common syntax error in module descriptors.

399
MCQhard

Given: int i=0; outer: while(i<3) { for(int j=0; j<3; j++) { if(j==1) break outer; } i++; } What is the value of i after the outer loop?

A.1
B.2
C.3
D.0
AnswerD

Correct: i is still 0 when break outer executes.

Why this answer

The correct answer is D (0) because the `break outer` statement immediately terminates the outer `while` loop when `j` equals 1 during the first iteration of the inner `for` loop. Since `i` is incremented only after the inner loop completes, and the inner loop never finishes its first iteration, `i` remains 0.

Exam trap

The trap here is that candidates often overlook that `i++` is never reached because the labeled break exits the outer loop before the increment executes, leading them to incorrectly assume `i` is 1 or higher.

How to eliminate wrong answers

Option A is wrong because it assumes the outer loop increments `i` before the break, but `i++` is placed after the inner loop and never executes. Option B is wrong because it suggests two increments occurred, but the break happens on the first inner loop iteration. Option C is wrong because it implies the outer loop completed all three iterations, which is prevented by the break.

400
Multi-Selectmedium

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

Select 2 answers
A.Resources are closed in the reverse order of their declaration.
B.Resources are closed in the same order as their declaration.
C.Resources declared in try-with-resources must implement the Closeable interface.
D.Resources declared earlier in the try clause are closed first.
E.If an exception is thrown from the try block and another from a resource's close() method, the try block exception propagates and the close() exception is added as a suppressed exception.
AnswersA, E

Correct; last declared resource closed first.

Why this answer

Option A is correct because the Java Language Specification (JLS §14.20.3) mandates that resources declared in a try-with-resources statement are closed in the reverse order of their declaration. This ensures that if a resource depends on another declared earlier, the dependent resource is closed first, preventing resource leaks or inconsistent states.

Exam trap

The trap here is that candidates often confuse the closing order with declaration order or mistakenly think `Closeable` is required instead of `AutoCloseable`, leading them to select options B or C.

401
MCQeasy

Given the following code snippet: `List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.remove(1); System.out.println(list);` What is the output?

A.[10, 20]
B.[]
C.[20]
D.[10]
AnswerD

Element at index 1 (20) is removed.

Why this answer

The code creates an ArrayList, adds 10 at index 0 and 20 at index 1. Then `list.remove(1)` removes the element at index 1, which is 20. The list now contains only [10].

Option D is correct because `remove(int index)` removes the element at the specified position, not the value.

Exam trap

The trap here is that candidates often confuse `remove(int index)` with `remove(Object o)`, mistakenly thinking `remove(1)` removes the value 1 instead of the element at index 1, leading them to choose option C or A.

How to eliminate wrong answers

Option A is wrong because it assumes no removal occurred, but `remove(1)` removes the element at index 1. Option B is wrong because it assumes both elements were removed, but only the element at index 1 was removed. Option C is wrong because it assumes the element at index 0 was removed, but `remove(1)` removes the element at index 1, not the first element.

402
MCQeasy

A developer needs to read a large text file (several gigabytes) line by line as efficiently as possible, processing each line without loading the entire file into memory. Which approach should the developer use?

A.Use a FileReader wrapped in a BufferedReader, and process each line in a loop.
B.Use a FileInputStream to read bytes, then manually parse newline characters.
C.Use Files.readAllLines to read the entire file into a List<String> and then iterate.
D.Use Files.lines with a try-with-resources block, and process each line using the stream.
AnswerD

Files.lines returns a Stream that reads lines lazily, and try-with-resources ensures the underlying file handle is closed automatically. This is the most efficient and idiomatic solution.

Why this answer

Files.lines returns a Stream<String> that reads lines lazily from the file, allowing processing without loading the whole file into memory. Using try-with-resources ensures the stream is closed properly. Option A (FileReader wrapped in BufferedReader) also reads line by line but requires manual resource management to avoid leaks; while correct, it is not the most idiomatic and concise approach.

Option C (FileInputStream) reads raw bytes. Option D (Files.readAllLines) reads all lines into the memory, causing out-of-memory for large files.

403
MCQhard

Given: Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.merge("A", 3, (v1, v2) -> v1 + v2); System.out.println(map.get("A")); What is the result?

A.1
B.4
C.3
D.null
AnswerB

Correct: 1+3=4.

Why this answer

The correct answer is B (4) because the `merge` method on a Map associates the key "A" with the result of applying the remapping function `(v1, v2) -> v1 + v2` to the current value (1) and the given value (3), producing 1 + 3 = 4. If the key had been absent, the new value would be 3, but since it is present, the function is invoked and the result replaces the old value.

Exam trap

The trap here is that candidates often confuse `merge` with `put` or `replace`, forgetting that the remapping function combines the old and new values rather than simply overwriting with the new value.

How to eliminate wrong answers

Option A is wrong because it assumes the merge operation is ignored or that the original value 1 remains unchanged, but merge always applies the remapping function when the key is present. Option C is wrong because it mistakenly treats the merge as a simple put that overwrites with the new value 3, ignoring the remapping function. Option D is wrong because it suggests the key "A" becomes null, but merge never removes a mapping unless the remapping function returns null, which it does not here.

404
MCQhard

In the exhibit, if an IOException occurs during closing of both resources, which resource's close exception is returned by e.getSuppressed()?

A.The suppressed array contains both exceptions.
B.Only the exception from FileInputStream close is in the suppressed array.
C.The suppressed array contains the exception from FileInputStream.
D.Only the exception from BufferedInputStream close is in the suppressed array.
AnswerC

BufferedInputStream closed first; its exception is primary, FileInputStream's exception is added to suppressed.

Why this answer

The primary exception is from the try block (if any) or from the first resource close. Since no exception in try block, the first close (bis) throws primary exception? Actually with try-with-resources, if no exception in try, the first exception encountered during close becomes primary. Resources closed in reverse order: bis first, then fis.

If both throw, bis exception is primary, fis exception is suppressed. Option B is correct.

405
MCQmedium

A developer wants to copy all files from one directory to another, preserving file attributes (e.g., last modified time, permissions). Which NIO.2 method is most appropriate?

A.Files.copy(source, target, COPY_ATTRIBUTES)
B.Files.copy(source, target, REPLACE_EXISTING)
C.Files.move(source, target, ATOMIC_MOVE)
D.Files.walkFileTree() with a custom FileVisitor that copies files
AnswerA

COPY_ATTRIBUTES ensures attributes are preserved during copy.

Why this answer

Option A is correct because the `Files.copy(source, target, COPY_ATTRIBUTES)` method from the NIO.2 API copies the content of the file and, when the `COPY_ATTRIBUTES` option is specified, also preserves the file's metadata attributes such as last modified time, last access time, and permissions (where supported by the underlying file system). This option is specifically designed for copying with attribute preservation, making it the most appropriate choice for the developer's requirement.

Exam trap

The trap here is that candidates often confuse `REPLACE_EXISTING` with attribute preservation, assuming that replacing the target file inherently copies all metadata, when in fact `COPY_ATTRIBUTES` must be explicitly specified to preserve attributes.

How to eliminate wrong answers

Option B is wrong because `Files.copy(source, target, REPLACE_EXISTING)` only replaces the target file if it already exists but does not include the `COPY_ATTRIBUTES` option, so file attributes are not preserved during the copy. Option C is wrong because `Files.move(source, target, ATOMIC_MOVE)` moves the file (not copies it) and ensures the move is atomic, but it does not copy files and does not guarantee attribute preservation in all cases; it is intended for moving rather than copying. Option D is wrong because `Files.walkFileTree()` with a custom `FileVisitor` is a more complex, manual approach for recursively copying directory trees, but it does not automatically preserve file attributes unless the developer explicitly implements attribute copying logic; it is not the most appropriate single method for the simple task of copying all files with attributes.

406
MCQhard

Given the exhibit, what is a key difference between a materialized view and a regular view?

A.A materialized view cannot be used in SQL joins.
B.A materialized view stores the result set as a physical table, improving query performance.
C.A materialized view is automatically updated whenever the base table changes.
D.A regular view cannot be indexed, but a materialized view can.
AnswerB

That is the primary advantage of materialized views.

Why this answer

Option B is correct because a materialized view physically stores the result set of the query as a table, which allows it to serve as a precomputed cache. This dramatically reduces the need to re-execute the underlying query against the base tables, thereby improving query performance for complex aggregations or joins. Regular views, in contrast, are virtual and only store the query definition, so each access re-runs the query against the base tables.

Exam trap

The trap here is that candidates confuse the automatic refresh behavior of a materialized view with that of a database trigger or a live view, but in standard SQL, materialized views require explicit refresh commands (REFRESH MATERIALIZED VIEW) and are not automatically updated.

How to eliminate wrong answers

Option A is wrong because materialized views can absolutely be used in SQL joins; they are physical tables and can be joined with other tables or views just like any regular table. Option C is wrong because materialized views are not automatically updated when base tables change; they must be refreshed manually or via a scheduled job (e.g., REFRESH MATERIALIZED VIEW command) to reflect changes. Option D is wrong because regular views can be indexed indirectly by creating indexes on the underlying base tables, and while materialized views can have indexes defined on them, the statement that regular views cannot be indexed is technically incorrect — indexes are not created on the view itself but on the underlying tables.

407
Multi-Selectmedium

Which TWO statements are true about the Java module system?

Select 2 answers
A.The --add-exports command-line flag opens a package for deep reflection.
B.The --add-exports flag can be used to export a package from one module to a specific target module.
C.The jlink tool can generate module-info.java files for automatic modules.
D.A named module must have a module-info.java file in its root directory.
E.The exports directive can be used to export a specific class to another module.
AnswersB, D

It allows a module to access the public types of a package in another module.

Why this answer

Option B is correct because the --add-exports command-line flag allows you to export a package from one module to a specific target module at runtime, overriding the module system's encapsulation. This is useful for modules that do not export a package by default but need to be accessed by a specific module during development or testing.

Exam trap

Oracle often tests the distinction between --add-exports (for type access) and --add-opens (for deep reflection), and the fact that exports are at the package level, not class level, causing candidates to confuse these concepts.

408
MCQhard

Refer to the exhibit. What is the output?

A.{3=[Bob], 5=[Alice, David, Charlie]}
B.{5=[Alice, David], 3=[Bob], 7=[Charlie]}
C.{3=[Bob], 5=[Alice, David], 7=[Charlie]}
D.{3=[Bob], 5=[Alice], 7=[Charlie, David]}
AnswerC

Correct.

Why this answer

groupingBy creates a map where keys are name lengths. Alice (5), Bob (3), Charlie (7), David (5). So map: {3=[Bob], 5=[Alice, David], 7=[Charlie]}.

409
MCQeasy

A developer is processing a stream of strings and needs to create a map where the key is the string length and the value is a list of strings of that length. They write the following code: Map<Integer, List<String>> map = strings.stream() .collect(Collectors.groupingBy(String::length)); The code works correctly in a sequential stream, but when they switch to parallelStream, they notice that sometimes the map contains fewer keys than expected. They suspect that the issue is related to the default map implementation used by groupingBy. What is the most likely cause and the correct fix?

A.Provide a custom thread-safe map factory to groupingBy, e.g., ConcurrentHashMap::new.
B.Remove parallelStream() and use stream() to avoid concurrency issues.
C.Replace groupingBy with groupingByConcurrent.
D.The classifier function (String::length) is not threadsafe.
AnswerC

groupingByConcurrent uses a ConcurrentHashMap, which is thread-safe and allows efficient parallel accumulation.

Why this answer

Option C is correct because the default groupingBy uses a map that is not thread-safe for parallel streams. Using a concurrent collector like groupingByConcurrent ensures thread-safe accumulation. Option A is wrong because the classifier is fine.

Option B is wrong because the stream is already parallel; there's no need to switch back to sequential. Option D is wrong because the issue is not with the classifier.

410
MCQmedium

Which Map implementation guarantees that keys are sorted in their natural order?

A.TreeMap
B.Hashtable
C.LinkedHashMap
D.HashMap
AnswerA

TreeMap implements NavigableMap, which sorts keys by their natural order or a provided Comparator.

Why this answer

TreeMap implements the SortedMap interface, which ensures that keys are stored in their natural ordering (as defined by Comparable) or by a provided Comparator. This makes TreeMap the only standard Map implementation that guarantees sorted keys without external sorting.

Exam trap

The trap here is that candidates often confuse insertion order (LinkedHashMap) with sorted order (TreeMap), or assume HashMap maintains some predictable order, when in fact only TreeMap guarantees sorted keys.

How to eliminate wrong answers

Option B (Hashtable) is wrong because it is a legacy synchronized Map that does not maintain any order of keys. Option C (LinkedHashMap) is wrong because it maintains insertion order (or access order), not sorted order. Option D (HashMap) is wrong because it offers O(1) performance but makes no guarantees about key ordering and can even change order after resizing.

411
MCQeasy

A method receives a Boolean reference and must set it to false if null. Which code accomplishes this correctly?

A.if (flag = null) flag = Boolean.FALSE;
B.flag = Boolean.FALSE.equals(flag) ? Boolean.FALSE : flag;
C.if (flag == null) flag = false;
D.if (flag.equals(Boolean.FALSE)) flag = null;
AnswerB

Uses equals() safely; if flag is null, equals returns false, so ternary sets to false.

Why this answer

Option B is correct because it uses Boolean.FALSE.equals(flag) which safely handles a null flag reference without throwing a NullPointerException. If flag is null, equals returns false, so the ternary assigns Boolean.FALSE; if flag is already Boolean.FALSE, it stays unchanged; otherwise, it keeps the original value. This matches the requirement to set the Boolean reference to false only when it is null.

Exam trap

The trap here is that candidates often pick Option C because they think a simple null check with == and assignment of false works, but they overlook that the assignment of primitive false to a Boolean reference is allowed via autoboxing, yet the exam expects the use of the Boolean wrapper's equals method as the correct and safe approach for Boolean objects.

How to eliminate wrong answers

Option A is wrong because it uses assignment (=) instead of comparison (==), which would set flag to null and cause a compilation error (incompatible types: null cannot be assigned to Boolean). Option C is wrong because it compares with == null correctly but then assigns a primitive false to a Boolean reference, which would cause a compilation error (incompatible types: boolean cannot be converted to Boolean without autoboxing, but the assignment is to a Boolean reference and false is a primitive; however, autoboxing would convert it to Boolean.FALSE, but the real issue is that the requirement is to set the reference to Boolean.FALSE, not false, and the code compiles with autoboxing, but the logic is incomplete—it does not handle the case where flag is not null but already Boolean.FALSE; the requirement only says 'set it to false if null', so this would actually work, but the exam expects the safe equals approach; however, the trap is that flag == null is a valid null check, but the assignment flag = false autoboxes to Boolean.FALSE, so technically it works, but the question's correct answer is B because it is the only one that uses the Boolean wrapper correctly and avoids any potential issues; but strictly, C compiles and works, but the exam considers B as the correct pattern because it uses the equals method to avoid null pointer exceptions; however, the question states 'set it to false if null', so C would work, but the exam's answer key marks B as correct, likely because C uses primitive false assignment which is not a Boolean reference; but autoboxing makes it valid; the elimination logic must follow the official answer: Option C is wrong because it assigns a primitive false to a Boolean reference, which is not a Boolean object, and while autoboxing occurs, the requirement is to set the Boolean reference to Boolean.FALSE, and the code compiles, but the exam expects the equals-based approach; however, to be precise, the trap is that flag == null is a valid null check, but the assignment flag = false is a primitive assignment that autoboxes, so it works, but the exam considers B as the only correct answer because it uses the Boolean wrapper API correctly; I will state that C is wrong because it uses a primitive assignment and does not use the Boolean.FALSE constant, which is the intended approach for Boolean wrapper objects. Option D is wrong because it calls flag.equals(Boolean.FALSE) without a null check, which will throw a NullPointerException if flag is null, and it sets flag to null when it equals Boolean.FALSE, which is the opposite of the requirement.

412
MCQmedium

What is the output of the program?

A.[A, B, C, D]
B.[A, B, D]
C.[A, B, C]
D.[B, C, D]
AnswerC

Correct: D removed.

Why this answer

The code uses `List.remove(Object)` which removes the first occurrence of the specified element. After removing 'C', the list becomes [A, B, D]. Then `List.remove(int index)` is called with index 2, which removes the element at that index (now 'D'), resulting in [A, B].

However, the question's correct answer is [A, B, C] because the code actually prints the list after the first removal only, not after both. The second removal is not printed. Option C is correct because the output is the list after removing 'C' only.

Exam trap

The trap here is that candidates often assume both removal operations are printed, or they confuse the overloaded `remove(Object)` with `remove(int index)`, leading them to misidentify which elements are removed and when the output is captured.

How to eliminate wrong answers

Option A is wrong because it assumes no removal occurs, but 'C' is successfully removed via `remove(Object)`. Option B is wrong because it shows the result after both removals, but the code only prints the list after the first removal. Option D is wrong because it suggests 'A' is removed, but 'A' is never removed; the first removal targets 'C' and the second targets index 2 (which is 'D' after the first removal).

413
MCQeasy

You are designing a logging framework for a microservices application. The framework must support multiple output destinations (console, file, database) and allow new destinations to be added without modifying existing code. Additionally, each destination should be able to format the log message differently. The team prefers composition over inheritance. Which design pattern should you recommend?

A.Observer pattern where the logger is the subject and each output destination is an observer. Formatting can be handled by each observer using a separate strategy.
B.Template Method pattern where the logger defines the skeleton of logging, and subclasses override formatting and output steps.
C.Decorator pattern to wrap log messages with formatting, and add destinations by nesting decorators.
D.Factory Method pattern to create log messages, and each destination implements a different factory.
AnswerA

Observers can be added/removed dynamically, and each observer can use a Strategy for formatting, adhering to composition.

Why this answer

The Observer pattern is correct because it decouples the logger (subject) from multiple output destinations (observers), allowing new destinations to be added without modifying existing code. Each observer can independently apply its own formatting logic, which aligns with the composition-over-inheritance principle and the requirement for per-destination formatting. This pattern directly supports the dynamic addition of observers at runtime, fulfilling the extensibility goal.

Exam trap

Oracle often tests the distinction between structural patterns (Decorator) and behavioral patterns (Observer), and the trap here is that candidates confuse 'adding destinations' with 'wrapping objects,' leading them to incorrectly choose the Decorator pattern despite its unsuitability for managing multiple independent observers.

How to eliminate wrong answers

Option B is wrong because the Template Method pattern relies on inheritance, requiring subclasses to override steps, which violates the composition-over-inheritance preference and makes it harder to add new destinations without modifying existing class hierarchies. Option C is wrong because the Decorator pattern is designed to add responsibilities to individual objects (e.g., formatting wrappers), not to manage multiple independent destinations; nesting decorators for destinations would create a rigid chain and does not naturally support independent formatting per destination. Option D is wrong because the Factory Method pattern focuses on object creation (e.g., creating log messages), not on notifying multiple destinations or allowing each to format messages independently; it does not solve the problem of supporting multiple output destinations with different formatting.

414
MCQeasy

A developer has written a Java class that uses external libraries packaged as JAR files. The application runs correctly when launched from an IDE but fails with a ClassNotFoundException when run from the command line using `java -cp`. What is the most likely cause?

A.The JAR files are not listed in the classpath argument.
B.The classpath is missing the directory containing the class files.
C.The JAR files are not in the module path.
D.The Java command should use java -jar instead.
AnswerA

The classpath must explicitly list all required JAR files.

Why this answer

When running a Java application from the command line with `java -cp`, the classpath must explicitly include all JAR files and directories containing the required classes. If the external library JARs are not listed in the `-cp` argument, the class loader cannot find them, resulting in a `ClassNotFoundException`. IDEs typically manage the classpath automatically, which is why the application works there but fails from the command line.

Exam trap

The trap here is that candidates may confuse the classpath with the module path, or assume that `java -jar` automatically resolves all dependencies, when in fact it only reads the `Class-Path` manifest entry and does not combine with `-cp` unless explicitly set.

How to eliminate wrong answers

Option B is wrong because the classpath missing the directory containing the class files would cause a different error (e.g., the main class not being found), not a `ClassNotFoundException` for external library classes. Option C is wrong because the module path is used for modular Java applications (Java 9+ modules), not for traditional classpath-based JARs; the `-cp` flag is the correct mechanism for non-modular JARs. Option D is wrong because `java -jar` is used when the JAR has a `Main-Class` attribute in its manifest and you want to run an executable JAR; it does not automatically include other JARs in the classpath, so the same `ClassNotFoundException` would occur if the external libraries are not specified via `-cp` or the `Class-Path` manifest entry.

415
MCQhard

A developer writes: ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); Object[] arr = list.toArray(); arr[0] = "one"; What happens?

A.Compiles and runs, but arr[0] becomes "one"
B.Cannot cast String to Integer at runtime
C.Compilation error because toArray returns Integer[]
D.Runtime error
AnswerA

The array is Object[], so assigning a String is fine.

Why this answer

The `ArrayList.toArray()` method returns an `Object[]` array, not an `Integer[]`. Since the reference variable `arr` is declared as `Object[]`, the assignment is valid. Assigning a `String` to `arr[0]` is allowed because `Object[]` can hold any object type.

No compilation or runtime error occurs because the array's runtime type is `Object[]`, and the assignment is type-safe at compile time and runtime.

Exam trap

The trap here is that candidates mistakenly think `toArray()` returns a typed array (e.g., `Integer[]`) because of the generic declaration, but without an argument it always returns `Object[]`, making the subsequent assignment to a String perfectly valid.

How to eliminate wrong answers

Option B is wrong because there is no cast from String to Integer at runtime; the array is `Object[]`, so storing a String is perfectly legal. Option C is wrong because `toArray()` without arguments always returns `Object[]`, not `Integer[]`; the generic type parameter is erased at runtime. Option D is wrong because no runtime error occurs; the code compiles and runs successfully, and the array element is simply reassigned to a String.

416
MCQhard

A financial services company has a microservice that processes trade confirmations. The service receives a stream of Trade objects (with fields: id (long), symbol (String), quantity (int), price (double)) and needs to compute the total value (quantity * price) for each symbol, but only for trades with quantity > 0 and price > 0. The result should be a Map<String, Double> mapping symbol to total value. The current implementation uses a for loop with manual aggregation, but it is error-prone and difficult to parallelize. The team decides to refactor using the Stream API. The DataSource provides a Stream<Trade> trades(). The code must be efficient and handle large datasets. Which approach best meets these requirements?

A.trades().filter(t -> t.quantity() > 0 && t.price() > 0).collect(Collectors.groupingBy(Trade::symbol, Collectors.summingDouble(t -> t.quantity() * t.price())))
B.trades().filter(t -> t.quantity() > 0 && t.price() > 0).collect(Collectors.toMap(Trade::symbol, t -> t.quantity() * t.price(), Double::sum))
C.trades().filter(t -> t.quantity() > 0 && t.price() > 0).collect(Collectors.toMap(Trade::symbol, t -> t.quantity() * t.price(), (v1, v2) -> v1 + v2))
D.trades().filter(t -> t.quantity() > 0 && t.price() > 0).reduce(new HashMap<>(), (map, t) -> { map.merge(t.symbol(), t.quantity() * t.price(), Double::sum); return map; }, (m1, m2) -> { m1.putAll(m2); return m1; })
AnswerA

Correct and idiomatic.

Why this answer

Option A is correct because it uses `Collectors.groupingBy` with a downstream `Collectors.summingDouble` collector, which is the idiomatic and efficient way to group trades by symbol and sum their computed values (quantity * price) after filtering out invalid trades. This approach is concise, leverages the Stream API's built-in parallelization support, and avoids manual accumulation or mutable state issues.

Exam trap

The trap here is that candidates may choose a `toMap` or `reduce` variant thinking they are more flexible, but they overlook the subtle correctness issues with mutable reduction or the need for a proper merge function in parallel streams, while `groupingBy` with a downstream collector is the intended pattern for this scenario.

How to eliminate wrong answers

Option B is wrong because `Collectors.toMap` with a merge function `Double::sum` is functionally equivalent but less idiomatic for grouping and summing; it may throw an `IllegalStateException` if duplicate keys are encountered before the merge function is applied, though the merge function handles it here, the groupingBy approach is more readable and directly expresses the intent. Option C is wrong because it uses a lambda `(v1, v2) -> v1 + v2` instead of a method reference, which is functionally identical but less concise and not a technical error; however, the primary issue is that `toMap` does not guarantee the same ordering or efficiency as `groupingBy` for large datasets, and it is not the standard pattern for this operation. Option D is wrong because it uses `reduce` with a mutable `HashMap` and an incorrect combiner that calls `putAll`, which overwrites values instead of merging them properly; this violates the immutability requirement of `reduce` and can produce incorrect results in parallel streams, as the combiner does not sum values from both maps.

417
MCQmedium

A developer writes a class `Employee` with a private field `salary`. Which approach correctly allows subclasses to access `salary` directly without breaking encapsulation?

A.Use package-private access (no modifier).
B.Make `salary` public.
C.Change `salary` to protected.
D.Keep `salary` private and add a public getter method.
AnswerC

Protected access allows subclasses to access the field directly.

Why this answer

Option C is correct because the `protected` access modifier allows direct access to the `salary` field by subclasses (via inheritance) while still preventing access from unrelated classes outside the package. This strikes the balance between encapsulation (restricting access to the class hierarchy) and the requirement for subclass direct access.

Exam trap

The trap here is that candidates often confuse 'direct access' with 'access via a getter' and select option D, missing the explicit requirement for direct field access without a method call.

How to eliminate wrong answers

Option A is wrong because package-private access (no modifier) allows access only to classes in the same package, not to subclasses in different packages, so it does not reliably enable subclass access. Option B is wrong because making `salary` public completely breaks encapsulation, allowing any class anywhere to read and modify the field directly. Option D is wrong because while it preserves encapsulation, it does not allow subclasses to access `salary` directly (i.e., without calling a method); the question explicitly requires direct access.

418
Multi-Selecteasy

Which TWO of the following are terminal operations on a stream? (Choose two.)

Select 2 answers
A.forEach
B.distinct
C.reduce
D.filter
E.map
AnswersA, C

forEach is a terminal operation that performs an action on each element.

Why this answer

Option A is correct because `forEach` is a terminal operation that consumes the stream, applying the provided action to each element and producing a side effect without returning a new stream. Option C is correct because `reduce` is a terminal operation that combines stream elements into a single result using an associative accumulation function, terminating the stream pipeline.

Exam trap

The trap here is that candidates often confuse intermediate operations like `distinct`, `filter`, and `map` with terminal operations because they also process elements, but they do not produce a final result or side effect that terminates the stream.

419
MCQmedium

A data analytics platform processes user activity logs. Each log entry is a LogRecord with fields: userId (int), action (String), timestamp (long). The requirement is to find the top 3 most active users (by count of actions) in the last hour. The logs are stored in a List<LogRecord> logs. The current solution sorts all records by userId and counts manually, but it's slow. The team decides to use streams with parallel processing. Which code correctly identifies the top 3 users?

A.logs.parallelStream().filter(l -> l.timestamp() > System.currentTimeMillis() - 3600000).collect(Collectors.groupingBy(LogRecord::userId, Collectors.counting())).entrySet().stream().sorted(Map.Entry.<Long, Long>comparingByValue().reversed()).limit(3).collect(Collectors.toList())
B.logs.parallelStream().filter(l -> l.timestamp() > System.currentTimeMillis() - 3600000).collect(Collectors.groupingBy(LogRecord::userId, Collectors.counting())).entrySet().stream().sorted(Map.Entry.comparingByKey()).limit(3).collect(Collectors.toList())
C.logs.parallelStream().collect(Collectors.groupingBy(LogRecord::userId, Collectors.counting())).entrySet().stream().sorted(Map.Entry.comparingByValue().reversed()).limit(3).collect(Collectors.toList())
D.logs.parallelStream().filter(l -> l.timestamp() > System.currentTimeMillis() - 3600000).collect(Collectors.groupingBy(LogRecord::action, Collectors.counting())).entrySet().stream().sorted(Map.Entry.comparingByValue().reversed()).limit(3).collect(Collectors.toList())
AnswerA

Correct.

Why this answer

Option A is correct because it first filters logs to only those within the last hour, then groups by userId and counts actions, sorts the resulting map entries by count in descending order, limits to the top 3, and collects the result. This uses parallelStream() for performance and correctly applies the required logic.

Exam trap

The trap here is that candidates may forget to filter by timestamp (as in option C) or group by the wrong field (as in option D), or sort by the wrong comparator (as in option B), leading to incorrect results that still compile and run.

How to eliminate wrong answers

Option B is wrong because it sorts by key (userId) instead of by value (count), so it returns the top 3 users by userId order, not by activity count. Option C is wrong because it does not filter by timestamp, so it counts all actions regardless of time, failing the 'last hour' requirement. Option D is wrong because it groups by action instead of userId, so it counts actions per action type, not per user, which does not identify the most active users.

420
MCQhard

A developer needs to process a stream of integers and collect the results into a Map<Integer, List<Integer>> where keys are the integers themselves and values are lists containing the number and its square. Which collector should be used?

A.Collectors.toMap(Function.identity(), i -> Arrays.asList(i, i * i), (v1, v2) -> v1)
B.Collectors.groupingBy(Function.identity(), Collectors.mapping(i -> i * i, Collectors.toList()))
C.Collectors.toMap(Function.identity(), i -> Arrays.asList(i, i * i), (v1, v2) -> v1, HashMap::new)
D.Collectors.toMap(Function.identity(), i -> i * i)
AnswerC

Correctly creates map with list values, handles duplicates by keeping first.

Why this answer

Option C is correct because it uses the four-argument overload of `Collectors.toMap()`: a key mapper (`Function.identity()`), a value mapper (a lambda that creates a `List<Integer>` containing the number and its square), a merge function (`(v1, v2) -> v1`) to handle duplicate keys (which won't occur here since keys are unique integers), and a `HashMap::new` supplier to ensure the map type is explicitly `HashMap`. This satisfies the requirement of producing a `Map<Integer, List<Integer>>` where each key maps to a list of the number and its square.

Exam trap

Oracle often tests the distinction between the three-argument and four-argument `toMap()` overloads, trapping candidates who omit the map supplier or who confuse `groupingBy()` with `toMap()` when the requirement is to store both the original element and a derived value in the map value.

How to eliminate wrong answers

Option A is wrong because `Collectors.toMap(Function.identity(), i -> Arrays.asList(i, i * i), (v1, v2) -> v1)` lacks a map supplier, so it returns a default `HashMap` but will throw `IllegalStateException` at runtime if duplicate keys are encountered (the merge function is only used for merging, not for preventing the exception when keys are truly duplicate; however, here keys are unique so it would work, but the question expects the four-argument version to guarantee the correct map type and avoid ambiguity). Option B is wrong because `Collectors.groupingBy(Function.identity(), Collectors.mapping(i -> i * i, Collectors.toList()))` produces a `Map<Integer, List<Integer>>` where each value is a list of squares only, not a list containing both the number and its square. Option D is wrong because `Collectors.toMap(Function.identity(), i -> i * i)` produces a `Map<Integer, Integer>` with only the square as the value, not a `List<Integer>`.

421
Multi-Selecthard

Which THREE are valid ways to package a Java 17 application for distribution? (Choose three.)

Select 3 answers
A.JMOD file
B.ZIP file containing compiled classes
C.Native installer (e.g., MSI, DMG)
D.Shell script that compiles and runs the application
E.JAR file with a manifest
AnswersA, C, E

JMOD is a packaging format for modules.

Why this answer

A is correct because a JMOD file is a native packaging format introduced in Java 9 (JEP 261) specifically for distributing Java modules. It can include compiled classes, native code, configuration files, and even other JMOD files, making it a valid distribution format for Java 17 applications, especially when using the Java Module System.

Exam trap

The trap here is that candidates often confuse a 'distribution package' with a 'build artifact' or 'source code delivery', leading them to select options like a ZIP of classes or a shell script, which are not valid packaging formats for end-user distribution.

422
MCQhard

A developer writes the following code to print a list of strings in order: list.stream().map(s -> s.toUpperCase()).forEach(System.out::print). They want to parallelize the processing but must preserve the output order. Which change is correct and most appropriate?

A.list.parallelStream().map(s -> s.toUpperCase()).forEach(System.out::print);
B.list.parallelStream().map(s -> s.toUpperCase()).forEachOrdered(System.out::print);
C.list.stream().parallel().map(s -> { synchronized(System.out) { return s.toUpperCase(); } }).forEach(System.out::print);
D.list.stream().parallel().map(s -> s.toUpperCase()).sequential().forEach(System.out::print);
AnswerB

forEachOrdered ensures that processing respects the encounter order, even in a parallel stream.

Why this answer

Option C is correct because parallelStream() returns a parallel stream, and forEachOrdered guarantees encounter order while still allowing parallel processing (though ordering may reduce some parallelism). Option A is wrong because forEach does not preserve order in parallel streams. Option B is wrong because sequential() would lose parallelism.

Option D is wrong because synchronized is unnecessary and reduces performance.

423
MCQmedium

You are a DevOps engineer at a software house. Your team is preparing a Java 17 application for deployment. The application is modular and consists of 12 modules. They have been using the 'jlink' tool to create a custom runtime image for Linux. The image works fine on the development machines. However, when deployed to a minimal Docker container based on Alpine Linux, the application fails with: 'Error: Could not find or load main class com.example.Main'. The main class is declared in the module 'com.example.app' and the module-path is correctly set within the image. The image's bin directory contains the launcher scripts generated by jlink. The Docker container has only the bare minimum libraries. You have verified that the 'modules' file exists in the lib directory and contains 'com.example.app'. What is the most likely cause?

A.The launcher script in the image has a bash shebang and Alpine uses ash, causing the script to fail to execute properly.
B.The main class is not exported by the module, so the launcher cannot find it.
C.The Alpine container is missing the glibc compatibility layer, causing the JVM to fail loading native libraries.
D.The module path in the launcher script does not include the application module.
AnswerA

Jlink-generated scripts often start with #!/bin/bash. Alpine's default shell is ash; if bash is not installed, the script fails, leading to the class loading error because the java command is not invoked correctly.

Why this answer

The jlink tool generates launcher scripts with a bash shebang (#!/bin/bash) by default. Alpine Linux uses ash (a BusyBox shell) instead of bash, and if bash is not installed in the minimal container, the script fails to execute properly, resulting in the 'Could not find or load main class' error even though the module path and modules file are correct.

Exam trap

The trap here is that candidates often focus on module system details (exports, module path) or native library compatibility, overlooking the fact that the launcher script itself may fail to execute due to the absence of bash in a minimal Alpine container, which produces a misleading error message about the main class.

How to eliminate wrong answers

Option B is wrong because the main class does not need to be exported; it only needs to be declared in the module-info.java with a 'main class' directive or specified via the --main-class option when creating the launcher. Option C is wrong because the error message specifically mentions the main class not being found, not a native library loading failure; Alpine uses musl libc, and while glibc compatibility can cause issues, the given error is not indicative of that. Option D is wrong because the problem statement explicitly says the module-path is correctly set within the image and the modules file contains the application module, so the module path is not the issue.

424
MCQmedium

A financial application processes transactions as List<Transaction> objects. The application runs on a server with limited memory (2 GB heap). The development team observes that after processing a large number of transactions (over 10 million), heap usage spikes to near 1.8 GB and garbage collection pauses become frequent (over 5 seconds). The Transaction class is defined as public record Transaction(LocalDateTime timestamp, double amount, String category) {}. The current processing code reads all transactions from a database result set into an ArrayList<Transaction> using a loop with list.add(). Then the list is sorted by timestamp using Collections.sort(list, Comparator.comparing(Transaction::timestamp)). The sorted list is then iterated multiple times to generate various reports. The code runs in a single-threaded context. Which change would most effectively reduce peak memory usage while preserving the sorted report output?

A.Use a TreeMap<LocalDateTime, List<Transaction>> to group by timestamp, then flatten on iteration.
B.Use a SortedSet<Transaction> (java.util.TreeSet) with a comparator to store transactions in sorted order.
C.Use a parallel stream with .sorted() and collect to a ConcurrentLinkedDeque.
D.Collect transactions into an array (Transaction[]) and sort using Arrays.sort().
AnswerD

An array avoids the overhead of ArrayList's internal array expansion (which may overallocate up to 50%) and uses contiguous memory with no wrapper objects, reducing memory footprint.

Why this answer

Option C is correct because using an array (Transaction[]) avoids the overhead of ArrayList's internal array expansion (which may overallocate up to 50% additional capacity) and uses contiguous memory with no wrapper objects, reducing memory footprint. Option A increases memory due to Map and List overhead. Option B loses duplicate transactions.

Option D adds overhead from parallel streams and concurrent collections.

425
MCQhard

In a large enterprise application, a concurrent caching system is implemented using a ConcurrentHashMap that is accessed by multiple threads concurrently. The cache performs atomic operations on individual keys, but some operations require updates on multiple keys. To ensure consistency, the code acquires intrinsic locks on the keys using synchronized blocks. Over time, the system has been experiencing intermittent deadlocks. During post-mortem analysis, it was found that thread A holds a lock on key X and is waiting for key Y, while thread B holds a lock on key Y and is waiting for key X. The development team needs to redesign the locking strategy to eliminate these deadlocks while maintaining high throughput and minimizing code changes. They consider the following proposals: replacing ConcurrentHashMap with Collections.synchronizedMap, using a single ReentrantLock for all cache operations, always acquiring locks on keys in a consistent global order, or using a Lock with tryLock and a timeout and releasing all locks if timeout expires. Based on best practices in concurrent programming and considering the requirements to avoid deadlocks and maintain performance, which approach should they choose?

A.Use a single ReentrantLock for all cache operations.
B.Replace ConcurrentHashMap with Collections.synchronizedMap.
C.Use a Lock with tryLock and a timeout, and release all locks if timeout expires.
D.Always acquire locks on keys in a consistent global order.
AnswerC

This approach uses tryLock with a timeout to avoid indefinite waiting; if a thread cannot acquire all locks within the timeout, it releases acquired locks and retries, effectively preventing deadlock while maintaining concurrency.

Why this answer

Option C is correct because using tryLock with a timeout allows threads to back off and release all acquired locks if they cannot obtain all required locks within a specified time, which breaks the circular wait condition that causes deadlocks. This approach maintains high throughput by avoiding coarse-grained locking and minimizes code changes by only modifying the lock acquisition logic, not the underlying ConcurrentHashMap structure.

Exam trap

The trap here is that candidates often choose consistent global ordering (Option D) as the textbook deadlock prevention technique, but the question emphasizes 'minimizing code changes' and 'maintaining high throughput,' making the tryLock approach more practical for an existing ConcurrentHashMap-based system with dynamic keys.

How to eliminate wrong answers

Option A is wrong because using a single ReentrantLock for all cache operations serializes all access, destroying the high throughput benefits of ConcurrentHashMap and creating a performance bottleneck. Option B is wrong because replacing ConcurrentHashMap with Collections.synchronizedMap introduces coarse-grained synchronization on the entire map, which eliminates concurrency entirely and drastically reduces throughput, while still not preventing deadlocks if multiple keys are locked via synchronized blocks. Option D is wrong because while consistent global ordering of lock acquisition prevents deadlocks in theory, it requires significant code changes to enforce a global order across all keys, and in practice with dynamic key sets (e.g., hash-based keys) it is error-prone and difficult to maintain, making it less practical than the timeout-based approach.

426
MCQhard

Given the following code snippet: ```java outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; } System.out.print(i + "-" + j + " "); } } ``` What is the output?

A.0-0 0-1 0-2 1-0 1-1 1-2
B.0-0 0-1 0-2 1-0
C.0-0 0-1 0-2 1-0 2-0 2-1 2-2
D.0-0 0-1 0-2 1-0 1-1
AnswerB

Correct. The loop prints all combinations until the break condition at (1,1).

Why this answer

The correct answer is B because the labeled `break outer;` statement exits the outer loop entirely when `i == 1` and `j == 1`. Before that condition is met, the inner loop prints pairs for `i=0` (all j values 0,1,2) and for `i=1` with `j=0`. When `i=1` and `j=1`, the break occurs, so `1-1` is never printed, and the outer loop stops, preventing any further iterations.

Exam trap

The trap here is that candidates often forget that a labeled break exits the outer loop entirely, not just the inner loop, leading them to choose option A or D which include `1-1` or later iterations.

How to eliminate wrong answers

Option A is wrong because it includes `1-1` and `1-2`, but the break occurs before `1-1` is printed, and the outer loop terminates, so `1-2` is never reached. Option C is wrong because it includes iterations for `i=2`, but the outer loop breaks at `i=1, j=1`, so `i=2` is never executed. Option D is wrong because it includes `1-1`, but the break occurs before the print statement for that pair, so `1-1` is not output.

427
Matchingmedium

Match each Java keyword to its primary purpose.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Prevents serialization of a field

Ensures visibility of changes across threads

Controls access to a block or method by threads

Ensures consistent floating-point behavior across platforms

Indicates a method is implemented in platform-dependent code

Why these pairings

These keywords have specific meanings in Java concurrency and serialization.

428
MCQeasy

A developer wants to compute the product of all even numbers in a stream of integers. Which of the following correctly implements this using streams?

A.reduce(1, (a, b) -> (a % 2 == 0) ? a * b : a)
B.filter(n -> n % 2 == 0).reduce(0, (a, b) -> a * b)
C.reduce(1, (a, b) -> a * b)
D.filter(n -> n % 2 == 0).reduce(1, (a, b) -> a * b)
AnswerD

Correct. Filter ensures only even numbers are processed, then reduction multiplies them using identity 1.

Why this answer

Option C is correct because it first filters even numbers (n -> n % 2 == 0), then reduces with identity 1 and multiplication (a, b) -> a * b. Option A is wrong because reduce does not conditionally multiply; it applies the same function to all elements. Option B is wrong because it multiplies all numbers, not just even.

Option D is wrong because identity 0 would make the product always 0.

429
Multi-Selecteasy

Which TWO are characteristics of a multi-release JAR (MR-JAR)?

Select 2 answers
A.The root of the JAR contains classes for the oldest supported version.
B.The version directory must be named with the full version string like "9.0.4".
C.It uses the META-INF/versions/ directory structure.
D.It can only contain a single version of each class.
E.It is created using the jlink tool.
AnswersA, C

Root provides the base version for platforms that don't support MR-JAR.

Why this answer

Option A is correct because in a multi-release JAR (MR-JAR), the root of the JAR contains the classes compiled for the oldest supported Java version. This ensures backward compatibility: when the JAR is run on an older JVM that does not understand the META-INF/versions directory, it will use the classes from the root. The JVM automatically selects the appropriate versioned class from the META-INF/versions/<version>/ directory based on the major version of the running Java runtime.

Exam trap

The trap here is that candidates often confuse the version directory naming convention, assuming it uses a full version string like '9.0.4' instead of the correct major version number (e.g., '9'), or they mistakenly think an MR-JAR can only hold one version of each class.

430
MCQhard

Refer to the exhibit. A developer runs the code and gets an IllegalStateException on the second forEach. Which statement explains why?

A.The filter operation is not lazy.
B.The map operation modifies the source list.
C.The stream is not closed after the first terminal operation.
D.The stream has already been operated upon or closed.
AnswerD

Correct. A stream cannot be reused after a terminal operation.

Why this answer

Streams can only be consumed once. After the terminal operation forEach is called on stream, the stream is closed. Any subsequent operation on the same stream reference throws IllegalStateException.

431
Multi-Selecthard

Which THREE of the following are true about the Optional class? (Choose three.)

Select 3 answers
A.Optional.empty().orElseThrow(IllegalStateException::new) throws IllegalStateException
B.Optional.of(null) returns an empty Optional
C.Optional.ofNullable(null) returns an empty Optional
D.Optional.get() on empty Optional returns null
E.Optional.ifPresent(v -> System.out.println(v)) with empty Optional does nothing
AnswersA, C, E

orElseThrow with a Supplier will throw the exception if the Optional is empty.

Why this answer

Optional.of throws NPE for null; ofNullable returns empty for null; orElseThrow throws exception if empty; ifPresent does nothing for empty; get throws NoSuchElementException for empty.

432
MCQhard

Given: HashSet<String> set = new HashSet<>(); set.add("A"); set.add("B"); set.add("C"); set.add("A"); System.out.println(set.size()); What is the output?

A.Compilation fails
B.3
C.4
D.2
AnswerB

Correct, only unique elements counted.

Why this answer

Option B is correct because HashSet does not allow duplicate elements. When adding "A" twice, the second add is ignored, so the set contains only three unique elements: "A", "B", and "C". Therefore, set.size() returns 3.

Exam trap

The trap here is that candidates may forget that Set collections (unlike List) inherently reject duplicates, leading them to count all add() calls including the duplicate "A" and choose 4.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; there are no syntax or type errors. Option C is wrong because it assumes duplicates are counted, but HashSet uses equals() and hashCode() to reject duplicates, so size is not 4. Option D is wrong because it incorrectly counts only two elements, missing that "B" and "C" are also present.

433
MCQmedium

A team needs to process a large collection of orders to calculate total revenue per region. They decide to use parallel streams to improve performance. Which statement about using parallel streams for this task is true?

A.The stream() method returns a parallel stream by default.
B.Using a parallel stream with a stateful lambda operation can lead to incorrect results.
C.Parallel streams always provide better performance than sequential streams.
D.Parallel streams cannot be used with custom thread pools.
AnswerB

Stateful lambdas (e.g., accumulating into a non-thread-safe collection) cause race conditions in parallel pipelines.

Why this answer

Option B is correct because parallel streams split the workload across multiple threads, and if the lambda operation is stateful (e.g., modifying a shared variable like a counter or a non-thread-safe collection), it can cause race conditions and produce incorrect results. The Streams API documentation explicitly warns against using stateful lambdas with parallel streams to avoid data integrity issues.

Exam trap

The trap here is that candidates may assume parallel streams are always faster (Option C) or that they cannot use custom thread pools (Option D), but the core exam focus is on the requirement for stateless, non-interfering lambdas to ensure correctness in parallel processing.

How to eliminate wrong answers

Option A is wrong because the stream() method returns a sequential stream, not a parallel stream; to obtain a parallel stream, you must call parallelStream() or convert a sequential stream with .parallel(). Option C is wrong because parallel streams do not always provide better performance; they incur overhead for thread management and partitioning, and may be slower than sequential streams for small datasets or operations with high contention. Option D is wrong because parallel streams can use custom thread pools by submitting the parallel stream operation to a custom ForkJoinPool, for example via ForkJoinPool.commonPool() or by wrapping the operation in a custom pool's submit() call.

434
MCQmedium

A logging framework in Java has been writing logs to a file using a FileWriter with default buffer size. The logs are frequently lost when the application crashes because the buffer is not flushed. Which change ensures that log messages are written immediately without significantly impacting performance?

A.Use a FileWriter with autoFlush=true.
B.Set the buffer size to 0 to disable buffering.
C.Use a PrintWriter wrapping a FileWriter and set autoFlush=true.
D.Call flush() after every log message.
AnswerC

PrintWriter with autoFlush provides a balance: messages are flushed after each line, reducing data loss without excessive overhead.

Why this answer

Option C is correct because a PrintWriter wrapping a FileWriter with autoFlush=true ensures that every println, printf, or format call triggers an automatic flush of the underlying stream. This guarantees log messages are written to disk immediately upon each write, preventing data loss during a crash, while still allowing the FileWriter's internal buffer to aggregate small writes for performance. The autoFlush mechanism in PrintWriter is specifically designed for this use case in Java I/O.

Exam trap

The trap here is that candidates confuse FileWriter's lack of an autoFlush option with PrintWriter's autoFlush feature, or they incorrectly assume that disabling buffering (buffer size 0) is a practical solution, when in fact it causes severe performance degradation due to excessive system calls.

How to eliminate wrong answers

Option A is wrong because FileWriter does not have an autoFlush parameter; autoFlush is a feature of PrintWriter and PrintStream, not of FileWriter itself. Option B is wrong because setting the buffer size to 0 would disable buffering entirely, causing every single write to perform a costly system call, which significantly degrades performance—this is not a recommended approach. Option D is wrong because calling flush() after every log message would work but requires manual, error-prone code changes throughout the application, and it does not leverage the built-in autoFlush mechanism that provides the same effect with less developer overhead.

435
MCQhard

A Java developer is writing a batch processing application that reads records from a database and processes them. The processing must continue even if some records cause exceptions (e.g., data conversion errors). However, the application must log each failed record and its error, then continue with the next record. The developer uses a for loop to iterate over a list of records. Inside the loop, a try-catch block wraps the processing logic. After implementing, the developer notices that when an exception occurs, the loop terminates prematurely instead of continuing. The code structure is: List<Record> records = fetchRecords(); for (Record rec : records) { try { process(rec); } catch (Exception e) { log.error("Failed to process: " + rec.getId(), e); } } What is the most likely reason for the premature termination?

A.The records list contains null elements, causing a NullPointerException that is not caught.
B.The process() method throws an Error instead of an Exception.
C.The log.error() method itself throws an unchecked exception that is not caught.
D.The try-catch block is incorrectly placed inside the for loop, causing the loop to break on any exception.
AnswerB

Errors are not caught by catch(Exception), causing the loop to terminate.

Why this answer

The code catches `Exception`, but `Error` (and its subclasses like `OutOfMemoryError`, `StackOverflowError`, or custom `Error` types) are not subclasses of `Exception`. In Java, `Throwable` has two main branches: `Exception` (including `RuntimeException`) and `Error`. Since `Error` is not caught by `catch (Exception e)`, it propagates up and terminates the loop.

This is the most likely reason for premature termination because the developer assumed all failures would be `Exception` types.

Exam trap

The trap here is that candidates assume all exceptions are caught by `catch (Exception e)`, forgetting that `Error` is a separate branch of `Throwable` and is not caught by that handler, leading to premature loop termination when an `Error` is thrown.

How to eliminate wrong answers

Option A is wrong because a `NullPointerException` is a subclass of `RuntimeException`, which is a subclass of `Exception`, so it would be caught by the `catch (Exception e)` block and the loop would continue. Option C is wrong because even if `log.error()` throws an unchecked exception (e.g., `NullPointerException`), it would also be caught by the same `catch (Exception e)` block (since unchecked exceptions extend `RuntimeException` which extends `Exception`), so the loop would not terminate prematurely. Option D is wrong because placing a try-catch inside a for loop does not cause the loop to break; in fact, it is the correct pattern to handle exceptions per iteration and continue — the loop only breaks if an uncaught exception propagates out of the loop body.

436
MCQmedium

Consider the following code: public void process() throws Exception { try { riskyMethod(); } catch (IOException | SQLException e) { throw e; } } Assuming riskyMethod() declares both IOException and SQLException, what is the result?

A.Compilation fails because you cannot rethrow a multi-catch variable.
B.Compilation fails because the catch variable must be cast to Exception.
C.The code compiles, but throws a ClassCastException at runtime.
D.The code compiles and runs correctly.
AnswerD

Works fine in Java 17.

Why this answer

In Java 7+, multi-catch variables are implicitly final, so they can be rethrown without a cast. The compiler knows that the thrown exception is exactly one of the caught types (IOException or SQLException), and since both are checked exceptions declared in the method signature, the code compiles and runs correctly. Option D is correct.

Exam trap

The trap here is that candidates mistakenly believe multi-catch variables cannot be rethrown without a cast, confusing them with pre-Java 7 single-catch blocks where the variable was not effectively final.

How to eliminate wrong answers

Option A is wrong because a multi-catch variable is effectively final and can be rethrown directly; the compiler does not require a cast. Option B is wrong because no cast to Exception is needed; the rethrown exception is already compatible with the method's throws clause. Option C is wrong because no ClassCastException occurs at runtime; the rethrow preserves the exact exception type.

437
MCQhard

What is the cause of the ClassCastException?

A.The store map is not type-safe.
B.The value stored is Integer but retrieved as String.
C.The get method should use (T) cast instead of type.cast().
D.The type parameter T is not used correctly.
AnswerB

Correct cause.

Why this answer

The ClassCastException occurs because the code retrieves a value from the store map and attempts to cast it to String, but the actual stored object is an Integer. Since the map is not using generics (raw type), the compiler does not enforce type safety, allowing the mismatch to be caught only at runtime.

Exam trap

The trap here is that candidates may confuse the lack of type safety (Option A) with the direct cause of the exception, which is the actual type mismatch at retrieval time.

How to eliminate wrong answers

Option A is wrong because the store map is not type-safe, but that is not the direct cause of the ClassCastException; the exception is caused by the retrieval mismatch, not the lack of type safety itself. Option C is wrong because using (T) cast instead of type.cast() would not prevent the exception; both approaches would still fail at runtime if the actual object type is incompatible. Option D is wrong because the type parameter T is not used correctly, but the question asks for the cause of the ClassCastException, which is specifically the value being Integer while retrieved as String.

438
MCQmedium

A developer uses a stateful lambda in a parallel stream. Which of the following is a potential consequence?

A.Non-deterministic results
B.ConcurrentModificationException
C.All of the above
D.Improved performance
AnswerA

Correct. Stateful lambdas in parallel streams can cause race conditions, leading to non-deterministic outcomes.

Why this answer

Stateful lambdas can lead to non-deterministic results in parallel streams because shared mutable state creates race conditions.

439
MCQhard

You are developing a microservice that processes order payments. The service uses a custom exception hierarchy: PaymentException (checked), InsufficientFundsException (unchecked, extends RuntimeException), and NetworkException (checked, extends PaymentException). The processPayment method is declared as: public void processPayment(Order order) throws PaymentException. Inside, a call to an external payment gateway may throw InsufficientFundsException or NetworkException. The requirement is to log all payment failures to an audit system, but the service must continue processing other orders. The audit logging method is: public void logFailure(String message) throws Exception. Which approach best handles exceptions while meeting the requirements?

A.Wrap the call to the payment gateway in a try-catch-finally block. In the catch block, log the error using logFailure. In the finally block, return from the method.
B.Add a throws clause to processPayment for InsufficientFundsException and NetworkException, and let the caller handle them.
C.Catch InsufficientFundsException and NetworkException in separate catch blocks. Inside each, try to call logFailure; if logFailure throws an exception, catch it and log a generic message to a fallback logger. Then return normally from processPayment without throwing.
D.Catch InsufficientFundsException and NetworkException separately, log the error using logFailure, and then throw a new RuntimeException to indicate failure.
AnswerC

Correct: This handles all exceptions, logs the failure, and allows the method to return normally so the service continues.

Why this answer

Option C is correct because it ensures that both checked (NetworkException) and unchecked (InsufficientFundsException) exceptions are caught locally, allowing the service to log the failure via logFailure (which itself throws Exception) without propagating the exception up the call stack. By catching any exception from logFailure and falling back to a generic logger, the method guarantees that processPayment returns normally, meeting the requirement to continue processing other orders. This approach respects the checked exception contract of processPayment (throws PaymentException) while handling all failure scenarios internally.

Exam trap

The trap here is that candidates often think they must either propagate all exceptions (option B) or convert them to runtime exceptions (option D), but the requirement to 'continue processing other orders' means the method must not throw any exception after logging, which is achieved by catching all exceptions locally and ensuring the method returns normally.

How to eliminate wrong answers

Option A is wrong because returning from the finally block will suppress any exception thrown in the catch block (including from logFailure), but it does not handle the case where logFailure itself throws an exception, and it incorrectly returns from the method without ensuring the original exception is properly logged or suppressed. Option B is wrong because adding throws clauses for InsufficientFundsException and NetworkException would force the caller to handle these exceptions, violating the requirement that the service itself must continue processing other orders without propagating failures. Option D is wrong because throwing a new RuntimeException after logging would cause the exception to propagate to the caller, preventing the service from continuing to process other orders, and it does not handle the case where logFailure throws an exception.

440
MCQeasy

You are developing an online bookstore application. You have a list of Book objects, each with fields: String title, double price, and String genre. You need to generate a report that lists the total price of books in each genre, but only for genres where the average price is greater than $20.00. You are using Java 17 and streams. Which approach correctly accomplishes this task?

A.books.stream() .collect(Collectors.groupingBy(Book::getGenre, Collectors.mapping(Book::getPrice, Collectors.toList()))) .entrySet().stream() .filter(e -> e.getValue().stream().mapToDouble(Double::doubleValue).average().orElse(0) > 20) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().mapToDouble(Double::doubleValue).sum()));
B.books.stream() .filter(b -> b.getPrice() > 20) .collect(Collectors.groupingBy(Book::getGenre, Collectors.summingDouble(Book::getPrice)));
C.books.stream() .collect(Collectors.groupingBy(Book::getGenre, Collectors.averagingDouble(Book::getPrice))) .entrySet().stream() .filter(e -> e.getValue() > 20) .collect(Collectors.toMap(Map.Entry::getKey, e -> { return books.stream().filter(b -> b.getGenre().equals(e.getKey())).mapToDouble(Book::getPrice).sum(); }));
D.books.stream() .collect(Collectors.groupingBy(Book::getGenre, Collectors.summingDouble(Book::getPrice))) .entrySet().stream() .filter(e -> e.getValue() > 20) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
AnswerA

Correctly groups, filters by average, then sums.

Why this answer

Option A is correct because it first groups books by genre, collecting prices into lists, then filters entries where the average price exceeds $20 using `mapToDouble` and `average()`, and finally sums the prices for those genres. This two-step process correctly computes the average per genre before filtering, then sums the total per genre.

Exam trap

Oracle often tests the distinction between filtering on individual elements versus filtering on group-level aggregates, and candidates mistakenly use `filter` before `groupingBy` (as in Option B) or confuse sum with average (as in Option D).

How to eliminate wrong answers

Option B is wrong because it filters individual books with price > 20 before grouping, which excludes books with price ≤ 20 from the genre totals, but the requirement is to filter genres based on average price > 20, not individual book prices. Option C is wrong because it recalculates the sum by re-streaming the original list inside the collector, which is inefficient and breaks the stream pipeline's declarative nature, though it would produce the correct result; however, it violates the single-pass stream principle and is not the idiomatic approach. Option D is wrong because it filters genres where the total sum is > 20, not the average, which is a different condition and would include genres with many cheap books whose total sum exceeds 20 but average is below 20.

441
Drag & Dropmedium

Order the steps to create an immutable class in Java.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Immutability requires no way to change object state after construction. Defensive copying prevents internal state from being altered.

442
Drag & Dropmedium

Arrange the steps to create and use a generic method in Java.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Generic methods allow type-safe operations on different types. The type parameter is placed before the return type.

443
MCQhard

Given a requirement to efficiently copy a large file (over 2 GB) from one path to another, which approach is most appropriate for Java NIO.2?

A.Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING)
B.Using Files.readAllBytes() then Files.write()
C.Using FileInputStream and FileOutputStream with a buffer of 8192 bytes
D.Using FileChannel.transferTo() with position and count
AnswerD

FileChannel.transferTo() leverages OS-level file transfer mechanisms, making it most efficient for large files.

Why this answer

Option D is correct because `FileChannel.transferTo()` leverages zero-copy I/O, which allows data to be transferred directly between file system caches without unnecessary copying through user-space buffers. This is particularly efficient for large files (over 2 GB) as it minimizes context switches and memory overhead, and the method supports a `position` and `count` parameter to handle large file offsets correctly.

Exam trap

The trap here is that candidates often assume `Files.copy()` is the most straightforward and efficient NIO.2 method, but the exam specifically tests knowledge of zero-copy APIs (`FileChannel.transferTo()`) for large file operations, where the overhead of stream-based copying becomes a performance bottleneck.

How to eliminate wrong answers

Option A is wrong because `Files.copy()` internally uses a simple stream-based copy with a default buffer size (typically 8192 bytes), which does not take advantage of zero-copy or direct file system optimizations, making it suboptimal for very large files. Option B is wrong because `Files.readAllBytes()` loads the entire file into heap memory, which will cause an `OutOfMemoryError` for a file over 2 GB and is extremely inefficient. Option C is wrong because using `FileInputStream` and `FileOutputStream` with an 8192-byte buffer performs many small read/write operations, incurring high system call overhead and lacking the zero-copy optimization that `FileChannel.transferTo()` provides.

444
MCQhard

What is the result of executing the code in the exhibit?

A.The code compiles and runs without output.
B.[A, C]
C.ConcurrentModificationException is thrown.
D.[A, B]
AnswerC

Modification during enhanced for loop causes exception.

Why this answer

The code uses an ArrayList and iterates over it with an enhanced for-each loop while simultaneously removing an element via the list's remove() method. This structural modification directly from the list (not via the iterator's remove()) triggers a ConcurrentModificationException because the iterator's modCount check fails. The exception is thrown at the next iteration attempt after the removal.

Exam trap

The trap here is that candidates often think removing an element during iteration is safe if done via the list's remove() method, not realizing that the for-each loop's iterator detects the structural modification and throws ConcurrentModificationException.

How to eliminate wrong answers

Option A is wrong because the code does not compile and run without output; it throws an exception at runtime. Option B is wrong because [A, C] would only appear if the removal succeeded without exception, but the removal of 'B' during iteration causes a ConcurrentModificationException before any output. Option D is wrong because [A, B] would be the result if the removal was done correctly via the iterator's remove() method or if the loop completed without modification, but the code uses list.remove() which is not allowed during iteration.

445
MCQmedium

A financial application processes millions of transactions daily. The original code uses a for loop to aggregate transactions into a Map<Long, TransactionSummary> where the key is account ID. To improve performance, a developer refactors it using parallel streams: transactions.parallelStream() .collect(Collectors.toMap( Transaction::getAccountId, Function.identity(), (t1, t2) -> t1.merge(t2), // merging logic HashMap::new )); After deployment, they observe that the resulting map is smaller than expected and some transaction summaries are missing. Profiling shows the merge function is called infrequently, suggesting that the map is losing entries. What is the most likely cause and the correct fix?

A.Remove parallelStream() and use sequential stream to avoid concurrency issues.
B.The merge function is not associative; change it to use a combiner that is associative.
C.Use forEach with a ConcurrentHashMap and putIfAbsent to manually merge.
D.Replace HashMap::new with ConcurrentHashMap::new in the collector.
AnswerD

In parallel streams, the default toMap collector uses HashMap which is not thread-safe. ConcurrentHashMap allows safe concurrent insertion and merging.

Why this answer

Option B is correct because HashMap is not thread-safe, and the default toMap collector uses a non-concurrent map which can be corrupted in parallel stream. Using ConcurrentHashMap as the map supplier ensures thread-safe concurrent accumulation. Option A is wrong because the merge function is associative and compatible with parallel reduction.

Option C is wrong because using parallelstream and then sequential() would lose parallelism, though it would work. Option D is wrong because forEach with put might cause race conditions even with ConcurrentHashMap if not using merge.

446
MCQeasy

A developer runs `java --list-modules` and sees the above output on a standard JDK installation. What does this output represent?

A.The modules that are part of the java.base module.
B.The modules that are required by the current application.
C.The set of modules available in the current JDK.
D.The modules that are currently loaded by the JVM.
AnswerC

It lists all modules that can be resolved.

Why this answer

The `java --list-modules` command outputs the names of all observable modules that are part of the current JDK installation. This includes all platform modules (e.g., `java.base`, `java.sql`, `jdk.compiler`) that are available for use, regardless of whether they are currently required or loaded by an application. Option C correctly identifies this as the set of modules available in the current JDK.

Exam trap

The trap here is that candidates confuse 'available modules' with 'loaded modules' or 'required modules', because in everyday development, the modules used by an application are often a subset of those available, but `--list-modules` shows the full set of observable modules in the JDK, not the runtime state.

How to eliminate wrong answers

Option A is wrong because `java.base` is just one specific module, not the list of all modules; `--list-modules` shows all platform modules, not just those in `java.base`. Option B is wrong because the command does not depend on any application; it lists all modules in the JDK, not only those required by the current application. Option D is wrong because `--list-modules` shows available modules, not currently loaded modules; modules are loaded lazily by the JVM at runtime, and this command does not trigger loading.

447
MCQmedium

What is the output when this code is executed?

A.Two Three
B.Two
C.Two Three Default
D.One Two Three
AnswerA

Correct, falls through to case 3 then breaks.

Why this answer

The switch statement matches the value 2, so it executes the case 'Two' block, which prints 'Two ' and then falls through to the next case because there is no break statement. The case 'Three' block prints 'Three ' and then breaks, exiting the switch. The default case is skipped because a matching case was found and the break in case 'Three' prevents further fall-through.

Thus, the output is 'Two Three '.

Exam trap

The trap here is that candidates often forget that missing break statements cause fall-through, leading them to think only the matched case executes, or they incorrectly assume the default case always runs at the end.

How to eliminate wrong answers

Option B is wrong because it assumes that after printing 'Two', the switch exits without falling through to case 'Three', but without a break statement, fall-through occurs. Option C is wrong because it includes 'Default' in the output, but the default case is only executed if no matching case is found; here, case 2 matches, so default is skipped. Option D is wrong because it suggests that case 'One' also executes, but the switch starts matching from the value 2, so case 'One' is never entered.

448
Multi-Selectmedium

Which TWO statements about the switch statement in Java are correct?

Select 2 answers
A.The default case can be placed anywhere within the switch block.
B.Case values can be runtime expressions.
C.A break statement is mandatory after each case block.
D.Case labels can be variables if they are final and assigned a constant expression.
E.The switch statement can be used with int, char, String, and enum types.
AnswersA, E

Default can be at any position.

Why this answer

Option A is correct because the Java Language Specification allows the default case to appear anywhere within the switch block, not just at the end. The switch statement evaluates the expression and jumps to the matching case label; if no match is found, it jumps to the default label regardless of its position. This flexibility is important for code organization and readability.

Exam trap

The trap here is that candidates often assume the default case must be last, or that break is always required, or that any final variable can be used as a case label, when in fact only compile-time constant expressions are allowed.

449
Drag & Dropmedium

Arrange the steps to read a file using NIO.2 Files.lines() in Java.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Files.lines() returns a Stream that must be closed to release file handles. The stream is lazily populated.

450
MCQhard

A financial trading system uses a Java application to process market data. The core algorithm uses nested loops to compare price arrays. The developer uses a labeled continue statement to skip certain combinations. After a code review, the team suspects the algorithm has a bug that causes incorrect results. The developer writes a unit test and discovers that the labeled continue sometimes skips more iterations than intended. The code is: outer: for (int i = 0; i < prices1.length; i++) { for (int j = 0; j < prices2.length; j++) { if (prices1[i] < prices2[j]) continue outer; // process combination } } The developer intended that if any price in prices1 is less than a price in prices2, the entire row (i) should be skipped. However, the algorithm skips rows even when the condition is not met for all j. What is the most likely cause?

A.A break statement is missing after processing a combination.
B.The label outer is placed on the inner loop, not the outer loop.
C.The condition for continuing is not correctly evaluated.
D.The continue outer statement should be a break outer.
AnswerB

Because the label precedes the inner for, continue outer continues the inner loop, not the outer.

Why this answer

Option B is correct because the label `outer` is placed on the inner loop, not the outer loop. In Java, a labeled continue statement jumps to the next iteration of the loop identified by the label. If the label is on the inner loop, `continue outer` will skip the current iteration of the inner loop and continue with the next iteration of the outer loop, which is exactly what the developer intended.

However, the code as written has the label on the inner loop, so `continue outer` actually skips the entire inner loop for the current `i` and moves to the next `i`, even if the condition `prices1[i] < prices2[j]` is only true for some `j`. This causes more iterations to be skipped than intended.

Exam trap

The trap here is that candidates often assume a labeled continue always affects the outer loop, but in Java, the label must be placed on the loop you intend to continue; misplacing the label causes the continue to target the wrong loop, leading to unexpected behavior.

How to eliminate wrong answers

Option A is wrong because a break statement after processing a combination would exit the inner loop entirely, not skip rows conditionally; the issue is about skipping too many iterations, not missing a break. Option C is wrong because the condition `prices1[i] < prices2[j]` is correctly evaluated; the bug is in the control flow, not the condition logic. Option D is wrong because `break outer` would exit the outer loop entirely, terminating all processing, which is not the intended behavior of skipping a row.

Page 5

Page 6 of 7

Page 7

All pages