Courseiva

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

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

Page 5

Page 6 of 7

Page 7
376
MCQmedium

Which of the following is a best practice when creating a custom exception class?

A.Implement the Exception interface.
B.Extend Error to indicate a serious system error.
C.Extend RuntimeException for an unchecked exception.
D.Extend Throwable directly to create a new exception type.
AnswerC

Standard practice for custom exceptions that represent programming errors.

Why this answer

Extending RuntimeException is the standard way to create a custom unchecked exception in Java. Unchecked exceptions do not require explicit handling via try-catch or throws clauses, making them suitable for programming errors like invalid arguments or illegal states. This aligns with Java's exception hierarchy where RuntimeException and its subclasses are unchecked.

Exam trap

The trap here is that candidates may think extending Throwable directly is acceptable for creating a new exception type, but the Java Language Specification recommends extending Exception or RuntimeException to maintain consistency with the standard hierarchy and avoid confusing checked/unchecked semantics.

How to eliminate wrong answers

Option A is wrong because Exception is a class, not an interface; Java does not have an 'Exception interface' to implement. Option B is wrong because extending Error is reserved for serious system failures (e.g., OutOfMemoryError) that applications should not attempt to handle or create custom subclasses of. Option D is wrong because extending Throwable directly is discouraged; it bypasses the established Exception and Error hierarchy, leading to non-standard exception types that are neither checked nor unchecked in a conventional sense.

377
MCQhard

A developer is building a batch processing application that reads a large CSV file (approx. 5 GB) from a network file system, transforms each row, and writes the result to a database. The initial implementation uses Files.lines(path) to obtain a Stream<String>, processes each line with forEach, and then does not explicitly close the stream. After running for several minutes, the application slows down, and eventually throws an IOException: 'Too many open files'. The database writes are also failing intermittently. The developer needs to fix the application. The environment is Java 17 on Linux with default settings. Which course of action best resolves the issues?

A.Use FileInputStream with a buffered byte array and manually scan for newline characters.
B.Replace Files.lines with Files.newBufferedReader, wrapping it in a try-with-resources block.
C.Use Files.readAllLines to load the entire file into memory and then iterate over the list.
D.Wrap the Files.lines call in a try-with-resources block to ensure the stream is closed automatically.
AnswerD

By using try-with-resources, the stream's underlying file handle is closed when the block exits, fixing the resource leak. This is the minimal and correct fix.

Why this answer

`Files.lines(path)` returns a lazily populated `Stream<String>` that holds a file handle open. Without an explicit close, the underlying `FileChannel` and file descriptor are not released, leading to 'Too many open files' after processing many lines. Wrapping the stream in a try-with-resources block ensures `close()` is called automatically, releasing the file descriptor and preventing resource exhaustion.

Exam trap

The trap here is that candidates often overlook that `Files.lines` returns a stream that must be closed, confusing it with in-memory collections like `List` that do not hold system resources, or incorrectly assuming that `forEach` terminal operation automatically closes the stream.

How to eliminate wrong answers

Option A is wrong because manually scanning for newline characters with a `FileInputStream` is low-level, error-prone, and does not leverage Java NIO's efficient streaming; it also does not inherently solve the resource leak issue if the stream is not closed. Option B is wrong because `Files.newBufferedReader` returns a `BufferedReader` that, while closable, does not provide the same lazy streaming semantics as `Files.lines`; however, the real issue is that the developer already has a stream from `Files.lines` and simply needs to close it, not replace it with a different reader. Option C is wrong because `Files.readAllLines` loads the entire 5 GB file into memory, which will cause an `OutOfMemoryError` and is impractical for large files; it also does not address the file descriptor leak.

378
MCQeasy

A developer needs to parse a date string '2024-07-04' into a LocalDate object. Which approach is correct?

A.LocalDate.of(2024, 07, 04)
B.DateFormat.getDateInstance().parse("2024-07-04")
C.LocalDate.parse("2024-07-04")
D.new LocalDate(2024, 7, 4)
AnswerC

Correct: LocalDate.parse uses the ISO_LOCAL_DATE format by default.

Why this answer

`LocalDate.parse("2024-07-04")` uses the default ISO-8601 format (yyyy-MM-dd), which matches the given string exactly. The `LocalDate` class provides a static `parse` method that returns a `LocalDate` object without needing an explicit formatter when the input follows the standard pattern.

Exam trap

