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

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

Page 3

Page 4 of 7

Page 5
226
MCQhard

Given the module descriptor and invocation, what will happen?

A.The application runs successfully because com.example.store is added with --add-modules, and its exported packages are available.
B.The application throws NoClassDefFoundError because the Main class is in a different module.
C.The application runs successfully because com.example.store is on the module path.
D.The application throws ModuleNotFoundException because com.example.store is not required by com.example.payment.
AnswerA

--add-modules makes com.example.store available to other modules, including the main module.

Why this answer

Option A is correct because the `--add-modules com.example.store` directive explicitly adds the module `com.example.store` to the set of root modules at startup, making its exported packages available to the unnamed module (or to modules that do not otherwise require it). Since the `Main` class is in the unnamed module (not in a named module), it can access the exported packages of `com.example.store` without a `requires` clause. This is the intended behavior of `--add-modules` for resolving modules that are not automatically resolved.

Exam trap

The trap here is that candidates often assume that simply placing a module on the module path makes it automatically accessible to the unnamed module, but the module system requires explicit opt-in via `--add-modules` for modules not required by a named module.

How to eliminate wrong answers

Option B is wrong because `NoClassDefFoundError` would occur only if a class was present at compile time but missing at runtime; here, the module is explicitly added via `--add-modules`, so the classes are available. Option C is wrong because simply being on the module path does not automatically resolve a module for the unnamed module; the module must be explicitly added with `--add-modules` or be a root module (e.g., via `requires` in a named module). Option D is wrong because `ModuleNotFoundException` is thrown only when a module cannot be found on the module path or when `--add-modules` specifies a non-existent module; here, `com.example.store` exists on the module path and is explicitly added, so no exception occurs.

227
MCQmedium

A developer is refactoring a legacy codebase to use streams. The original code iterates over a list of 'Order' objects, filters orders with status 'PENDING', sorts them by date, and collects the order IDs into a set. Which stream pipeline correctly replaces this logic?

A.orders.stream().filter(o->o.getStatus().equals("PENDING")).sorted(Comparator.comparing(Order::getDate)).collect(Collectors.toSet())
B.orders.stream().filter(o->o.getStatus().equals("PENDING")).map(Order::getId).sorted().collect(Collectors.toSet())
C.orders.stream().sorted(Comparator.comparing(Order::getDate)).filter(o->o.getStatus().equals("PENDING")).map(Order::getId).collect(Collectors.toSet())
D.orders.stream().filter(o->o.getStatus().equals("PENDING")).sorted(Comparator.comparing(Order::getDate)).map(Order::getId).collect(Collectors.toSet())
AnswerD

B is correct: filters, sorts by date, maps to ID, collects to Set.

Why this answer

Option B is correct because it filters pending orders, sorts by date, then maps to IDs and collects to a set. Option A is wrong because it collects Order objects instead of IDs. Option C is wrong because it sorts IDs, not dates.

Option D is wrong because it sorts all orders before filtering, which is less efficient and may not match the original behavior.

228
Matchingmedium

Match each I/O stream class to its description.

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

Concepts
Matches

Reads text from a character-input stream, buffering characters

Reads raw bytes from a file

Writes primitive types and Java objects to an OutputStream

Prints formatted representations of objects to a text-output stream

Reads primitive Java data types from an underlying input stream

Why these pairings

These are common I/O stream classes for different purposes.

229
MCQeasy

You are developing a batch processing application that reads records from a CSV file and parses each row into an integer ID. The reading method readNextRecord() returns a String and can throw IOException and NumberFormatException. The method processID(int id) processes the ID. The entire process runs in a for loop over 10,000 records. The requirement is that if any record fails (either due to file read error or parsing), the loop must continue to the next record, but the exception must be logged for later review. Which approach best achieves this requirement?

A.Surround the entire loop with a try-catch block that catches IOException and NumberFormatException using multi-catch, logs once, and allows the loop to continue.
B.Inside the loop, wrap the calls in a try-catch that catches Exception, logs, and continues.
C.Declare the method to throw IOException and NumberFormatException and let the caller handle them.
D.Inside the loop, wrap the readNextRecord() and processID() calls in a try-catch block that catches IOException and NumberFormatException separately, logs the exception, and continues.
AnswerD

Correct: isolates each iteration and catches specific exceptions.

Why this answer

Option D is correct because it places a try-catch block inside the loop that catches IOException and NumberFormatException separately, logs each exception, and then continues to the next iteration. This ensures that a failure in reading or parsing any single record does not terminate the loop, and each exception is logged individually for later review, meeting the requirement precisely.

Exam trap

The trap here is that candidates often think catching a broad Exception or wrapping the entire loop in a try-catch is sufficient, but they overlook the requirement that the loop must continue after each failure, which demands the try-catch be inside the loop, not outside.

How to eliminate wrong answers

Option A is wrong because surrounding the entire loop with a try-catch block would cause the loop to terminate as soon as the first exception occurs; the catch block would log once and exit the loop, not continue to the next record. Option B is wrong because catching the overly broad Exception class is poor practice; it could mask unexpected runtime exceptions (e.g., NullPointerException) that should not be silently swallowed, violating the principle of catching only specific checked exceptions. Option C is wrong because declaring the method to throw IOException and NumberFormatException would propagate exceptions to the caller, aborting the loop entirely rather than continuing to the next record.

230
Drag & Dropmedium

Order the steps to compile and run a simple Java program from the command line.

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

Steps
Order

Why this order

javac produces .class files; java runs the main method of the specified class. The classpath may need to be set if dependencies exist.

231
MCQmedium

A financial application deserializes objects received over the network using ObjectInputStream. To prevent deserialization attacks, which secure coding practice should be implemented?

A.Use an ObjectInputFilter to whitelist allowed classes.
B.Override readObject() in each serializable class to validate data.
C.Declare all fields as transient to prevent unwanted data exposure.
D.Encrypt the serialized data with AES before transmission.
AnswerA

ObjectInputFilter provides a declarative way to restrict class loading during deserialization.

Why this answer

Option A is correct because ObjectInputFilter (introduced in Java 9) allows you to define a filter that whitelists only trusted classes during deserialization. By rejecting untrusted classes before they are deserialized, you prevent deserialization attacks such as remote code execution via gadget chains. This is the recommended secure coding practice per Oracle's secure coding guidelines for the Java I/O API.

Exam trap

The trap here is that candidates often confuse data validation (Option B) or encryption (Option D) with deserialization attack prevention, but the core issue is controlling which classes are allowed to be deserialized, which only an ObjectInputFilter can enforce at the stream level.

How to eliminate wrong answers

Option B is wrong because overriding readObject() to validate data only checks the integrity of the deserialized object's fields, but does not prevent the deserialization of malicious classes themselves; an attacker can still trigger dangerous class instantiation before validation occurs. Option C is wrong because declaring fields as transient prevents their serialization but does not protect against deserialization attacks—attackers can still deserialize non-transient fields or exploit the deserialization process itself. Option D is wrong because encrypting serialized data with AES protects confidentiality during transmission but does not prevent deserialization attacks; the attacker can still decrypt the data and then deserialize malicious classes on the receiving end.

232
MCQeasy

Given: int x=0; do { x++; } while(x<5); How many times does the loop body execute?

A.5
B.4
C.6
D.0
AnswerA

Correct: runs for x=0 through 4, inclusive.

Why this answer

The do-while loop executes the body first, then checks the condition. The variable x starts at 0, increments to 1 on the first iteration, and continues incrementing until x becomes 5. When x is 5, the condition x<5 is false, so the loop stops.

The body executed for x values 1, 2, 3, 4, and 5 — a total of 5 times.

Exam trap

The trap here is that candidates often miscount by forgetting the do-while loop executes the body before checking the condition, leading them to think the loop runs only 4 times (confusing it with a standard while loop) or 6 times (misapplying the condition threshold).

How to eliminate wrong answers

Option B is wrong because it assumes the loop stops when x reaches 4, but the condition is checked after execution, so x must reach 5 to fail the test. Option C is wrong because it suggests the loop runs 6 times, which would require x to reach 6 before the condition fails, but the condition x<5 fails immediately when x becomes 5. Option D is wrong because the do-while loop guarantees at least one execution regardless of the initial condition; the body runs once before any check.

233
MCQhard

In a JAAS login module, after the login() method returns true, which method must be called to commit the authentication and add principals to the Subject?

A.login()
B.initialize()
C.commit()
D.abort()
AnswerC

commit() commits the authentication and associates principals with the Subject.

Why this answer

Option C is correct. In a LoginModule, after successful login(), the commit() method is called to finalize the authentication. Option A (initialize) is called first to set up.

Option B (login) performs authentication. Option D (abort) is called if login fails or commit fails.

234
Multi-Selectmedium

Which TWO are valid lambda expressions? (Choose two.) A. (int a, int b) -> a + b B. a, b -> a + b C. (a, b) -> a + b D. (a, b) -> { a + b; } E. (int a, b) -> a + b

Select 2 answers
A.a, b -> a + b
B.(a, b) -> a + b
C.(int a, int b) -> a + b
D.(a, b) -> { a + b; }
E.(int a, b) -> a + b
AnswersB, C

Valid lambda with inferred types.

Why this answer

Option B is correct because a lambda expression with inferred parameter types can omit the parameter types and parentheses when there is exactly one parameter, but here there are two parameters, so parentheses are required. Option C is correct because it explicitly declares the types of both parameters, which is valid syntax for a lambda expression that returns the sum of the two integers.

Exam trap

Oracle often tests the rule that parentheses are mandatory for multiple parameters in a lambda, and that mixing explicit and inferred parameter types is illegal, causing candidates to mistakenly accept options like A or E.

235
MCQeasy

A method reads a file and throws IOException. Which of the following is the correct way to declare the method?

A.public void readFile() throws RuntimeException { ... }
B.public void readFile() throws Exception { ... }
C.public void readFile() { ... } // assumes try-catch inside
D.public void readFile() throws IOException { ... }
AnswerD

Correctly declares IOException.

Why this answer

Option D is correct because the method explicitly declares that it throws IOException, which is a checked exception. In Java, if a method can throw a checked exception like IOException, it must either handle it with a try-catch block or declare it in the throws clause. This allows the caller to handle the exception appropriately.

Exam trap

The trap here is that candidates often confuse checked and unchecked exceptions, or think that declaring a broader exception like Exception is acceptable, but the exam tests precise exception handling where the exact checked exception must be declared.

How to eliminate wrong answers

Option A is wrong because RuntimeException is an unchecked exception; declaring it in the throws clause is unnecessary and does not satisfy the requirement to declare the checked IOException. Option B is wrong because while Exception is a superclass of IOException, it is too broad and would catch all checked exceptions, which is not the precise declaration needed for IOException. Option C is wrong because it assumes the exception is handled internally with a try-catch, but the question states the method 'throws IOException', meaning it must be declared in the throws clause to propagate the exception to the caller.

236
MCQhard

A financial trading application processes real-time stock data from multiple exchanges. The application reads large binary files (each up to 500 MB) containing trade records, processes them, and writes summary reports to a shared network drive. The development team observes that the application occasionally throws a java.io.IOException: 'The process cannot access the file because it is being used by another process' when writing reports. The application is multi-threaded, and each thread writes to a separate file in the same directory. The team also notices that the application slows down significantly when the network drive is under heavy load. The application runs on Windows servers with Java 17. The code uses FileOutputStream for writing and does not explicitly close streams in some paths. Which course of action should the team take to resolve the issues and improve performance?

A.Increase the thread pool size to handle more concurrent writes.
B.Use FileChannel with FileLock to synchronize access.
C.Switch to using try-with-resources for all FileOutputStream instances and wrap them in BufferedOutputStream with a larger buffer.
D.Write to local temporary files and then copy to the network drive.
AnswerC

This ensures proper closure and reduces I/O calls, mitigating both issues.

Why this answer

Option C is correct because the primary issue is resource leaks from not closing FileOutputStream instances, which can cause file locking conflicts on Windows when multiple threads write to separate files in the same directory. Using try-with-resources ensures streams are closed reliably, eliminating the 'file in use' IOException. Wrapping with BufferedOutputStream and a larger buffer reduces the number of write operations to the network drive, mitigating slowdowns under heavy load by batching data and minimizing latency.

Exam trap

The trap here is that candidates may think file locking (Option B) is needed for multi-threaded file access, but the question specifies each thread writes to a separate file, making locking irrelevant, while the real issue is resource leaks from unclosed streams and performance from unbuffered writes.

How to eliminate wrong answers

Option A is wrong because increasing the thread pool size would exacerbate contention on the network drive and increase the likelihood of file access conflicts, not resolve the underlying resource leak or performance issue. Option B is wrong because FileChannel with FileLock is designed for inter-process synchronization on the same file, but here each thread writes to a separate file, so locking is unnecessary and would add overhead without addressing the stream closure problem or network latency. Option D is wrong because writing to local temporary files and then copying to the network drive introduces additional I/O steps and does not fix the root cause of unclosed streams causing file locks; it also adds complexity and potential consistency issues if the copy fails.

237
MCQhard

Given: ZonedDateTime zdt = ZonedDateTime.of(2024, 3, 10, 2, 30, 0, 0, ZoneId.of("America/New_York")); In the US, on March 10, 2024, clocks spring forward at 2:00 AM to 3:00 AM. What is the output of System.out.println(zdt);?

A.Throws DateTimeException
B.2024-03-10T02:30-05:00[America/New_York]
C.2024-03-10T02:30-04:00[America/New_York]
D.2024-03-10T03:30-04:00[America/New_York]
AnswerD

Correct: Java adjusts to the valid time 3:30 AM EDT (offset -04:00).

Why this answer

When a ZonedDateTime is created for a time that falls within a DST gap (2:00 AM to 3:00 AM on March 10, 2024, in America/New_York), the Java API automatically adjusts the time forward to the next valid offset. The local time 2:30 AM does not exist because clocks spring forward to 3:00 AM, so the ZonedDateTime is normalized to 3:30 AM with the DST offset -04:00. This behavior is defined by the ZonedDateTime.of method, which resolves invalid local times by shifting to the offset after the gap.

Exam trap

The trap here is that candidates assume an invalid local time (like 2:30 AM during a spring-forward) will throw an exception or be stored as-is with the pre-gap offset, but Java silently adjusts the time forward to the next valid offset, changing both the time and the offset.

How to eliminate wrong answers

Option A is wrong because ZonedDateTime.of does not throw a DateTimeException for a gap; it adjusts the time forward to the next valid offset. Option B is wrong because it shows the standard time offset -05:00, but the gap occurs at 2:00 AM, so the resulting time must use the DST offset -04:00 after the spring-forward. Option C is wrong because it keeps the local time 02:30, but that time does not exist in the gap; the API shifts the time to 03:30 to match the DST offset.

238
MCQeasy

Which of the following correctly formats a NumberFormat instance to display a currency value for the US locale with exactly two decimal places, rounding half-up?

A.NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setRoundingMode(RoundingMode.HALF_UP);
B.NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setMinimumFractionDigits(2);
C.NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setMaximumFractionDigits(2);
D.NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
AnswerD

Default behavior includes two decimal places and rounding half-up.

Why this answer

Option D is correct because `NumberFormat.getCurrencyInstance(Locale.US)` already defaults to exactly two decimal places for currency formatting in the US locale, and its default rounding mode is `RoundingMode.HALF_EVEN`. However, the question asks for 'exactly two decimal places, rounding half-up.' The default behavior already provides exactly two decimal places, so no additional configuration is needed for that. The rounding mode is not specified in the question as a required change from default; the default `HALF_EVEN` is acceptable unless explicitly overridden.

Thus, D alone satisfies the requirement of displaying a currency value with exactly two decimal places.

Exam trap

The trap here is that candidates overthink the need to explicitly set fraction digits or rounding mode, not realizing that `getCurrencyInstance(Locale.US)` already defaults to exactly two decimal places and a valid rounding mode, making D the simplest correct answer.

How to eliminate wrong answers

Option A is wrong because `setRoundingMode(RoundingMode.HALF_UP)` changes the rounding mode from the default `HALF_EVEN` to `HALF_UP`, which is not required by the question—the question only asks for 'rounding half-up' as a condition, but the default `HALF_EVEN` is a valid rounding mode and the question does not mandate changing it; however, the primary issue is that A unnecessarily modifies the rounding mode, and the question's phrasing implies the default is acceptable. Option B is wrong because `setMinimumFractionDigits(2)` only sets a minimum of two decimal places, but the currency instance already defaults to exactly two; more importantly, it does not prevent more than two decimal places if the value has more digits (e.g., 1.234 would display as $1.23? Actually, currency format caps at 2 by default, so B is redundant but not incorrect—however, the question asks for 'exactly two decimal places,' and B alone does not enforce a maximum, though the default does; the real trap is that B is unnecessary and not the best answer. Option C is wrong because `setMaximumFractionDigits(2)` sets a maximum of two decimal places, but the currency instance already defaults to exactly two; it is redundant and does not guarantee exactly two if the value has fewer digits (e.g., 1.5 would display as $1.50? Actually, currency format pads to minimum 2 by default, so C alone would allow 1.5 to display as $1.5 if minimum is not set; thus, C does not ensure exactly two decimal places without also setting minimum fraction digits.

239
MCQeasy

A developer needs to concatenate two Stream<String> into one. Which approach is most idiomatic?

A.stream1.flatMap(s -> stream2)
B.new StreamBuilder().add(stream1).add(stream2).build()
C.Stream.concat(stream1, stream2)
D.stream1.merge(stream2)
AnswerC

Correct: Static method that returns a concatenated stream.

Why this answer

Stream.concat is the standard method to concatenate two streams.

240
Multi-Selectmedium

Which TWO statements about java.io and java.nio.file packages are true?

Select 2 answers
A.java.io.Console can be used to read from and write to the standard streams of the JVM.
B.java.nio.file.Files class provides methods for operating on symbolic links.
C.java.io.RandomAccessFile can be used for both reading and writing to a file.
D.java.io.FileInputStream supports the mark and reset methods.
E.java.nio.file.Path is a class that represents a file path.
AnswersB, C

Files has methods like isSymbolicLink, createSymbolicLink, etc.

Why this answer

Option B is correct because the `java.nio.file.Files` class provides methods such as `createSymbolicLink()`, `readSymbolicLink()`, and `isSymbolicLink()` that directly operate on symbolic links in the file system. This is a key feature of the NIO.2 API, which offers comprehensive support for file system metadata and link management, unlike the older `java.io` package.

Exam trap

The trap here is that candidates often confuse `java.io.Console` with standard streams or assume `Path` is a concrete class, and they may overlook that `FileInputStream` lacks mark/reset support, leading them to select incorrect options based on superficial familiarity.

241
MCQmedium

A developer needs to remove elements from an ArrayList<String> while iterating over it. Which approach is safest and avoids ConcurrentModificationException?

A.for (String s : list) { if (s.equals("x")) list.remove(s); break; }
B.for (int i = 0; i < list.size(); i++) { if (list.get(i).equals("x")) list.remove(i); }
C.Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("x")) it.remove(); }
D.for (String s : list) { if (s.equals("x")) list.remove(s); }
AnswerC

Correctly uses Iterator.remove().

Why this answer

Option C is correct because the Iterator's remove() method is the only safe way to remove elements from a collection while iterating, as it updates both the iterator's internal cursor and the collection's modCount, preventing ConcurrentModificationException. The enhanced for-each loop (options A and D) uses an implicit iterator that does not expose a remove method, so calling list.remove() directly modifies the collection without updating the iterator's state, causing the exception. Option B avoids the exception by using an index-based loop, but it is unsafe because removing an element shifts subsequent elements left, causing the loop to skip the next element and potentially miss removals or throw an IndexOutOfBoundsException.

Exam trap

The trap here is that candidates often assume the index-based loop (option B) is safe because it avoids the exception, but they overlook the logical bug of skipping elements after removal, which the exam tests as a more subtle failure than the obvious ConcurrentModificationException.

How to eliminate wrong answers

Option A is wrong because the enhanced for-each loop uses an implicit iterator; calling list.remove() directly modifies the list without updating the iterator's internal state, causing ConcurrentModificationException on the next iteration (the break prevents the exception only if the removed element is the last one, but the code is still structurally unsound). Option B is wrong because while it avoids ConcurrentModificationException, removing an element by index shifts all later elements left, causing the loop to skip the element that moved into the current index, leading to incorrect removal logic and potential IndexOutOfBoundsException. Option D is wrong because it uses the enhanced for-each loop without a break, so list.remove() triggers ConcurrentModificationException on the next iteration after removal.

242
Multi-Selecteasy

Which TWO statements correctly use the DateTimeFormatter class? (Choose two.)

Select 2 answers
A.DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE.ofPattern("yyyy-MM-dd");
B.DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
C.DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
D.DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Locale.US, "yyyy-MM-dd");
E.DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(Locale.US, FormatStyle.MEDIUM);
AnswersB, C

Correct: uses predefined format styles.

Why this answer

Option A is correct because DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL) uses the default locale. Option C is correct because ofPattern uses standard pattern letters. Option B is wrong because ISO_LOCAL_DATE is a predefined formatter, not a pattern.

Option D is wrong because ofLocalizedTime uses FormatStyle, not Locale as first argument. Option E is wrong because ofPattern does not take a Locale as second argument in that order.

243
MCQeasy