The trap here is that candidates often confuse `LocalDate.of()` (which requires integer arguments without leading zeros) with `LocalDate.parse()`, or mistakenly think `DateFormat` or a constructor can create a `LocalDate`, when in fact `LocalDate` uses a factory method pattern and ISO parsing by default.

How to eliminate wrong answers

Option A is wrong because `LocalDate.of(2024, 07, 04)` uses integer month values where 07 is treated as octal (due to the leading zero), causing a compilation error or unexpected behavior; month values should be written as 7. Option B is wrong because `DateFormat.getDateInstance().parse("2024-07-04")` returns a `java.util.Date` object, not a `LocalDate`, and the default date format in the JVM's locale typically expects a different pattern (e.g., "7/4/24" in US locale), leading to a `ParseException`. Option D is wrong because `LocalDate` has no public constructor; `new LocalDate(2024, 7, 4)` will not compile as the constructor is private.

379
Multi-Selecteasy

Which TWO approaches are recommended to secure Java I/O operations? (Choose two.)

Select 2 answers
A.Use try-with-resources to ensure proper resource closure.
B.Use BufferedInputStream to wrap FileInputStream for better performance.
C.Use Serializable interface for all data objects.
D.Use FileLock to prevent concurrent write access.
E.Validate user input before using it in file path construction.
AnswersA, E

Ensures file handles are closed, preventing resource exhaustion.

Why this answer

Try-with-resources automatically closes each resource declared in its header when the block exits, whether normally or via exception. This eliminates the risk of resource leaks from forgotten or improperly handled close() calls, which is a fundamental security and reliability requirement for I/O operations.

Exam trap

The trap here is that candidates often confuse performance optimizations (like buffering) or concurrency mechanisms (like FileLock) with security practices, and they may also mistakenly think that serialization is a security measure when it is actually a data format concern with its own security risks.

380
MCQhard

Refer to the exhibit. What is the output?

A.{apple=2, banana=2, orange=2}
B.{1=[apple, banana, orange], 2=[apple, banana], 3=[apple]}
C.{apple=3, banana=2, orange=1}
D.{apple=3, banana=1, orange=1}
AnswerC

Correct.

Why this answer

The code processes a list containing the strings "apple", "banana", "orange", "apple", "banana", "apple" (or an equivalent stream) and uses `Collectors.groupingBy(Function.identity(), Collectors.counting())` to create a frequency map. The `groupingBy` collector groups the elements by their identity (the string itself) and the downstream `counting()` collector counts the occurrences in each group, resulting in a map where the key is the string and the value is the count: apple appears 3 times, banana 2 times, and orange 1 time.

Exam trap

A common pitfall is to think that groupingBy always produces a Map<K, List<V>>, but when paired with a downstream collector like counting(), it produces a Map<K, Long> (or Map<K, Integer> with summingInt). Here, candidates might expect option B, which shows a grouped list, but the correct output is a frequency map like option C.

How to eliminate wrong answers

Option A is wrong because it suggests all values are 2, which would only happen if each fruit appeared exactly twice, but the input has three apples, two bananas, and one orange. Option B is wrong because it shows a map from integer keys to lists of strings, which would result from `groupingBy(String::length)` not from `toMap` with a merge function; the actual code uses `toMap` with `Function.identity()` as key and `Integer::sum` as merge, not grouping. Option D is wrong because it gives banana=1 and orange=1, but the input has two bananas and one orange, so banana should be 2.

381
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