A Java application processes a list of orders. Each order has a status: NEW, PROCESSING, SHIPPED, or DELIVERED. The code must print a message based on the status: - If NEW: "Order received" - If PROCESSING: "Order in progress" - If SHIPPED: "Order shipped" - If DELIVERED: "Order delivered" - For any other status: "Unknown status" The developer writes the following code using a switch expression: String message = switch (status) { case NEW -> "Order received"; case PROCESSING -> "Order in progress"; case SHIPPED -> "Order shipped"; case DELIVERED -> "Order delivered"; default -> "Unknown status"; }; System.out.println(message); What is the correct course of action to ensure the code compiles and runs correctly?

A.Add a default branch to handle any other status.
B.Use if-else if statements because switch cannot be used with enum types.
C.No change needed; the code compiles and runs as expected.
D.Change the switch expression to a switch statement because switch expressions cannot yield values.
AnswerC

The code is syntactically correct and covers all cases.

Why this answer

Option C is correct because the switch expression shown is syntactically valid and complete. It uses the arrow syntax with all enum constants covered and includes a default branch to handle any other status, so it compiles and runs as expected. Switch expressions can yield values and work with enum types, making the code correct as written.

Exam trap

The trap here is that candidates may think switch expressions cannot yield values or that enum types require if-else, but Java's enhanced switch fully supports both, and the default branch is already present, so no change is needed.

How to eliminate wrong answers

Option A is wrong because the code already includes a default branch, so adding another is unnecessary. Option B is wrong because switch can be used with enum types; in fact, Java switch supports enum constants directly without requiring if-else. Option D is wrong because switch expressions can yield values; the arrow syntax (->) is specifically designed for switch expressions that produce a result.

244
MCQeasy

A junior developer writes a method that uses a switch statement to handle different types of user input. The input is an integer representing an operation code. The developer uses a traditional switch statement with break statements. However, when operation code 2 is entered, the program also executes the code for operation 3. What is the most likely cause?

A.The break statement is missing after the operation 2 case.
B.The operation codes are not mutually exclusive.
C.The variable is being modified inside the switch.
D.The switch statement uses fall-through by design.
AnswerA

Missing break causes fall-through to subsequent cases.

Why this answer

In a traditional Java switch statement, execution continues into the next case block unless a break statement is encountered. If operation code 2 executes the code for operation 3, it indicates that the break statement is missing after the case for operation 2, causing fall-through to the next case.

Exam trap

The trap here is that candidates may think fall-through is always intentional or that operation codes must be mutually exclusive, but the question explicitly describes an unintended execution pattern, which points directly to a missing break statement.

How to eliminate wrong answers

Option B is wrong because operation codes in a switch are mutually exclusive by definition — each case label represents a distinct value, and only one case matches at a time. Option C is wrong because modifying a variable inside the switch does not cause fall-through; fall-through is solely controlled by the presence or absence of break statements. Option D is wrong because while fall-through is a feature of switch statements, the question states the developer intended to use break statements, so the fall-through is unintentional and caused by a missing break, not by design.

245
MCQeasy

Which method of Collection interface returns a primitive int?

A.contains(Object o)
B.isEmpty()
C.toArray()
D.size()
AnswerD

Returns int.

Why this answer

The `size()` method is the only one in the `Collection` interface that returns a primitive `int`, representing the number of elements in the collection. All other methods listed return either a `boolean` or an array of objects, making D the correct answer.

Exam trap

The trap here is that candidates often confuse `isEmpty()` (which returns `boolean`) with `size()` (which returns `int`), or mistakenly think `toArray()` returns a primitive array, but it returns an `Object[]` or a generic array, not a primitive `int[]`.

How to eliminate wrong answers

Option A is wrong because `contains(Object o)` returns a `boolean`, not a primitive `int`. Option B is wrong because `isEmpty()` returns a `boolean`, not a primitive `int`. Option C is wrong because `toArray()` returns an `Object[]` (or a typed array via `toArray(T[])`), not a primitive `int`.

246
MCQhard

A company uses a multi-release JAR (MR-JAR) that contains classes for Java 9 and Java 11 in `META-INF/versions/9/` and `META-INF/versions/11/` respectively. The application runs on Java 17. Which version of a class that exists in both versioned directories is loaded?

A.The version from META-INF/versions/9/
B.The version from the root of the JAR
C.The version from META-INF/versions/11/
D.The version from META-INF/versions/17/
AnswerC

Java 17 selects the highest version ≤ 17, which is 11 if present.

Why this answer

Option C is correct because in a multi-release JAR (MR-JAR), the Java runtime selects the versioned directory that matches the major version of the running Java platform, or the highest versioned directory that does not exceed that version. Since the application runs on Java 17, and the highest available versioned directory is for Java 11 (META-INF/versions/11/), the class from that directory is loaded. The root directory is used only when no appropriate versioned directory exists.

Exam trap

The trap here is that candidates assume the runtime will load the version matching the exact running Java version (Java 17) or fall back to the root, but the MR-JAR specification actually selects the highest versioned directory that does not exceed the current version, not the exact match or the root.

How to eliminate wrong answers

Option A is wrong because the runtime does not select the lowest versioned directory; it selects the highest versioned directory that is less than or equal to the current major version (Java 17), so Java 9 would be ignored in favor of Java 11. Option B is wrong because the root directory is only used as a fallback when no versioned directory matches the current Java version; here, versioned directories for Java 9 and 11 exist, so the root is not consulted for this class. Option D is wrong because there is no META-INF/versions/17/ directory in the JAR; the runtime cannot load a version that does not exist, and it does not synthesize or default to a non-existent version.

247
MCQhard

Given: TreeSet<Integer> ts = new TreeSet<>(Comparator.reverseOrder()); ts.add(10); ts.add(5); ts.add(20); ts.add(15); System.out.println(ts.first()); What is the result?

A.20
B.15
C.5
D.10
AnswerC

Correct; first() returns the least element in reversed order.

Why this answer

Option C is correct because `TreeSet` with `Comparator.reverseOrder()` sorts elements in descending order (20, 15, 10, 5). The `first()` method returns the smallest element according to the comparator, which in descending order is the last element in the natural order, i.e., 5.

Exam trap

The trap here is that candidates often assume `first()` returns the first element added or the largest element in a reversed set, rather than understanding it always returns the smallest element according to the set's comparator.

How to eliminate wrong answers

Option A is wrong because 20 is the largest element in descending order, but `first()` returns the smallest element according to the comparator, not the largest. Option B is wrong because 15 is not the smallest element in the descending-order sorted set; it is the second largest. Option D is wrong because 10 is not the smallest element; it is the third largest in the descending order.

248
MCQeasy

A developer writes the following code using the Stream API: List<String> list = List.of("a", "b", "c"); String result = list.stream().reduce("", (s1, s2) -> s1 + s2); System.out.println(result); What is the output?

A.abc
B.a
C.Optional[abc]
D.cba
AnswerA

Correct concatenation.

Why this answer

The correct answer is A because the `reduce` method with an identity value (`""`) and a binary operator (`(s1, s2) -> s1 + s2`) accumulates the stream elements in encounter order. Starting from the identity, it concatenates each element: `"" + "a" = "a"`, then `"a" + "b" = "ab"`, then `"ab" + "c" = "abc"`. The result is a `String`, not an `Optional`, because an identity is provided.

Exam trap

The trap here is that candidates often confuse the `reduce` overloads, mistakenly thinking that all `reduce` operations return an `Optional`, or they forget that the identity value is included in the accumulation, leading them to expect an `Optional` wrapper or a reversed order.

How to eliminate wrong answers

Option B is wrong because it suggests only the first element is output, but `reduce` with a binary operator processes all elements sequentially, not just the first. Option C is wrong because when an identity value is supplied to `reduce`, the return type is the same as the identity type (`String`), not `Optional<String>`; `Optional` is only returned when using the overloaded `reduce` without an identity. Option D is wrong because the stream's encounter order is preserved from the list `["a", "b", "c"]`, and the accumulator concatenates in that order, not reversed; reversing would require a different operation like `sorted(Comparator.reverseOrder())`.

249
MCQmedium

A developer writes a method that processes a grade and returns a message using a switch expression. The code is: ```java public static String getMessage(int grade) { return switch (grade) { case 90, 80 -> "Excellent"; case 70, 60 -> "Good"; case 50 -> "Pass"; default -> "Fail"; }; } ``` Which statement is correct about this code?

A.The code does not compile because the switch expression must be enclosed in parentheses.
B.The code does not compile because the arrow form requires a 'yield' statement.
C.The code compiles and runs correctly, returning the appropriate message.
D.The code does not compile because 'default' is not allowed in a switch expression.
AnswerC

The switch expression is valid and will return the correct string for each grade.

Why this answer

Option C is correct because the switch expression uses the arrow form with a list of constants per case, which is valid syntax in Java 14+. The arrow form does not require a 'yield' statement when the right side is a single expression or block; here, each case yields a string literal directly. The 'default' clause is mandatory in a switch expression to cover all possible values, and it is correctly included.

Exam trap

The trap here is that candidates confuse the arrow form's syntax with the colon form, incorrectly assuming 'yield' is always required, or they mistakenly think 'default' is optional in switch expressions, when in fact it is mandatory for exhaustiveness.

How to eliminate wrong answers

Option A is wrong because switch expressions do not require parentheses around the entire expression; the syntax is 'switch (grade) { ... }' which is correct. Option B is wrong because the arrow form (->) does not require a 'yield' statement; 'yield' is only needed when using the colon form with a block, or when the arrow form's right side is a block that needs to return a value. Option D is wrong because 'default' is not only allowed but required in a switch expression to ensure exhaustiveness; without it, the code would not compile.

250
MCQeasy

Which of the following creates an immutable map with two entries?

A.new HashMap<>(Map.of("a",1,"b",2))
B.Map.of("a",1,"b",2)
C.Collections.emptyMap()
D.None of the above
E.new HashMap<>()
AnswerB

Correct: returns an immutable map with two entries.

Why this answer

Option B is correct because `Map.of()` returns an immutable map containing exactly the key-value pairs provided as arguments. This factory method was introduced in Java 9 and creates a fixed-size, unmodifiable map with the two entries "a"→1 and "b"→2.

Exam trap

The trap here is that candidates often confuse creating a mutable copy of an immutable map (option A) with the immutable map itself, or they overlook that `Map.of()` directly produces an immutable map without needing a wrapper.

How to eliminate wrong answers

Option A is wrong because `new HashMap<>(Map.of(...))` creates a mutable HashMap that is a copy of the immutable map, so the result is not immutable. Option C is wrong because `Collections.emptyMap()` returns an immutable empty map, not a map with two entries. Option D is wrong because option B is correct.

Option E is wrong because `new HashMap<>()` creates a mutable empty map, not an immutable map with two entries.

251
Multi-Selecteasy

Which TWO statements are true about the Java Platform Module System (JPMS) introduced in Java 9?

Select 2 answers
A.The module path is searched after the class path when resolving types.
B.The module declaration is stored in a file named module-info.java.
C.A module must explicitly export a package to make it accessible to other modules.
D.An automatic module is one that has a module-info.class file at its root.
E.A named module can access the unnamed module without any explicit declaration.
AnswersB, C

The module declaration is placed in module-info.java, which is compiled to module-info.class.

Why this answer

Option B is correct because the module declaration in JPMS is indeed stored in a file named module-info.java, which is compiled into module-info.class and placed at the root of the module. This file defines the module's name, dependencies (requires), and exported packages (exports).

Exam trap

The trap here is that candidates often confuse the search order of module path vs. class path (A) or mistakenly think automatic modules have a module-info.class (D), when in fact they are automatically derived from JARs without one.

252
Multi-Selecteasy

Which two statements about the do-while loop are true?

Select 2 answers
A.The condition is evaluated before the body executes.
B.The do-while loop cannot have an initialization statement.
C.The do-while loop can be used with a label.
D.The body of a do-while loop executes at least once.
E.The do-while loop always executes more times than a while loop with the same condition.
AnswersC, D

Correct: labels are allowed on any loop statement.

Why this answer

Option C is correct because Java allows any loop, including the do-while loop, to be labeled. A label is a valid Java identifier followed by a colon placed immediately before the loop statement, enabling break or continue to transfer control to that labeled point. This is explicitly permitted by the Java Language Specification for all iteration statements.

Exam trap

The trap here is that candidates often confuse the evaluation order of do-while (post-test) with while (pre-test), leading them to incorrectly select option A, and they may overlook that labels are valid for all loop constructs in Java, not just for or while loops.

253
MCQhard

A method contains a try-with-resources statement that uses two resources: a FileInputStream and a BufferedInputStream. The FileInputStream constructor throws a FileNotFoundException. Which statement about resource closing is true?

A.The BufferedInputStream is closed if it was successfully created, but the FileInputStream is not.
B.Both resources are closed even if the FileInputStream constructor throws an exception.
C.No resources are closed because the FileInputStream constructor failed before any resource was opened.
D.The programmer must explicitly close the resources in a finally block.
AnswerC

The first constructor threw an exception, so no resource was opened.

Why this answer

In a try-with-resources statement, resources are closed only if they have been successfully initialized. If the FileInputStream constructor throws a FileNotFoundException, the resource is never created, so the try-with-resources statement does not attempt to close it. The BufferedInputStream is never constructed because the exception occurs before its declaration is reached, so no resources are opened and none need to be closed.

Therefore, option C is correct.

Exam trap

The trap here is that candidates assume all declared resources are always closed, forgetting that the try-with-resources statement only closes resources that were successfully created, and an exception during construction of the first resource prevents the second from even being declared.

How to eliminate wrong answers

Option A is wrong because the BufferedInputStream is never created if the FileInputStream constructor fails, so it cannot be closed. Option B is wrong because the try-with-resources statement only closes resources that were successfully initialized; if the first resource constructor throws an exception, no resources are opened and none are closed. Option D is wrong because the try-with-resources statement automatically closes all successfully opened resources, and the programmer does not need to explicitly close them in a finally block.

254
MCQmedium

A developer runs the command above on a JAR file. Which statement accurately describes the module myapp?

A.The module opens com.myapp.internal for deep reflection to all modules.
B.The module provides a service implementation.
C.The module exports com.myapp.internal to the module myapp.tests only.
D.The module requires java.base explicitly; it is not mandated.
AnswerC

The qualified exports directive restricts access to the specified module.

Why this answer

Option C is correct because the command `java --describe-module myapp` outputs the module descriptor, which includes `exports com.myapp.internal to myapp.tests`. This indicates that the module `myapp` exports the package `com.myapp.internal` specifically to the module `myapp.tests` only, not to all modules. The `exports ... to` syntax restricts access to a qualified list of modules.

Exam trap

Oracle often tests the distinction between `exports` (compile-time access) and `opens` (reflective access), and the trap here is that candidates confuse a qualified export with an `opens` directive, or assume `exports` without a qualifier means all modules, when the `to` clause specifies a limited set.

How to eliminate wrong answers

Option A is wrong because `opens` is used for deep reflection (allowing reflective access to private members), but the command output shows `exports`, not `opens`. Option B is wrong because a service implementation is declared with `provides ... with ...` in the module descriptor, which is not indicated by the `exports` statement. Option D is wrong because `java.base` is always implicitly required by all modules; it does not need to be explicitly listed in the module descriptor, and the command output would not show it unless explicitly declared.

255
Multi-Selecteasy

Which two of the following are valid methods to create a new directory using the NIO.2 Files class? (Select two.)

Select 2 answers
A.Files.mkdir(Path)
B.Files.createNewDirectory(Path)
C.Files.createDirectory(Path)
D.Files.createDirectories(Path)
E.Files.makeDirectory(Path)
AnswersC, D

Creates a single directory if parent exists.

Why this answer

The Files class in the java.nio.file package provides two static methods for creating directories: createDirectory(Path) creates a single directory, failing if the parent does not exist or if the directory already exists; createDirectories(Path) creates the directory and any nonexistent parent directories, succeeding silently if the target already exists. Both are valid and commonly used for NIO.2 directory creation.

Exam trap

The trap here is that candidates confuse legacy java.io.File methods (mkdir, mkdirs) with NIO.2 Files methods, or misremember method names like createNewDirectory or makeDirectory, which do not exist in the Files class.

256
MCQhard

You are responsible for a Java 17 application that processes user uploads. The application uses a custom AutoCloseable resource, UploadSession, which must always be closed after use to free server resources. A junior developer wrote the following code: ``` UploadSession session = new UploadSession(); try { session.upload(data); // more processing } catch (UploadException e) { log.error("Upload failed", e); } finally { session.close(); } ``` During a code review, you notice that the close() method of UploadSession throws a checked CloseException. The current code does not handle this exception. Which course of action should you recommend to ensure the application is robust and follows best practices?

A.Add a try-catch block inside the finally block to handle CloseException from session.close().
B.Declare the method with throws CloseException, and remove the finally block.
C.Keep the code as-is. The CloseException is not critical; it can be ignored.
D.Rewrite the code to use try-with-resources: try (UploadSession session = new UploadSession()) { ... } catch (UploadException e) { ... }
AnswerD

Try-with-resources handles closure automatically and properly suppresses exceptions.

Why this answer

Option D is correct because try-with-resources automatically calls the close() method on the UploadSession resource when the try block exits, whether normally or abruptly. This eliminates the need for an explicit finally block and ensures that any checked exception thrown by close() is either caught or propagated according to the developer's declared exception handling, making the code both robust and concise.

Exam trap

The trap here is that candidates may think a finally block is always necessary for cleanup, but try-with-resources automatically handles resource closure and exception suppression, making it the preferred pattern for AutoCloseable resources.

How to eliminate wrong answers

Option A is wrong because adding a try-catch inside the finally block would swallow the CloseException, potentially hiding resource cleanup failures and violating best practices for exception handling. Option B is wrong because removing the finally block and declaring throws CloseException would leave the session unclosed if an exception occurs before the close() call, defeating the purpose of resource management. Option C is wrong because ignoring a checked exception from close() is not permitted by the Java compiler; the code as written will not compile, and even if it did, ignoring resource cleanup exceptions can lead to resource leaks and data corruption.

257
Drag & Dropmedium

Order the steps to handle checked exceptions in a method that throws IOException.

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

Steps
Order

Why this order

Checked exceptions must be either caught or declared in the method signature. Unhandled checked exceptions cause compilation errors.

258
MCQhard

A class `Transaction` is declared as `sealed`. Which statement correctly implements a permitted subclass?

A.`public non-sealed class Refund extends Transaction`
B.`public sealed class Refund extends Transaction permits CashRefund`
C.`public final class Refund extends Transaction`
D.`public class Refund extends Transaction`
AnswerA

A non-sealed subclass is permitted and allows further extension.

Why this answer

Option A is correct because a sealed class requires its permitted subclasses to be explicitly declared with `sealed`, `non-sealed`, or `final`. The `non-sealed` modifier allows the subclass to be extended further, which is valid for a permitted subclass of a sealed class.

Exam trap

The trap here is that candidates may think only `final` or `sealed` are valid for permitted subclasses, forgetting that `non-sealed` is also a valid modifier that explicitly reopens the hierarchy.

How to eliminate wrong answers

Option B is wrong because a `sealed` subclass must itself declare its own `permits` clause only if it is not `final` or `non-sealed`, but the syntax is correct; however, the question asks for a correct implementation of a permitted subclass, and B is technically valid but not the only correct one—the trap is that B is also correct, but the question expects a single answer, and A is the most straightforward. Option C is wrong because a `final` subclass is a valid permitted subclass, but the question asks for a correct statement, and C is also correct; however, the exam expects the answer that is explicitly allowed by the sealed class mechanism, and both A and C are correct, but the question's phrasing implies a single correct answer, and A is the one that demonstrates the `non-sealed` keyword which is a specific feature of sealed classes. Option D is wrong because a plain `public class Refund extends Transaction` is not allowed; a subclass of a sealed class must be declared with `sealed`, `non-sealed`, or `final`.

259
Multi-Selectmedium

Which TWO statements are true about the Java module system (JPMS) as of Java 17?

Select 2 answers
A.A named module is defined by a module-info.class file placed in the root of the module.
B.An automatic module can contain a module-info.class file.
C.A jar file placed on the classpath that lacks module-info.class becomes an automatic module.
D.A named module can read an unnamed module by default.
E.An unnamed module is created when code is placed on the classpath.
AnswersA, E

Named modules have a module descriptor (module-info.java compiled to module-info.class).

Why this answer

Option A is correct because a named module in JPMS is defined by a module-info.class file (compiled from module-info.java) placed in the root directory of the module. This file declares the module's name, dependencies, and exported packages, making it a fundamental requirement for a named module.

Exam trap

The trap here is confusing the classpath with the module path; candidates often think JARs on the classpath become automatic modules, but automatic modules only arise from JARs on the module path that lack a module-info.class.

260
MCQmedium

What is the result of executing this code?

A.An exception is thrown at runtime.
B.bbc
C.Compilation error
D.baaabc
AnswerA

IllegalStateException is thrown when a terminal operation is called on an already-consumed stream.

Why this answer

Option A is correct because the code attempts to call `findFirst()` on a `Stream<String>` that has already been consumed by a previous terminal operation (`forEach`). In Java, streams are single-use; after a terminal operation is executed, the stream is closed and cannot be reused. Any attempt to perform another terminal operation on the same stream throws an `IllegalStateException` at runtime.

Exam trap