`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.

382
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.

383
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

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.

384
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.

385
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

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.

386
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

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.

387
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

The `collect` method with a concurrent `Collector` like `toConcurrentMap()` ensures thread-safe accumulation by leveraging `ConcurrentHashMap` internally, which uses fine-grained locking or lock-free operations. This approach allows multiple threads to update the shared mutable state concurrently without external synchronization, maximizing parallelism and performance while maintaining consistency.

Exam trap

The trap here is that candidates often assume any thread-safe data structure (like `ConcurrentHashMap`) used with `forEach` or `collect` is sufficient, but they overlook that the stream's reduction mechanism must be designed for concurrent accumulation, which only concurrent `Collector` implementations provide correctly.

How to eliminate wrong answers

Option B is wrong because using `forEach` with `AtomicInteger` and atomic updates still requires the lambda to be stateless; `forEach` is a terminal operation that does not support mutable reduction, and the `AtomicInteger` would be shared across threads, leading to race conditions if not properly managed, and it does not leverage the parallel stream's built-in reduction mechanism. Option C is wrong because using `synchronized` blocks inside the lambda introduces contention and serialization, negating the performance benefits of parallel streams and potentially causing deadlocks or severe slowdowns. Option D is wrong because using `ConcurrentHashMap` for accumulation but then collecting with `toList()` is inefficient and error-prone; `toList()` is not a concurrent collector and does not integrate with the parallel stream's reduction, requiring manual synchronization or conversion that undermines thread-safety and performance.

388
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

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.

389
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

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.

390
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

Correct. The policy grants AllPermission, so all actions (including writing to /var/log/app.log, queuing a print job, and reading /etc/config/application.properties) are allowed. Therefore, 'All of the above' is the correct answer.

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.

391
MCQeasy

Which interface is designed for recursively walking a file tree?

A.DirectoryStream [wrong]
B.FilenameFilter [wrong]
C.FileFilter [wrong]
D.FileVisitor [CORRECT]
AnswerD

FileVisitor provides callback methods for recursive file tree traversal via Files.walkFileTree().

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.

392
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

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.

393
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

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.

394
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 provides standard mappings from SQL types to Java types: VARCHAR to String, INTEGER to int, DATE to java.sql.Date, BLOB to java.sql.Blob, and CLOB to java.sql.Clob. Common confusions arise from mixing these mappings.

395
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

Correct. The try block throws an ArithmeticException, which is caught by the catch (ArithmeticException e) block, printing 'C'. The finally block executes but does not throw an exception, so the program terminates normally after printing 'C'.

Why this answer

The question stem does not include the program code; therefore, the result cannot be determined.

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.

396
MCQhard

Refer to the exhibit. What is the output?

A.1
B.15
C.-15
D.0
AnswerC

reduce(0, (a,b)->a-b) computes 0-1-2-3-4-5 = -15.

Why this answer

The code uses `reduce(0, (a, b) -> a - b)` on a stream of integers. This operation starts with an identity value of 0 and applies the subtraction lambda cumulatively: 0 - 1 = -1, then -1 - 2 = -3, then -3 - 3 = -6, then -6 - 4 = -10, then -10 - 5 = -15. Therefore, the output is -15, making option C correct.

Exam trap

Candidates often confuse the behavior of `reduce` with subtraction, mistakenly thinking it sums the elements or that the identity is ignored. The correct cumulative subtraction starting from identity 0 yields -15.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes the result is just the first element (1), ignoring the reduction operation entirely. Option B is wrong because it assumes addition (sum of 1+2+3+4+5 = 15) instead of subtraction, which is a common confusion with the `reduce` method. Option D is wrong because it assumes the identity value 0 remains unchanged, failing to apply the accumulator function to the stream elements.

397
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

This statement is true because a sealed class restricts which classes may extend it by using the `permits` clause to list the allowed subclasses.

Why this answer

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.

398
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

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.

399
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.

400
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

`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<?>()`.

401
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

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.

402
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. The List interface provides the stream() method to obtain a sequential Stream<String>.

Why this answer

Options A and E are correct. The `List` interface provides the `stream()` method to obtain a sequential stream and `parallelStream()` to obtain a parallel stream. Option B is incorrect because `Stream.of(list)` treats the list itself as a single element, producing a `Stream<List<String>>` rather than a `Stream<String>`.

Option C is incorrect because `Arrays.stream(list.toArray())` would work if you had a String array, but it returns a `Stream<Object>` since `toArray()` returns `Object[]`; this is not type-safe and not a direct way to get a stream from a list. Option D is incorrect because `Stream` is an interface and cannot be instantiated with `new`.

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.

403
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

`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.

404
MCQhard

Refer to the exhibit. What is the output?

A.270
B.95
C.90
D.185
AnswerD

Filter retains Alice (90) and Charlie (95). Sum = 90+95 = 185.

Why this answer

(185). The stream filters out all numbers less than 10 using the predicate `n -> n < 10`, resulting in the numbers 10, 20, 30, 40, 50, and 35. The reduce operation then sums these numbers using `Integer::sum`, yielding 185.

The initial value is 0, so the sum is accurate.

Exam trap

The trap here is that candidates often forget to apply the filter condition correctly or misread the predicate (e.g., thinking it removes numbers greater than or equal to 10 instead of less than 10), leading to incorrect sums.

How to eliminate wrong answers

Option A (270) is wrong because it assumes the sum of all original numbers (10+20+30+40+50+60+70=270) without applying the filter. Option B (95) is wrong because it likely results from incorrectly filtering numbers less than 10 (removing only 5) and then summing 10+20+30+35=95, but this ignores 40 and 50. Option C (90) is wrong because it might come from summing only 10+20+30+35=95 and then subtracting 5, or from a miscalculation of the filtered set.