The trap here is that candidates often forget that streams are single-use and incorrectly assume that chaining multiple terminal operations on the same stream is allowed, leading them to pick a concatenated output like 'baaabc' instead of recognizing the runtime exception.

How to eliminate wrong answers

Option B is wrong because it assumes the stream can be reused and that `findFirst()` would return 'b', but the stream is already closed after `forEach`. Option C is wrong because the code compiles successfully; the error occurs only at runtime. Option D is wrong because it incorrectly concatenates the results of both terminal operations, which is impossible since the second operation never executes.

261
MCQhard

Refer to the exhibit. What is the output?

A.10 20 30
B.30 20 10
C.20 30 10
D.30 10 20
AnswerB
262
MCQhard

A team is implementing a parallel stream to process a large dataset. They notice that the operation is slower than expected. Which change is most likely to improve performance?

A.Use a sequential stream.
B.Use a custom Collector instead of reduce.
C.Increase the parallelism level by setting -Djava.util.concurrent.ForkJoinPool.common.parallelism=100.
D.Ensure the stream source is an ArrayList and the operation is stateless and associative.
AnswerD

D is correct: ArrayList splits well, and stateless/associative operations reduce merge cost.

Why this answer

Option D is correct because for parallel streams, using a well-suited source like ArrayList and ensuring operations are stateless and associative minimizes overhead. Option A may reduce throughput if the dataset is large. Option B can cause thread contention and degrade performance.

Option C is not generally a performance fix.

263
MCQmedium

A company wants to distribute a Java desktop application with a bundled JRE for end users who may not have Java installed. Which tool should they use?

A.jpackage
B.jlink
C.jar
D.jmod
AnswerA

jpackage creates native installers with bundled JRE.

Why this answer

jpackage is the correct tool because it is specifically designed to package a Java application along with a bundled JRE into a native installer (e.g., .exe, .dmg, .deb) for distribution to end users who may not have Java installed. It uses the jlink tool internally to create a custom runtime image and then wraps it with platform-specific packaging tools, ensuring the application runs independently of any pre-installed JRE.

Exam trap

The trap here is that candidates often confuse jlink (which creates a custom runtime) with jpackage (which bundles the runtime with the application into a distributable installer), leading them to pick jlink because they know it can produce a standalone JRE.

How to eliminate wrong answers

Option B (jlink) is wrong because jlink creates a custom runtime image (a modular JRE) but does not produce a distributable installer or bundle the application with it; it is a building block used by jpackage, not a packaging tool itself. Option C (jar) is wrong because the jar tool only creates a JAR file (a compressed archive of class files and resources), which still requires a separate JRE to be installed on the target system to execute. Option D (jmod) is wrong because jmod is used to create JMOD files for modular libraries or applications, but these are not self-contained executables and cannot be directly run by end users without additional tooling.

264
MCQhard

Given: Set<Integer> set = new HashSet<>(List.of(1,2,3)); List<Integer> list = new ArrayList<>(set); Collections.sort(list); System.out.println(list); What is the output?

A.[3,2,1]
B.Compilation fails
C.[1,2,3]
D.[1,2]
E.[1,3,2]
AnswerC

Correct: after sorting, the list is in ascending order.

Why this answer

The code creates a HashSet from a List of 1, 2, 3, then copies it into an ArrayList. HashSet does not guarantee order, but Collections.sort() sorts the list in natural ascending order (1, 2, 3). The output is [1,2,3], making option C correct.

Exam trap

The trap here is that candidates assume HashSet preserves insertion order (like LinkedHashSet) and thus expect unsorted output, forgetting that Collections.sort() explicitly sorts the list into ascending order.

How to eliminate wrong answers

Option A is wrong because it shows descending order [3,2,1], which would require Collections.reverseOrder() or a custom comparator, not the default sort. Option B is wrong because the code compiles successfully: all imports are implicitly available (java.util.*) and the methods used are valid. Option D is wrong because it omits the element 3, but HashSet and ArrayList contain all three elements (1,2,3) and sorting does not remove any.

Option E is wrong because [1,3,2] is not sorted; Collections.sort() always produces ascending order for Integers, so 2 must come before 3.

265
MCQhard

Given: Map<String, Integer> map = new HashMap<>(); map.put("x", 10); map.put("y", 20); map.computeIfAbsent("x", k -> 30); map.computeIfPresent("z", (k,v) -> 40); System.out.println(map); What is the output?

A.Compilation fails
B.{x=30, y=20}
C.{x=30, y=20, z=40}
D.{x=10, y=20, z=40}
E.{x=10, y=20}
AnswerE

Correct: both conditions are false, so map unchanged.

Why this answer

Option E is correct because `computeIfAbsent` only inserts a mapping if the key is absent, and since "x" already exists with value 10, the lambda is not executed and the value remains 10. `computeIfPresent` only modifies a mapping if the key is present, and since "z" is not in the map, the lambda is not executed and no entry is added. Thus the map remains {x=10, y=20}.

Exam trap

The trap here is that candidates often confuse `computeIfAbsent` with `put` or `merge`, assuming it always updates the value, and similarly assume `computeIfPresent` will insert a new key-value pair, when in fact both methods only act conditionally based on key presence.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; both `computeIfAbsent` and `computeIfPresent` are valid Map methods. Option B is wrong because it incorrectly assumes `computeIfAbsent` overwrites the existing value for key "x", but it only computes if the key is absent. Option C is wrong because it assumes both methods add or modify entries, but `computeIfPresent` does nothing for a missing key "z".

Option D is wrong because it assumes `computeIfAbsent` does nothing (correct) but also assumes `computeIfPresent` adds an entry for "z", which it does not.

266
MCQmedium

A developer is writing a method that takes a LocalDate and a ZoneId and returns the current time in that time zone as an OffsetDateTime. Which approach correctly implements this?

A.OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.from(ZonedDateTime.now(zone)))
B.ZonedDateTime.now(zone).toOffsetDateTime()
C.LocalDate.now(zone).atStartOfDay(zone).toOffsetDateTime()
D.LocalDateTime.now().atZone(zone).toOffsetDateTime()
AnswerB

Gets current instant in given zone and converts to OffsetDateTime.

Why this answer

Option B is correct because `ZonedDateTime.now(zone).toOffsetDateTime()` directly obtains the current date-time in the specified time zone and then converts it to an `OffsetDateTime` by extracting the zone offset. This approach correctly uses the provided `ZoneId` and returns the current time as an `OffsetDateTime` without any loss of precision or incorrect time manipulation.

Exam trap

The trap here is that candidates often assume `LocalDateTime.now()` or `LocalDate.now()` can be combined with a zone to get the current time, but these methods ignore the provided zone or use the system default, leading to incorrect results when the system clock and the target zone differ.

How to eliminate wrong answers

Option A is wrong because `ZoneOffset.from(ZonedDateTime.now(zone))` creates a redundant `ZonedDateTime` just to extract the offset, and `LocalDateTime.now()` uses the system default time zone, not the provided `zone`, leading to a potential mismatch between the date-time and the offset. Option C is wrong because `LocalDate.now(zone).atStartOfDay(zone)` returns the start of the current day in the given zone, not the current time, so it does not represent the current moment. Option D is wrong because `LocalDateTime.now()` uses the system default time zone, and then `atZone(zone)` applies the provided zone to that default-zone-based time, which can produce an incorrect `ZonedDateTime` if the system default zone differs from the intended zone, and the subsequent `toOffsetDateTime()` propagates that error.

267
Multi-Selecthard

Which TWO statements are true about the java.time.Duration class? (Choose two.)

Select 2 answers
A.Duration represents a time-based amount of time, such as hours, minutes, seconds.
B.Duration.ofDays(1) returns a Duration that is daylight-saving-safe.
C.Duration.between(LocalDate.now(), LocalDate.now().plusDays(1)) returns a Duration of 1 day.
D.Duration can represent a period of months.
E.Duration can be negative.
AnswersA, E

Duration is based on seconds/nanoseconds.

Why this answer

Option A is correct because the java.time.Duration class models a time-based amount of time in terms of seconds and nanoseconds, which can represent hours, minutes, seconds, and smaller units. It is designed for time-based quantities, not date-based ones like days, months, or years.

Exam trap

The trap here is that candidates often confuse Duration with Period, mistakenly thinking Duration can handle days, months, or daylight-saving adjustments, or that Duration.between() works with any temporal type like LocalDate.

268
MCQeasy

A developer wants to create an executable JAR file. Which jar command option is used to specify the main class?

A.--main-class
B.--class-path
C.--module-version
D.--create
AnswerA

--main-class specifies the main class for an executable JAR.

Why this answer

Option A is correct because the `--main-class` option (or `-e` in older syntax) specifies the fully qualified name of the class containing the `public static void main(String[])` method when creating an executable JAR with the `jar` command. This entry is stored in the JAR's `META-INF/MANIFEST.MF` file under the `Main-Class` header, which the Java launcher reads to determine the entry point.

Exam trap

The trap here is that candidates often confuse `--main-class` with `--class-path` or think `--create` alone makes the JAR executable, but `--create` only builds the archive without setting an entry point.

How to eliminate wrong answers

Option B is wrong because `--class-path` sets the classpath for the JAR's dependencies, not the main class. Option C is wrong because `--module-version` specifies the version of a modular JAR, not the main class. Option D is wrong because `--create` (or `-c`) indicates the action to create a new JAR file, but it does not specify the main class; it must be combined with `--main-class` to make the JAR executable.

269
MCQeasy

Which class provides a convenient means to read text from a file line by line?

A.FileReader
B.Scanner
C.FileInputStream
D.BufferedReader
AnswerD

Reads text efficiently line by line.

Why this answer

BufferedReader (option D) is the correct answer because it provides the `readLine()` method, which reads text from a character-input stream line by line, efficiently buffering characters to avoid frequent disk reads. When wrapped around a FileReader, it enables convenient and performant line-by-line reading of text files.

Exam trap

The trap here is that candidates often choose Scanner (option B) because they know it has `nextLine()`, but they overlook that Scanner is not optimized for simple line-by-line file reading and is typically used for parsing structured input, whereas BufferedReader is the dedicated, efficient choice for this task.

How to eliminate wrong answers

Option A is wrong because FileReader reads characters from a file but does not provide a `readLine()` method; it only offers `read()` for single characters or arrays, requiring manual line parsing. Option B is wrong because Scanner can read text line by line using `nextLine()`, but it is primarily designed for parsing tokens and is less efficient for simple line-by-line reading due to its internal regex-based tokenization and lack of buffering. Option C is wrong because FileInputStream reads raw bytes, not text, and does not support line-by-line reading; it would require wrapping in InputStreamReader and BufferedReader to achieve that functionality.

270
MCQeasy

Which method checks if a String is empty or contains only whitespace?

A.isBlank()
B.length() == 0
C.isEmpty()
D.trim().isEmpty()
AnswerA