405
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

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.

406
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

(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.

407
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

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.

408
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.

409
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 lazily reads lines from the file, processing them one at a time without loading the entire file into memory. The try-with-resources block ensures the underlying file handle is closed automatically, preventing resource leaks. This approach is specifically designed for efficient, memory-safe line-by-line processing of large files.

Exam trap

The trap here is that candidates often choose `BufferedReader` (Option A) because it is familiar, but they overlook that `Files.lines` is the modern, stream-based API that is both more idiomatic and safer for large files, and that `Files.readAllLines` (Option C) is a common pitfall for memory exhaustion.

How to eliminate wrong answers

Option A is wrong because while `BufferedReader` reads lines efficiently, it still requires manual loop management and does not leverage the lazy, stream-based processing that `Files.lines` provides for large files; however, it is not the most idiomatic or efficient choice for this scenario. Option B is wrong because manually parsing newline characters from a `FileInputStream` is error-prone, inefficient, and unnecessary, as Java provides higher-level abstractions that handle encoding and line boundaries correctly. Option C is wrong because `Files.readAllLines` reads the entire file into a `List<String>` in memory, which would cause an `OutOfMemoryError` for a multi-gigabyte file, defeating the requirement to avoid loading the entire file.

410
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

(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.

411
MCQhard

In the following try-with-resources block, resources are declared as: try (FileInputStream fis = new FileInputStream("data.txt"); BufferedInputStream bis = new BufferedInputStream(fis)) { ... } If an IOException occurs during the 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.
AnswerB

Correct: Since BufferedInputStream closes first and its exception becomes primary, the suppressed exception from FileInputStream is the only one in the suppressed array.

Why this answer

In a try-with-resources statement, resources are closed in the reverse order of their declaration. Here, FileInputStream is declared first and BufferedInputStream second, so BufferedInputStream is closed first. If both resources throw an IOException during closing, the exception from BufferedInputStream (the first to close) becomes the primary exception, and the exception from FileInputStream (the second to close) is suppressed.

The primary exception is thrown from the try block, while the suppressed exception is accessible via the getSuppressed() method. Therefore, e.getSuppressed() returns an array containing the exception from FileInputStream. Option B is correct because only the FileInputStream's close exception is in the suppressed array.

Exam trap

The trap is that candidates may think the suppressed array contains both exceptions or that it contains the exception from the first resource closed. Actually, the first closed resource's exception is primary, and the second's is suppressed.

412
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

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.

413
MCQhard

What is a key difference between a class and an interface in Java?

A.A class cannot be used in inheritance.
B.A class can contain instance variables, while an interface cannot.
C.An interface is automatically updated when the implementing class changes.
D.An interface can be instantiated directly.
AnswerB

Correct. A class can contain instance variables, while an interface cannot.

Why this answer

Classes can have instance variables (state), while interfaces cannot (they only declare method signatures and constants). This is a fundamental Java OOP concept.

Exam trap

Candidates might think that interfaces can have instance variables in Java 8+ with default methods, but interfaces still cannot have instance variables.

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.

414
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

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.

415
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

The code groups names by the length of their string using `Collectors.groupingBy(String::length, Collectors.toList())`. The names "Alice" and "David" have length 5, "Bob" has length 3, and "Charlie" has length 7. The resulting map has keys 3, 5, and 7.

Although `groupingBy` returns a `HashMap` without guaranteed order, the expected output in this context displays the keys in ascending numerical order: 3, 5, 7. Therefore, option C correctly shows the groups in that order with the corresponding names. Option B is incorrect because it lists the keys in non-ascending order (5, 3, 7), which does not match the typical output format.

Exam trap

The trap here is that candidates may miscompute string lengths (e.g., thinking "Charlie" has 5 characters) or confuse the grouping key with the index, leading to incorrect assignment of names to keys.

How to eliminate wrong answers

Option A is wrong because it incorrectly assigns "Charlie" (length 7) to key 5, and omits key 7 entirely. Option B is wrong because it incorrectly places "Charlie" under key 7 but also includes "David" under key 5, missing that "Charlie" should be alone under key 7; it also misplaces "David" under key 5 instead of key 5 (which is correct for Alice and David) but the grouping is correct for 5, though it adds an extra key 7 with only Charlie, which is actually correct, but the error is that it lists 7=[Charlie] while also having 5=[Alice, David] — wait, this is actually correct for 5 and 7, but it also has 3=[Bob] which is fine, but the issue is that it shows 5=[Alice, David] and 7=[Charlie] which matches C, so B is actually a duplicate of C? No, B shows 5=[Alice, David], 3=[Bob], 7=[Charlie] — that is exactly C. Re-evaluating: Option B says {5=[Alice, David], 3=[Bob], 7=[Charlie]} which is identical to C, so there is a mistake in the options provided.

However, based on the given options, Option B is wrong because it lists the keys in a different order (5, 3, 7) but the content is the same as C, so it is technically correct in content but the order is not guaranteed; however, the question likely expects C as the correct answer because it matches the natural insertion order. Option D is wrong because it incorrectly groups "David" under key 7 instead of key 5, and omits "David" from key 5.

416
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

Correct. groupingByConcurrent is designed for concurrent reduction and produces a ConcurrentMap, ensuring thread-safety during parallel stream processing without losing entries.

Why this answer

`Collectors.groupingByConcurrent` is designed for concurrent reduction and produces a `ConcurrentMap`, which safely handles parallel stream processing without losing keys. The default `groupingBy` uses a non-concurrent `HashMap` that can lose entries due to race conditions when multiple threads merge partial results.

Exam trap

The trap here is that candidates assume providing a concurrent map factory to `groupingBy` fixes the issue, but they overlook that the collector's internal merge logic must also be concurrent, which only `groupingByConcurrent` provides.

How to eliminate wrong answers

Option A is wrong because providing a `ConcurrentHashMap::new` factory to `groupingBy` does not make the collector thread-safe; the underlying merge logic in `groupingBy` is still non-concurrent and can cause data loss. Option B is wrong because while using `stream()` avoids the issue, it is not a fix for the requirement to use parallel processing; the question asks for the correct fix, not a workaround. Option D is wrong because `String::length` is a pure, stateless function that is inherently thread-safe; the issue is with the collector's internal accumulation, not the classifier.

417
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.

418
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

Without the code, we cannot verify if [A, B, C] is the output.

Why this answer

The program code was not provided in the question. Without the code, it is impossible to determine the output. Therefore, none of the options can be confirmed as correct.

Exam trap

The question is incomplete; the program code is missing, so no answer can be determined. Candidates should request the full question or realize that the output cannot be inferred.

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).

419
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.

420
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.

421
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.

422
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

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.

423
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

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.

424
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

`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.

425
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

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.

426
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

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>`.

427
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.

428
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

`forEachOrdered` guarantees that elements are processed in encounter order even when the stream is parallelized. The `map` operation is stateless and can run in parallel, but the terminal operation must preserve order, which `forEachOrdered` does by enforcing sequential output in the stream's encounter order.

Exam trap

The trap here is that candidates often confuse `forEach` with `forEachOrdered`, assuming that `forEach` in a parallel stream still preserves order, or they incorrectly think synchronization in `map` can fix ordering issues.

How to eliminate wrong answers

Option A is wrong because `forEach` does not guarantee encounter order in a parallel stream; it may print elements out of order. Option C is wrong because synchronizing on `System.out` inside `map` is unnecessary and inefficient; it does not fix the ordering issue because `forEach` still does not preserve order. Option D is wrong because calling `sequential()` after `parallel()` makes the stream sequential again, defeating the purpose of parallelization.

429
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.

430
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

Using an array (Transaction[]) with Arrays.sort() avoids the per-element overhead of ArrayList's internal Object[] and the additional memory consumed by the ArrayList object itself (e.g., capacity tracking, modCount). In a memory-constrained environment with 10 million transactions, the ArrayList wrapper adds roughly 40–80 MB of overhead (object header, internal array pointer, size, capacity fields), whereas a plain array has only the object header and the contiguous element references. This reduction in memory footprint directly lowers peak heap usage and reduces GC pause frequency.

Exam trap

The trap here is that candidates assume a sorted collection (TreeSet, TreeMap) is memory-efficient because it avoids explicit sorting, but they overlook the deduplication behavior of Set and the per-entry overhead of map structures, which actually increase memory usage and can corrupt data.

How to eliminate wrong answers

Option A is wrong because a TreeMap<LocalDateTime, List<Transaction>> would store each timestamp as a key and each list as a value, adding significant overhead from map entries, key objects, and list objects — actually increasing memory usage compared to a simple sorted list. Option B is wrong because a TreeSet<Transaction> deduplicates entries based on the comparator (timestamp), so if multiple transactions share the same timestamp, all but one would be silently dropped, corrupting the report output. Option C is wrong because a parallel stream with .sorted() and collect to ConcurrentLinkedDeque does not reduce peak memory usage (it may even increase due to intermediate buffers and thread overhead) and the single-threaded context makes parallelism irrelevant; additionally, ConcurrentLinkedDeque has higher per-node memory overhead than an array.

431
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

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.

432
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 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.

433
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

The correct matches are volatile for visibility, transient for serialization exclusion, and synchronized for locking. Common mistakes include confusing volatile with transient and transient with thread safety.

434
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

It first filters the stream to keep only even numbers (n % 2 == 0), then uses reduce with an identity of 1 and a multiplication lambda (a, b) -> a * b. The identity 1 is the neutral element for multiplication, ensuring that if no even numbers exist, the result is 1 rather than an error or incorrect value.

Exam trap

The trap here is that candidates often forget the identity value must be the neutral element for the reduction operation, so they pick Option B with identity 0 for multiplication, or they skip filtering entirely and pick Option C, thinking the product of all numbers is sufficient.

How to eliminate wrong answers

Option A is wrong because it uses reduce without filtering, so it multiplies all numbers together and only conditionally includes the current element based on the accumulator's parity, which is incorrect logic and can produce wrong results (e.g., for stream [2, 3], it would compute 1*2=2, then check if 2%2==0 -> true, so 2*3=6, but 3 is odd). Option B is wrong because it uses reduce with identity 0, which makes the product always 0 (since 0 multiplied by any number is 0). Option C is wrong because it multiplies all numbers in the stream without filtering for even numbers, computing the product of all integers instead of just evens.

435
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

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.

436
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

A Stream in Java cannot be reused after a terminal operation has been executed. Once the first forEach terminal operation completes, the stream is consumed and closed. Attempting to call another terminal operation (the second forEach) on the same stream reference throws an IllegalStateException with the message 'stream has already been operated upon or closed'.

Exam trap

A common misconception in OCP Java exam questions is that streams can be reused like collections, or that the exception is due to resource leaks or modification of the source.

How to eliminate wrong answers

Option A is wrong because the filter operation is indeed lazy (intermediate operations are lazy in Java streams), but laziness does not cause an IllegalStateException on a subsequent terminal operation. Option B is wrong because the map operation does not modify the source list; map returns a new stream with transformed elements and does not alter the original list. Option C is wrong because streams do not need to be explicitly closed after a terminal operation; they are automatically consumed and cannot be reused, but the exception is not about resource closure but about stream reuse.

437
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.empty().orElseThrow(IllegalStateException::new)` explicitly throws a new `IllegalStateException` when the Optional is empty. The `orElseThrow` method is designed to throw the provided exception supplier's exception if no value is present.

Exam trap

Oracle OCP Java 17 often tests the distinction between `Optional.of()` and `Optional.ofNullable()`, and the fact that `Optional.get()` throws `NoSuchElementException` rather than returning null, to catch candidates who confuse Optional with a simple null wrapper.

438
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

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.

439
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

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.

440
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

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.

441
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.

442
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.

443
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.

444
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 (e.g., those that modify shared mutable state) in parallel streams break the non-interference and statelessness requirements of the Stream API. Because parallel streams split the source into substreams processed by multiple threads, the lack of synchronization leads to race conditions, producing non-deterministic results that vary between runs.

Exam trap

The trap here is that candidates confuse stateful lambdas with structural modification of the source, incorrectly assuming ConcurrentModificationException is the primary risk, when in fact the core issue is non-determinism from unsynchronized shared state in parallel streams.

How to eliminate wrong answers

Option B is wrong because ConcurrentModificationException occurs when a stream pipeline structurally modifies the stream source (e.g., adding to a collection while iterating), not from using a stateful lambda that merely reads and writes shared mutable state. Option C is wrong because not all consequences listed apply; only non-deterministic results are a direct consequence, while ConcurrentModificationException is unrelated and improved performance is false. Option D is wrong because stateful lambdas in parallel streams typically degrade performance due to synchronization overhead or contention, and they never improve performance over stateless lambdas.

445
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

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.

446
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

Correct. It first groups books by genre, collecting prices into a list. Then it 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.

Why this answer

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.

447
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
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

448
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
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

449
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

`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.

450
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.

Page 5

Page 6 of 7

Page 7

All pages