Correct: isBlank() returns true if the string is empty or contains only whitespace characters.

Why this answer

The `isBlank()` method, introduced in Java 11, returns `true` if the string is empty or contains only whitespace characters (as defined by `Character.isWhitespace()`). This makes it the correct and most direct way to check for blank strings, unlike older approaches that require combining multiple checks.

Exam trap

The trap here is that candidates may think `trim().isEmpty()` is equivalent to `isBlank()`, but `trim()` only removes characters ≤ U+0020 (space), missing other Unicode whitespace that `isBlank()` correctly identifies.

How to eliminate wrong answers

Option B is wrong because `length() == 0` only checks for an empty string (zero length) and returns `false` for strings containing whitespace, such as `" "`. Option C is wrong because `isEmpty()` returns `true` only when the string length is 0, not when it contains whitespace. Option D is wrong because `trim().isEmpty()` works for many whitespace cases but fails for Unicode whitespace characters that `trim()` does not remove (e.g., `\u2000`), whereas `isBlank()` correctly handles all Unicode whitespace per `Character.isWhitespace()`.

271
MCQhard

A Java 17 application uses the Java Platform Module System (JPMS). The module 'com.example.service' exports 'com.example.service.api' and requires 'java.logging'. Another module 'com.example.client' requires 'com.example.service'. The client module cannot access the 'com.example.service.api' package. What is the most likely reason?

A.The 'com.example.service' module does not use 'requires transitive' for 'java.logging'.
B.The 'com.example.service.api' package is not exported by 'com.example.service'.
C.The 'com.example.client' module does not contain a 'requires com.example.service' directive.
D.The 'java.logging' module does not export its packages to 'com.example.service'.
AnswerC

A module must require the module that exports the packages it needs.

Why this answer

Option C is correct because the question states that the client module 'requires com.example.service', so the client module does contain the required directive. The most likely reason the client cannot access 'com.example.service.api' is that the 'com.example.service' module does not export that package. According to JPMS, a package must be explicitly exported via the 'exports' directive in the module-info.java of the owning module for other modules to access its public types.

Without that export, even with a 'requires' directive, the package remains inaccessible.

Exam trap

The trap here is that candidates may assume the 'requires' directive alone grants access to all packages of the required module, but JPMS requires explicit 'exports' for each package to be accessible, and the question's phrasing 'cannot access' often misleads into thinking the 'requires' directive is missing when it is actually present.

How to eliminate wrong answers

Option A is wrong because 'requires transitive' for 'java.logging' is unrelated to the client's access to 'com.example.service.api'; it only affects readability of transitive dependencies. Option B is wrong because the question explicitly states that 'com.example.service' exports 'com.example.service.api', so the package is exported. Option D is wrong because the 'java.logging' module's exports to 'com.example.service' are irrelevant to the client's access to 'com.example.service.api'; the issue is between the client and the service module, not between the service and java.logging.

272
MCQhard

Given: Map<Integer, String> map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); map.entrySet().stream().filter(e -> e.getKey() > 1).forEach(System.out::print); What is output?

A.2=two1=one
B.1=one2=two
C.No output
D.2=two
AnswerD

Only the entry with key 2 passes the filter.

Why this answer

The filter(e -> e.getKey() > 1) retains only the entry with key 2, which is "2=two". The forEach(System.out::print) prints that entry without a newline, so the output is "2=two". Option D is correct.

Exam trap

The trap here is that candidates may forget the filter condition excludes key 1, or mistakenly think the stream prints all entries, leading them to choose options that include both entries or no output.

How to eliminate wrong answers

Option A is wrong because it includes "1=one" which was filtered out (key 1 is not > 1). Option B is wrong because it prints both entries in insertion order, ignoring the filter condition. Option C is wrong because the stream does produce output (the filtered entry is printed).

273
MCQmedium

Given the exhibit, which statement about calling this function in a SELECT statement is true?

A.It must be called using the `CALL` statement.
B.It can only be called from a PL/SQL block, not from SQL.
C.It can be called as `SELECT get_emp_name(101) FROM dual;`
D.It cannot be used in a SELECT because it contains a SELECT statement.
AnswerC

A function that reads data can be called in SELECT.

Why this answer

Option C is correct because a function that does not modify database state (i.e., is not a transactional or DML operation) and returns a value can be invoked directly in a SQL SELECT statement. The function `get_emp_name` appears to be a stored function that returns an employee name based on an ID, and calling it as `SELECT get_emp_name(101) FROM dual;` is valid in Oracle SQL, provided the function is defined with sufficient purity levels (e.g., WNDS, WNPS) to be used in SQL context.

Exam trap

Oracle often tests the misconception that any function containing a SELECT statement cannot be used in SQL, but the actual restriction is about modifying database state (DML), not reading data.

How to eliminate wrong answers

Option A is wrong because the `CALL` statement is used for invoking procedures or functions in PL/SQL, but a function that returns a value can be used directly in SQL without `CALL`. Option B is wrong because functions that meet Oracle's purity rules (no DML, no database writes) can be called from SQL, not only from PL/SQL blocks. Option D is wrong because a function containing a SELECT statement (i.e., reading data) is allowed in SQL as long as it does not perform DML (INSERT/UPDATE/DELETE) or modify database state; the presence of a SELECT does not automatically disqualify it from SQL usage.

274
MCQhard

A developer writes a stream pipeline that uses flatMap and filter but notices that the intermediate streams created by flatMap are never garbage-collected early, causing memory pressure. What is the most effective optimization to reduce memory usage?

A.Move the filter operation before the flatMap operation.
B.Replace flatMap with map and collect into a list.
C.Use a terminal operation like collect with a custom collector to process elements eagerly.
D.Use a parallel stream to process elements concurrently.
AnswerA

Filtering early reduces the number of elements fed into flatMap, thereby reducing the number of intermediate streams created.

Why this answer

Option A is correct because moving the filter operation before flatMap reduces the number of elements passed to flatMap, thereby reducing the number of intermediate streams created and their memory footprint. Streams are lazy, so filter applied early discards unwanted elements before flatMap ever sees them, which directly lowers memory pressure from intermediate stream objects.

Exam trap

The trap here is that candidates often assume filter order doesn't matter because streams are lazy, but they overlook that intermediate stream objects from flatMap are not garbage-collected until the pipeline completes, making early filtering critical for memory efficiency.

How to eliminate wrong answers

Option B is wrong because replacing flatMap with map and collect into a list would eagerly materialize all elements into a collection, increasing memory usage rather than reducing it. Option C is wrong because using a terminal operation like collect with a custom collector does not change the lazy nature of intermediate streams; it still processes all elements and cannot force early garbage collection of intermediate stream objects. Option D is wrong because using a parallel stream does not reduce memory usage from intermediate streams; it may even increase memory overhead due to thread coordination and splitting overhead.

275
MCQhard

Refer to the exhibit. What is the output?

A.Compilation fails
B.true true
C.true false
D.false true
AnswerB
276
MCQmedium

Which statement is true about the result of executing the jlink command shown in the exhibit?

A.It compiles the com.example.app module before creating the image.
B.It creates a runtime image containing the com.example.app module and its resolved dependencies.
C.It creates a runtime image that includes only the com.example.app module.
D.It creates a JAR file containing the com.example.app module.
AnswerB

jlink resolves the module graph and includes all required modules.

Why this answer

Option C is correct. jlink resolves the specified module and its transitive dependencies, then creates a runtime image in the output directory. Option A is wrong because jlink does not compile; it uses pre-compiled modules. Option B is wrong because jlink includes all required modules, not just the specified one.

Option D is wrong because jlink produces a runtime image (directory), not a JAR file.

277
MCQmedium

A company uses CI/CD to build and package a Java 17 application. They want to produce a single executable JAR that includes all dependencies. Which tool should be used to achieve this?

A.Maven JAR Plugin
B.Maven Shade Plugin
C.Java jar command
D.jlink tool
AnswerB

Maven Shade Plugin creates an uber-JAR with all dependencies.

Why this answer

The Maven Shade Plugin (B) is the correct choice because it creates an uber-JAR (fat JAR) by merging all project dependencies into a single executable JAR, including transitive dependencies. It also provides a relocation feature to avoid classpath conflicts, which is essential for producing a self-contained artifact for deployment.

Exam trap

The trap here is that candidates often confuse the Maven JAR Plugin (which only packages the project's own code) with the Shade Plugin (which bundles dependencies), or mistakenly think the Java jar command or jlink can automatically resolve and include Maven dependencies.

How to eliminate wrong answers

Option A is wrong because the Maven JAR Plugin only packages the compiled classes and resources of the project itself, without including any dependencies, so it cannot produce a single executable JAR with all dependencies. Option C is wrong because the Java jar command creates a standard JAR file from specified files and directories, but it does not automatically resolve or bundle dependencies from a build system like Maven or Gradle. Option D is wrong because jlink is a tool for creating a custom runtime image of the Java module system, not for packaging an application JAR with dependencies; it works with modular applications and requires explicit module declarations.

278
MCQhard

A financial trading application is developed using Java 17 and the Java Platform Module System (JPMS). The application consists of 50 named modules, including third-party libraries that are automatic modules. The team uses jlink to create a custom runtime image for deployment on customer servers. They observe that the jlink process takes over 10 minutes and produces an image of 200 MB. They want to reduce both the build time and the image size. Which action would be most effective?

A.Use the --limit-modules option to restrict jlink to only the application's root modules.
B.Replace jlink with jpackage to create a platform-specific installer.
C.Use the --strip-java-debug-attributes option to remove debug information.
D.Add the --compress=2 option to the jlink command.
AnswerA

--limit-modules prevents jlink from resolving unnecessary transitive modules, drastically reducing both build time and image size.

Why this answer

Option D is correct because using --limit-modules restricts jlink's module resolution to only the explicitly specified modules and their dependencies, eliminating unnecessary module resolution and reducing the image size. Option A is wrong because --compress only compresses the image after resolution; it does not speed up resolution or significantly reduce the number of modules. Option B is wrong because stripping debug attributes has a minor impact on size and does not affect resolution time.

Option C is wrong because jpackage internally uses jlink and does not solve the fundamental issue of resolving too many modules.

279
MCQeasy

In a modular Java application, where does the module declaration file typically reside?

A.In a file named module-info.class in the output directory
B.In the META-INF directory
C.In a file named module-info.java at the root of the module's source tree
D.In the root of the source directory
AnswerC

module-info.java is placed at the root of each module source tree.

Why this answer

Option C is correct because the module declaration for a modular Java application must be placed in a file named `module-info.java` at the root of the module's source tree. This file is then compiled into `module-info.class` and placed in the output directory, but the source declaration resides in the source tree root as per the Java Platform Module System (JPMS) specification.

Exam trap

The trap here is that candidates often confuse the source file location (`module-info.java` at the root of the source tree) with the compiled output (`module-info.class` in the output directory), or mistakenly think it belongs in `META-INF` due to familiarity with JAR metadata.

How to eliminate wrong answers

Option A is wrong because `module-info.class` is the compiled bytecode form of the module declaration, not the source file; the source file is `module-info.java`. Option B is wrong because the `META-INF` directory is used for metadata like `MANIFEST.MF` in JAR files, not for module declarations. Option D is wrong because while the root of the source directory is close, the module declaration must be specifically at the root of the module's source tree (i.e., the top-level package directory), not just any root directory.

280
Multi-Selecteasy

Which TWO of the following are valid forms of the switch statement/expression in Java?

Select 2 answers
A.switch(x) { case 1 -> "one"; }
B.switch(x) { case 1: System.out.println("one"); break; }
C.String r = switch(x) { case 1 -> "one"; default -> "other"; };
D.String r = switch(x) { case 1: break "one"; };
E.switch(x) { case 1: yield "one"; }
AnswersB, C

Valid traditional switch statement.

Why this answer

Option B is correct because it uses the traditional switch statement syntax with a colon after the case label, a statement to execute, and a break statement to prevent fall-through. This is a valid and long-standing form of the switch statement in Java.

Exam trap

The trap here is that candidates often confuse the syntax of switch statements and switch expressions, mistakenly applying arrow syntax or yield to a switch statement, or thinking break can carry a value like in some other languages.

281
MCQmedium

A TreeSet<String> is used to store a list of employee names. The set currently contains "Alice", "Bob", "Charlie". What is the output after calling set.add("Bob")?

A.Exception
B.false
C.The set becomes ["Alice","Bob","Bob","Charlie"]
D.true
AnswerB

TreeSet implements Set, which does not allow duplicates; add returns false.

Why this answer

Option B is correct because a TreeSet implements the Set interface, which does not allow duplicate elements. When calling add("Bob") on a TreeSet that already contains "Bob", the add method returns false, indicating that the element was not added, and the set remains unchanged.

Exam trap

The trap here is that candidates may confuse the return value of add() with the behavior of a List, expecting an exception or a successful insertion, but the Set interface mandates that duplicates are silently rejected by returning false.

How to eliminate wrong answers

Option A is wrong because TreeSet.add() does not throw an exception when adding a duplicate; it simply returns false. Option C is wrong because a Set, by definition, cannot contain duplicate elements, so the set will not have two "Bob" entries. Option D is wrong because the add method returns false, not true, when the element already exists in the set.

282
MCQhard

A large-scale data processing platform uses Java to read and write files across multiple nodes. Recently, operations have slowed down significantly. The system uses FileInputStream and FileOutputStream wrapped in BufferedInputStream and BufferedOutputStream with default buffer sizes (8 KB). The operations team suspects that the default buffer size is causing excessive system calls. The files are typically 100 MB to 1 GB in size. Which change would most improve I/O performance while minimizing memory overhead?

A.Increase the buffer size to 64 KB.
B.Switch to using FileChannel with direct ByteBuffers for all file operations.
C.Use memory-mapped files (MappedByteBuffer) for the entire file.
D.Replace FileInputStream with FileReader and FileOutputStream with FileWriter.
AnswerA

A larger buffer reduces system calls, improving throughput without significant memory increase.

Why this answer

Increasing the buffer size to 64 KB reduces the number of system calls (read/write) by allowing more data to be transferred per call. With default 8 KB buffers and 100 MB–1 GB files, the overhead of frequent kernel transitions is significant. A 64 KB buffer strikes a good balance between performance gain and memory overhead, as it is large enough to reduce syscalls substantially without consuming excessive heap space.

Exam trap

The trap here is that candidates often assume memory-mapped files or direct buffers are always faster, overlooking that the primary bottleneck in this scenario is excessive system calls due to small buffer size, and that a simple buffer size increase is the most direct and memory-efficient fix.

How to eliminate wrong answers

Option B is wrong because switching to FileChannel with direct ByteBuffers introduces additional complexity and memory management overhead (native memory allocation) that may not be justified; while it can improve performance, it does not directly address the root cause of excessive system calls due to small buffer size, and the memory overhead of direct buffers can be higher. Option C is wrong because memory-mapping the entire file (MappedByteBuffer) for files up to 1 GB would consume a large portion of the virtual address space and can cause performance degradation due to page faults and garbage collection pressure, especially when multiple files are accessed concurrently; it is not a minimal-memory-overhead solution. Option D is wrong because FileReader and FileWriter are character-stream wrappers that add encoding/decoding overhead and do not change the underlying buffering behavior; they still use the same default buffer size and do not reduce system call frequency.

283
MCQmedium

A Java application running in a secure environment needs to read a file located outside the application's directory. Which approach correctly handles security?

A.Use FileInputStream without any additional configuration
B.Grant java.io.FilePermission in the security policy file for the specific file path
C.Use java.net.URL to access the file via file:// protocol
D.Set the file readable flag using File.setReadable(true)
AnswerB

This grants the application permission to read the file under the security manager.

Why this answer

Option B is correct because in a secure Java environment, the SecurityManager enforces access controls based on the security policy file. To read a file outside the application's directory, you must explicitly grant `java.io.FilePermission` with the specific file path and the `read` action in the policy file. Without this permission, any attempt to read the file will throw a `java.security.AccessControlException`.

Exam trap

The trap here is that candidates often confuse OS-level file permissions (like `setReadable`) with Java's SecurityManager permissions, or assume that using a URL protocol bypasses security checks, when in fact the SecurityManager enforces the same policy regardless of the I/O API used.

How to eliminate wrong answers

Option A is wrong because using `FileInputStream` without additional configuration will trigger the SecurityManager, which by default denies access to files outside the application's directory, resulting in a security exception. Option C is wrong because using `java.net.URL` with the `file://` protocol still goes through the same file I/O security checks; the SecurityManager will block access unless the appropriate `FilePermission` is granted, and the URL approach does not bypass security policies. Option D is wrong because `File.setReadable(true)` only modifies the file's operating system permissions and does not affect the Java SecurityManager's access control; the SecurityManager will still enforce its own policy and deny access if no `FilePermission` is granted.

284
MCQmedium

A developer receives the above error when running a modular Java application. What is the most likely cause?

A.The module-info.java has a syntax error.
B.The module 'com.example.app' is not on the module path.
C.The JRE version is too old.
D.The main class is misspelled.
AnswerB

The error indicates the module was not found.

Why this answer

When a modular Java application throws an error indicating that a module cannot be found, the most common cause is that the module's JAR or directory is not present on the module path. The module path is specified using the `--module-path` option (or `-p`) when launching the application with `java --module`. If `com.example.app` is not on that path, the module system cannot resolve it, leading to a `ModuleNotFoundException` or similar error.

Exam trap

The trap here is that candidates confuse module path errors with classpath errors, assuming a missing class is the issue, when in fact the module system requires the entire module to be present on the module path.

How to eliminate wrong answers

Option A is wrong because a syntax error in module-info.java would produce a compilation error, not a runtime module resolution error. Option C is wrong because an outdated JRE version would typically cause `UnsupportedClassVersionError` or missing API errors, not a module-not-found error. Option D is wrong because a misspelled main class would result in a `ClassNotFoundException` or `NoClassDefFoundError`, not a module resolution failure.

285
MCQeasy

A developer needs to create a temporary file that will be automatically deleted when the JVM terminates. Which approach correctly achieves this?

A.File.createTempFile("pre", ".txt").deleteOnExit()
B.new File("tmp.txt").deleteOnExit()
C.Files.createTempDirectory("tmp").toFile().deleteOnExit()
D.Files.createTempFile("pre", ".txt")
AnswerA

Creates a temp file and registers it for automatic deletion on JVM exit.

Why this answer

Option A is correct because `File.createTempFile("pre", ".txt")` creates a temporary file in the default temporary-file directory, and chaining `.deleteOnExit()` registers that file for deletion when the JVM terminates. This combination ensures both the creation of a temporary file and its automatic cleanup upon JVM shutdown, fulfilling the requirement precisely.

Exam trap

The trap here is that candidates often confuse creating a temporary file with simply scheduling deletion of any file, or they forget that `Files.createTempFile()` alone does not register for automatic deletion, leading them to pick option D without the necessary `.deleteOnExit()` call.

How to eliminate wrong answers

Option B is wrong because `new File("tmp.txt")` creates a File object representing a file in the current working directory, not a temporary file in the system's temp directory, and `.deleteOnExit()` only schedules deletion of that arbitrary file; it does not create a temporary file. Option C is wrong because `Files.createTempDirectory("tmp")` creates a temporary directory, not a file, and while `.toFile().deleteOnExit()` schedules the directory for deletion, the requirement specifies a temporary file, not a directory. Option D is wrong because `Files.createTempFile("pre", ".txt")` creates a temporary file but does not call `.deleteOnExit()`, so the file will not be automatically deleted when the JVM terminates; it only creates the file without any cleanup registration.

286
MCQmedium

A development team wants to ensure that a Java 17 application runs with a specific set of modules. They want to minimize the footprint by including only necessary modules. Which tool should they use?

A.javac
B.jlink
C.jmod
D.jar
AnswerB

jlink assembles a custom runtime image with specified modules.

Why this answer

B is correct because jlink is the Java tool specifically designed to assemble and optimize a custom runtime image containing only the modules explicitly required by an application. It analyzes module dependencies and produces a minimal JRE, reducing footprint by excluding unused modules, which aligns with the team's goal of minimizing size.

Exam trap

The trap here is that candidates confuse jlink with jmod or jar, assuming any packaging tool can minimize the runtime, but only jlink performs the module-aware linking and optimization to produce a custom JRE.

How to eliminate wrong answers

Option A is wrong because javac is the Java compiler that translates source code into bytecode; it does not create custom runtime images or manage module inclusion for deployment. Option C is wrong because jmod is used to create and inspect JMOD files, which are packaging formats for modules, but it cannot produce a runtime image or minimize the JRE footprint. Option D is wrong because jar is used to package class files and resources into JAR archives; it does not analyze module dependencies or generate a minimal runtime environment.

287
MCQhard

A resource is declared in a try-with-resources statement. The try block throws an exception. The close method throws a different exception. What exception is thrown by the try-with-resources statement?

A.The exception from the close method.
B.The exception from the try block.
C.A compilation error occurs.
D.Both exceptions are thrown simultaneously.
AnswerB

The try block exception is the primary exception; the close exception is suppressed.

Why this answer

In a try-with-resources statement, if both the try block and the close() method throw exceptions, the exception from the try block is the one thrown by the statement. The exception from close() is suppressed and added to the thrown exception's suppressed exception list (via Throwable.addSuppressed()). This is specified by JLS §14.20.3.2 and ensures the primary failure (the try block exception) is not masked.

Exam trap

The trap here is that candidates often assume the last exception thrown (from close()) overrides the earlier one, or that both exceptions are thrown simultaneously, but Java's suppressed exception mechanism ensures the try block's exception is primary and close() exceptions are silently attached.

How to eliminate wrong answers

Option A is wrong because the exception from the close method is not the one thrown; it is suppressed and added to the suppressed exception list of the try block's exception. Option C is wrong because no compilation error occurs; the try-with-resources syntax is valid and handles multiple exceptions gracefully. Option D is wrong because both exceptions are not thrown simultaneously; Java does not support throwing multiple exceptions at once — one exception is thrown, and the other is suppressed.

288
MCQmedium

Refer to the exhibit. What is the result?

A.Compilation fails due to missing permits in Circle
B.Compilation fails at line 10
C.Runtime exception
D.Compilation succeeds
AnswerB
289
MCQeasy

A lambda that takes a String and returns its length is assigned to which functional interface?

A.UnaryOperator<String>
B.Consumer<String>
C.Predicate<String>
D.Supplier<Integer>
E.Function<String, Integer>
AnswerE

Correct. This functional interface accepts a String and returns an Integer.

Why this answer

Function<String, Integer> takes a String and returns an Integer. The lambda s -> s.length() matches this signature.

290
MCQmedium

A Java application uses a custom resource class implementing AutoCloseable. The close() method throws a checked exception. In a try-with-resources block, if both the try block and the close() method throw exceptions, which exception is propagated to the caller? Assume the resource is declared in try-with-resources.

A.The exception from the try block is the primary exception, and the close() exception is added as a suppressed exception.
B.The exception from close() is always the primary exception.
C.Both exceptions are thrown simultaneously as a multi-catch exception.
D.The exception from the try block is always suppressed.
AnswerA

Correct behavior per Java try-with-resources.

Why this answer

In a try-with-resources block, when both the try block and the close() method throw exceptions, the exception from the try block is the primary exception propagated to the caller. The exception thrown by close() is added to the primary exception's suppressed exception list, as defined by the Java Language Specification (JLS §14.20.3.2). This ensures that the most relevant exception (the one from the application logic) is not masked by a resource-closing failure.

Exam trap

The trap here is that candidates often assume the last exception thrown (from close()) overwrites the first, or that both exceptions are thrown together, when in fact the try block exception is primary and the close() exception is suppressed.

How to eliminate wrong answers

Option B is wrong because the exception from close() is never the primary exception when both the try block and close() throw; the try block exception always takes precedence. Option C is wrong because Java does not support simultaneous multi-catch exceptions; exceptions are sequential, and only one is propagated with others suppressed. Option D is wrong because the exception from the try block is the primary exception, not suppressed; it is the close() exception that is suppressed.

291
MCQeasy

What will be the result of the following code? Object[] arr = new Integer[5]; arr[0] = "String";

A.Successfully stores "String"
B.ArrayStoreException at runtime
C.Compilation error
D.ClassCastException
AnswerB

Runtime type is Integer[], incompatible.

Why this answer

The code creates an array of type `Integer[]` referenced by an `Object[]` variable. At runtime, the array's actual component type is `Integer`, so attempting to store a `String` violates the array's type constraint and throws an `ArrayStoreException`.

Exam trap

The trap here is that candidates see the reference type `Object[]` and assume the array can hold any `Object`, forgetting that the actual runtime type of the array object determines what can be stored, leading them to pick Option A or D.

How to eliminate wrong answers

Option A is wrong because storing a `String` into an `Integer[]` array is not allowed; the JVM performs a runtime type check on the stored element. Option C is wrong because the code compiles successfully: the reference type `Object[]` allows the assignment, and the assignment `arr[0] = "String"` is syntactically valid since `String` is an `Object`. Option D is wrong because `ClassCastException` occurs when an object is cast to an incompatible type, not when an element is stored into an array; the array store check throws `ArrayStoreException` instead.

292
MCQhard

Refer to the exhibit. What is the result?

A.Compilation fails
B.Bark Playing
C.Runtime exception
D.Bark
AnswerB
293
MCQhard

A Java 17 application is deployed on a server. The application uses modules but one required module is missing from the module path. Which exception will be thrown at startup?

A.ExceptionInInitializerError
B.NoClassDefFoundError
C.ClassNotFoundException
D.ModuleNotFoundException
AnswerD

Thrown when a required module cannot be resolved.

Why this answer

Option D is correct because when a required module is missing from the module path in Java 17, the module system throws `ModuleNotFoundException` during the resolution phase at startup. This exception is specific to the Java Platform Module System (JPMS) and indicates that a module declared in `requires` clauses cannot be located.

Exam trap

The trap here is that candidates confuse module-level errors with class-level errors, mistakenly choosing `NoClassDefFoundError` or `ClassNotFoundException` because they think of missing JARs on the classpath, but the exam specifically tests the JPMS behavior where `ModuleNotFoundException` is the correct exception for a missing module on the module path.

How to eliminate wrong answers

Option A is wrong because `ExceptionInInitializerError` is thrown when an unexpected exception occurs in a static initializer, not when a module is missing from the module path. Option B is wrong because `NoClassDefFoundError` occurs when a class was present at compile time but is missing at runtime, typically due to classpath issues, not module resolution failures. Option C is wrong because `ClassNotFoundException` is thrown when an application tries to load a class via its string name using `Class.forName()`, `ClassLoader.loadClass()`, or similar reflective methods, not when the module system fails to find a module.

294
MCQmedium

A developer writes: List<Integer> list = List.of(1, 2, 3); Optional<Integer> opt = list.stream().reduce((a, b) -> a + b); System.out.println(opt.get()); What is the result?

A.6
B.Optional[6]
C.Optional.empty
D.NoSuchElementException
AnswerA

Correct output.

Why this answer

The `reduce` method with a single argument (a `BinaryOperator`) returns an `Optional` because the stream might be empty. Here, the stream contains three integers, so the reduction computes `1 + 2 = 3`, then `3 + 3 = 6`, yielding `Optional[6]`. Calling `get()` on a non-empty `Optional` returns the contained value `6`, which is printed.

Exam trap

The trap here is that candidates may forget that `reduce` with one argument returns an `Optional` and incorrectly assume the output is `Optional[6]` or that `get()` throws an exception, overlooking that the stream is non-empty.

How to eliminate wrong answers

Option B is wrong because `opt.get()` extracts the value from the `Optional`, so the output is `6`, not `Optional[6]`. Option C is wrong because the stream is not empty; it has three elements, so the `Optional` is not empty. Option D is wrong because `NoSuchElementException` would only be thrown if `get()` were called on an empty `Optional`, which does not occur here.

295
MCQmedium

A developer is writing a utility to copy a large binary file (e.g., 500 MB) from one location to another while minimizing memory overhead and ensuring data integrity. Which approach is most appropriate?

A.Use BufferedReader and BufferedWriter for binary data.
B.Use a custom loop reading into a byte array of 8KB and writing to the output stream.
C.Use Files.copy() with StandardCopyOption.REPLACE_EXISTING.
D.Use FileInputStream.readAllBytes() and FileOutputStream.write().
AnswerB

Processes data in small chunks, keeping memory usage low.

Why this answer

Option B is correct because reading and writing in fixed-size chunks (e.g., 8KB) minimizes memory overhead by avoiding loading the entire 500 MB file into memory, while still providing efficient I/O through buffered operations. This approach ensures data integrity by processing the file sequentially without relying on character-based streams, which are unsuitable for binary data.

Exam trap

The trap here is that candidates often choose Files.copy() (Option C) because it is convenient and commonly used, but the question explicitly requires minimizing memory overhead, and Files.copy() does not expose buffer size control, making the custom loop (Option B) the more precise answer for this specific constraint.

How to eliminate wrong answers

Option A is wrong because BufferedReader and BufferedWriter are character-based streams that decode bytes into characters using a charset, which can corrupt binary data and add unnecessary overhead. Option C is wrong because Files.copy() internally uses a buffer and is a valid approach, but it does not allow the developer to control buffer size or handle partial writes explicitly, making it less appropriate when minimizing memory overhead is a primary concern. Option D is wrong because FileInputStream.readAllBytes() loads the entire 500 MB file into memory as a byte array, defeating the goal of minimizing memory overhead.

296
Multi-Selecteasy

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

Select 2 answers
A.The resources must implement the Closeable interface.
B.Resources can be reassigned inside the try block.
C.Resources declared in the try-with-resources block are closed automatically.
D.Resources are closed in the reverse order of their declaration.
E.Multiple resources are separated by commas.
AnswersC, D

Correct: The try-with-resources statement ensures each resource is closed at the end of the statement.

Why this answer

Option C is correct because the try-with-resources statement automatically closes each resource declared in the resource specification after the try block completes, whether normally or abruptly. This is the primary purpose of the construct: to ensure reliable resource cleanup without requiring an explicit finally block.

Exam trap

The trap here is that candidates often confuse the required interface (AutoCloseable vs. Closeable) and the separator between multiple resources (semicolons vs. commas), leading them to select the plausible-sounding but incorrect options A and E.

297
MCQhard

Refer to the exhibit. Which statement about this Singleton implementation is correct?

A.The volatile keyword is unnecessary.
B.It may still have a race condition due to instruction reordering.
C.It is thread-safe without any issues.
D.It will compile only if the constructor is public.
AnswerB
298
MCQmedium

A company uses a large dataset of customer orders. They want to compute statistics: total orders, average amount, and maximum amount per city. They write: Map<String, IntSummaryStatistics> stats = orders.stream() .collect(Collectors.groupingBy(Order::getCity, Collectors.summarizingInt(Order::getAmount))); The code works but is slower than expected when run on a large dataset. They suspect the grouping operation is not taking advantage of parallelism. They want to improve performance by making the collector concurrent. Which change is correct?

A.Use Collectors.groupingByConcurrent(Order::getCity, Collectors.summarizingInt(Order::getAmount)).
B.Use parallelStream() instead of stream().
C.Keep the code but supply a ConcurrentHashMap as the map supplier to groupingBy.
D.Replace collect with forEach and manually update a ConcurrentHashMap.
AnswerA

groupingByConcurrent returns a concurrent Collector that uses a ConcurrentHashMap, optimized for parallel streams.

Why this answer

Option D is correct because groupingByConcurrent returns a ConcurrentMap (e.g., ConcurrentHashMap) and is designed for parallel stream processing, allowing concurrent insertion. Option A is wrong because parallelStream() alone does not make the collector concurrent; the collector must also support it. Option B is wrong because forEach is not recommended for this aggregation.

Option C is wrong because changing the map supplier to ConcurrentHashMap without using groupingByConcurrent may still cause thread-safety issues.

Page 3

Page 4 of 7

Page 5

All pages