Courseiva

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

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

Page 3

Page 4 of 7

Page 5
226
MCQeasy

What is the output of the following code? List<Integer> list = List.of(0, 1, 2, 3); System.out.println(list.indexOf(0) + " " + list.lastIndexOf(3));

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

Correct: indexOf(0) returns 0 and lastIndexOf(3) returns 3.

Why this answer

The list is [0, 1, 2, 3]. The indexOf(0) returns 0 because 0 is at index 0. The lastIndexOf(3) returns 3 because 3 is at index 3.

The output is "0 3".

Exam trap

Candidates might mistakenly think that lastIndexOf(3) returns 2 due to off-by-one error, or confuse with other list methods like get().

How to eliminate wrong answers

Option A is wrong because it assumes the removal succeeds and prints the remaining elements after removing evens, but the code throws an exception before any removal occurs. Option C is wrong because it incorrectly suggests the output is `1 2`, which would only happen if the removal succeeded and the list was modifiable, but the exception prevents that. Option D is wrong because it implies the output is `1 3`, which would be the result of a successful removal of evens from a modifiable list, but the immutable list causes an exception instead.

227
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

228
Multi-Selecthard

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

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

Generates an infinite IntStream of zeros.

Why this answer

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

Exam trap

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

229
MCQhard

Given the module descriptor for com.example.payment: module com.example.payment { exports com.example.payment; // does not require com.example.store } And the Main class is in the unnamed module (on the classpath). The invocation is: java --add-modules com.example.store --module-path mods -cp classes com.example.Main 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

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.

230
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

Ly filters by status 'PENDING', sorts by date using a Comparator, maps to order IDs, and collects into a Set, matching the original logic.

Why this answer

It first filters orders with status 'PENDING', then sorts them by date using a Comparator, then maps each Order to its ID, and finally collects the IDs into a Set. This preserves the original logic: filter before sorting (to reduce the number of elements to sort), and map after sorting (since sorting requires Order objects, not IDs). Collecting into a Set automatically deduplicates IDs, matching the original intent.

Exam trap

The exam often tests the order of stream operations, specifically that sorting must occur before mapping when the sort key is a property of the original object, and that filtering early improves efficiency.

How to eliminate wrong answers

Option A is wrong because it collects Order objects into a Set without mapping to IDs, so it returns a Set<Order> instead of a Set<ID>. Option B is wrong because it sorts the IDs (after mapping) rather than sorting the Order objects by date, which changes the sorting semantics. Option C is wrong because it sorts before filtering, which is less efficient and could produce different results if the sorting comparator depends on filtered-out elements (though not an issue here, it violates the intended order of operations).

231
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

The correct matches are based on the direction (read vs write) and type (byte vs character) of the stream. FileInputStream reads bytes; FileOutputStream writes bytes. BufferedReader reads characters with buffering; BufferedWriter writes characters with buffering.

232
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

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.

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

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.

234
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

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.

235
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, so initially the body executes with x=0, then x increments to 1. The loop continues as long as x < 5.

The body executes for x = 0, 1, 2, 3, 4 — a total of 5 times. When x becomes 5, the condition x < 5 is false, so the loop stops.

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.

236
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

In a JAAS login module, after the `login()` method returns `true`, the `commit()` method must be called to associate the authenticated principals and credentials with the `Subject`. The `commit()` method is responsible for adding the successfully authenticated principals to the Subject, making them available for subsequent authorization checks. This is part of the two-phase authentication protocol defined by the `javax.security.auth.spi.LoginModule` interface.

Exam trap

The trap here is that candidates often confuse the purpose of `login()` and `commit()`, mistakenly thinking that `login()` both authenticates and adds principals, when in fact `login()` only performs verification and `commit()` is required to populate the Subject.

How to eliminate wrong answers

Option A is wrong because `login()` is the first phase of authentication that performs the actual authentication logic (e.g., verifying credentials) and returns a boolean; it does not add principals to the Subject. Option B is wrong because `initialize()` is called once before any login attempts to set up the LoginModule with the Subject, callback handler, shared state, and options; it does not commit authentication results. Option D is wrong because `abort()` is called if the overall authentication fails (e.g., after `login()` returns false or another module fails) to clean up any state; it does not add principals.

237
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.(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
AnswersA, C

Valid: explicit types are allowed in lambda parameter lists.

Why this answer

Options A and C are valid lambda expressions. Option A uses explicit parameter types, which is allowed in lambda expressions. Option C uses inferred types with parentheses, also valid.

Option B is invalid because multiple lambda parameters require parentheses. Option D is invalid because the block body does not contain a return statement, and the expression statement a + b; is not a valid return statement. Option E is invalid because it mixes explicit and inferred parameter types; if one parameter has an explicit type, all must have explicit types.

Exam trap

A common trap is assuming that parentheses can be omitted for multiple parameters. In Java, lambda expressions with multiple parameters always require parentheses around the parameter list.

238
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

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.

239
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

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.

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

241
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);
AnswerA

Correct. getCurrencyInstance(Locale.US) provides two decimal places by default, and setRoundingMode(HALF_UP) ensures half-up rounding.

Why this answer

It uses NumberFormat.getCurrencyInstance(Locale.US) which defaults to exactly two decimal places for the US locale, and explicitly sets the rounding mode to RoundingMode.HALF_UP, satisfying both requirements. Options B and C adjust fraction digits but do not set the rounding mode, so they default to HALF_EVEN. Option D also defaults to HALF_EVEN, not HALF_UP.

Therefore, only option A meets the conditions of exactly two decimal places and rounding half-up.

Exam trap

The trap is that candidates may think getCurrencyInstance already sets HALF_UP, but it defaults to HALF_EVEN. Option D appears simplest but fails the rounding requirement. Option A explicitly sets the rounding mode, making it the correct choice.

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.

242
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(stream1, stream2)` is the idiomatic, built-in static method in the Java Stream API for concatenating two streams into a single sequential stream. It creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream, preserving encounter order.

Exam trap

The trap here is that candidates may confuse `flatMap` with concatenation or assume a non-existent `merge` method exists, because they recall similar operations from other APIs like `Map.merge()` or reactive streams, but the Java Stream API specifically provides `concat()` for this purpose.

How to eliminate wrong answers

Option A is wrong because `stream1.flatMap(s -> stream2)` does not concatenate the streams; it attempts to replace each element of stream1 with the entire stream2, which would produce a stream of streams (or cause a compilation error if stream2 is not a stream of the same type). Option B is wrong because `StreamBuilder` is not a standard Java class; the correct builder is `Stream.builder()`, and even then it does not accept streams as arguments—only individual elements. Option D is wrong because `merge` is not a method defined in the `Stream` interface; it is a method in other contexts like `Map.merge()` or reactive libraries, but not in the standard Java Stream API.

243
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

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.

244
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

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.

245
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

`DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)` is a valid static factory method that returns a formatter using the default locale's full date style. Option C is correct because `DateTimeFormatter.ofPattern("dd/MM/yyyy")` is the standard way to create a custom pattern-based formatter.

Exam trap

Oracle often tests the confusion between static factory methods and instance methods, and the correct argument order for overloaded methods like `ofPattern()` and `ofLocalizedTime()`, leading candidates to incorrectly mix up parameter positions or call instance methods on static constants.

246
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

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.

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

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

249
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

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.

250
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

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

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

252
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

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.

253
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

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

254
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

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.

255
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

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.

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

257
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

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.

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

259
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

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.

260
MCQhard

What is the output of the following code? ```java System.out.println(Stream.of(1, 2).map(i -> i * 2.0).count()); ```

A.2.0
B.1
C.2
D.Compilation error
AnswerC

6/3 = 2, printed as 2.

Why this answer

The code is:

```java

System.out.println(Stream.of(1, 2).map(i -> i * 2.0).count());

```

This creates a stream of integers 1 and 2, maps each to a Double (2.0 and 4.0), and then calls count() which returns the number of elements in the stream, which is 2. count() returns a long, but when printed, it outputs 2 (not 2.0). Option C is correct because the stream has two elements.

Exam trap

The trap here is that candidates may mistakenly think the `map` operation changes the return type of `count()` or that the output would be a floating-point number (2.0) because the mapping produces `Double` values, but `count()` always returns a `long` regardless of the stream's element type.

How to eliminate wrong answers

Option A is wrong because it suggests the output is 2.0, but `count()` returns a `long` (not a `Double`), and the result is printed as an integer 2, not a floating-point number. Option B is wrong because it suggests the output is 1, but the stream contains two elements (1 and 2), so the count is 2, not 1. Option D is wrong because there is no compilation error: the `map` operation returns a `Stream<Double>`, and `count()` is a valid terminal operation on any stream, returning a `long` that can be assigned to `int` without explicit cast due to implicit narrowing conversion (though a cast would be required for `long` to `int` in general, here the literal value 2 fits within `int` range, so no error).

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

Why this order

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

262
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

Correct. The `non-sealed` modifier allows further subclassing, which is a valid implementation of a permitted subclass of a sealed class.

Why this answer

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

263
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

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.

264
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

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.

265
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

Why this answer

The code uses a Deque (ArrayDeque) and calls push() to add elements, which adds them to the front of the deque (LIFO order). The for-each loop iterates from the head (first) to the tail (last), so it prints 30, 20, 10. Option B is correct because push() behaves like a stack, and iteration follows the deque's head-to-tail order.

Exam trap

The trap here is that candidates confuse push() with add() (which adds to the tail) and assume the iteration order matches insertion order, rather than recognizing that push() places elements at the front for LIFO access.

How to eliminate wrong answers

Option A is wrong because it assumes the elements are printed in the order they were added (FIFO), but push() adds to the front, not the end. Option C is wrong because it suggests a mixed order that does not correspond to either LIFO or FIFO behavior; it might arise from misunderstanding that push() adds to the tail. Option D is wrong because it reverses the iteration order, as if the for-each loop traversed from tail to head, which it does not.

266
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

Parallel stream performance depends on the stream source being efficiently splittable (like an ArrayList, which has O(1) random access and can be split evenly) and the operation being stateless and associative to avoid synchronization overhead and ensure correct results. A poorly splittable source (e.g., LinkedList) or stateful operations can cause contention and reduce parallelism gains.

Exam trap

The trap here is that candidates often assume more threads (Option C) or switching to sequential (Option A) will fix performance, overlooking that the root cause is usually an inefficiently splittable source or non-associative/stateful operations, which are the key factors the exam tests for parallel stream optimization.

How to eliminate wrong answers

Option A is wrong because switching to a sequential stream would eliminate parallelism entirely, likely making the operation slower for a large dataset, not faster. Option B is wrong because using a custom Collector instead of reduce does not inherently improve parallel performance; both can be parallelized if designed correctly, and the issue is more about the stream source and operation properties. Option C is wrong because increasing the parallelism level beyond the number of available CPU cores (e.g., setting to 100) can lead to thread contention, overhead from context switching, and diminishing returns, often degrading performance rather than improving it.

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

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

269
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

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

270
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

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

271
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

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.

272
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

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.

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

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

275
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'.
AnswerB

Correct. If the 'com.example.service' module does not have an 'exports com.example.service.api' directive, the package is not accessible to any other module, including 'com.example.client'.

Why this answer

The stem states that the 'com.example.service' module exports 'com.example.service.api', but the most likely reason the client cannot access the package is that the package is not actually exported in the module's module-info.java. In JPMS, a module must explicitly export a package for it to be accessible to other modules. Without an exports directive, other modules cannot access the package even if they have a 'requires' directive.

Option C is incorrect because the stem explicitly states that the client requires the service module. Options A and D are not directly related to the client's inability to access the package.

Exam trap

The trap is that candidates may trust the stem's assertion that the package is exported, but the most likely reason for the access failure is that the export declaration is missing. Always verify that exports are present in the module declaration.

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.

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

277
MCQmedium

Given the exhibit, which statement about calling this method is true?

A.It must be called using the `new` keyword.
B.It can only be called from a static context, not from an instance.
C.It can be called as `ClassName.getEmpName(101)`.
D.It cannot be used because it contains a loop.
AnswerC

Correct. Static methods are called on the class, e.g., `ClassName.methodName()`.

Why this answer

A static method can be called directly on the class without creating an instance. The method `getEmpName` is static and returns a value, so it can be invoked as `ClassName.getEmpName(101)`. Instance methods require an object reference, and non-static methods cannot be called in a static context without an instance.

Exam trap

Java often tests the misconception that any method that performs I/O or database operations cannot be called directly, but the restriction is about modifying state (side effects) in contexts like lambdas, not about reading data. Here, the key is that the method is static, not that it contains a SELECT statement.

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.

278
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

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.

279
MCQhard

Refer to the exhibit. What is the output?

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

Why this answer

The code uses `equals()` on two `String` objects with the same content ("Test"), which returns `true`. The second `println` uses `==` to compare the same two `String` references; since both reference the same string literal from the string pool, `==` also returns `true`. Thus both lines print `true`.

Exam trap

Oracle certification questions often test the distinction between `equals()` (content comparison) and `==` (reference comparison) with string literals, trapping candidates who assume `==` always returns `false` for distinct variables without considering string interning.

How to eliminate wrong answers

Option A is wrong because the code compiles without error — both `equals()` and `==` are valid operators for `String` objects. Option C is wrong because `==` on two identical string literals returns `true`, not `false`, due to string interning. Option D is wrong because `equals()` on two strings with identical content returns `true`, not `false`.

280
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

The jlink command creates a custom runtime image that includes the specified module (com.example.app) and all of its resolved dependencies. It does not compile the module; compilation is done separately with javac. The resulting image is a directory structure with the JRE and module files, not a JAR.

Exam trap

The trap here is that candidates often think jlink compiles source code or produces a JAR, but jlink only links pre-compiled modules into a runtime image, and it always includes dependencies, not just the specified module.

How to eliminate wrong answers

Option A is wrong because jlink does not compile modules; compilation is performed by javac before jlink is invoked. Option C is wrong because jlink includes not only the specified module but also all its transitive dependencies required at runtime. Option D is wrong because jlink produces a runtime image (a directory with bin, lib, etc.), not a JAR file.

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

282
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

The --limit-modules option restricts jlink to only the specified root modules and their transitive dependencies, pruning unnecessary modules from the analysis and image. This directly reduces the number of modules jlink must process, cutting build time, and eliminates unused module classes from the runtime image, shrinking its size. In contrast, options like --strip-java-debug-attributes or --compress=2 only reduce image size after all modules are included, without addressing the root cause of excessive module scanning.

Exam trap

The trap here is that candidates often focus on image size reduction techniques like compression or stripping debug info, overlooking that the primary bottleneck is jlink's module graph resolution time, which --limit-modules directly addresses by constraining the module universe.

How to eliminate wrong answers

Option B is wrong because jpackage creates a platform-specific installer (e.g., .msi, .dmg) but does not reduce jlink build time or image size; it packages the already-built runtime image. Option C is wrong because --strip-java-debug-attributes removes debug information from class files, which reduces image size slightly but does not shorten jlink's module resolution and linking phase. Option D is wrong because --compress=2 applies ZIP compression to the image's resources, reducing disk size but not build time, and the compression overhead can even increase processing time.

283
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

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.

284
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

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.

285
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

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.

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

287
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

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.

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

289
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

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

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

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

292
MCQmedium

Refer to the exhibit. Given the following code: ```java 1: sealed interface Shape permits Circle { } ... 10: class Circle implements Shape { } ``` 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

Why this answer

In Java 17, when a sealed interface (like `Shape`) declares a `permits` clause listing permitted subclasses (e.g., `Circle`), each permitted subclass must explicitly declare itself as `sealed`, `non-sealed`, or `final`. If the `Circle` class is defined as `class Circle implements Shape` without any of these modifiers, compilation fails at line 10 where that class is defined. The error is that the class is not allowed to extend/implement the sealed interface unless it has the required modifier.

Exam trap

Candidates often overlook the mandatory modifier (`sealed`, `non-sealed`, or `final`) on each permitted subclass of a sealed type. Even if the class is logically final (e.g., all methods are final or the class is implicitly final), the Java compiler requires an explicit keyword.

How to eliminate wrong answers

Option A is wrong because a permitted subclass does not need to have its own `permits` clause — only a sealed class/interface needs `permits`. Option C is wrong because the code never compiles, so no runtime exception occurs. Option D is wrong because the code fails to compile due to the missing required modifier on the permitted subclass.

293
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

The lambda `(String s) -> s.length()` takes a `String` input and returns an `Integer` (the length). This matches the `Function<T, R>` functional interface, which defines the abstract method `R apply(T t)`. Option E is correct because `Function<String, Integer>` exactly represents a function that accepts a `String` and produces an `Integer`.

Exam trap

The trap here is that candidates often confuse `UnaryOperator` (which requires same input/output type) with `Function` (which allows different types), leading them to pick A instead of E.

How to eliminate wrong answers

Option A is wrong because `UnaryOperator<String>` extends `Function<String, String>`, meaning it must return the same type as its input (String), not an Integer. Option B is wrong because `Consumer<String>` accepts a String but returns void (via `void accept(T t)`), so it cannot return a length. Option C is wrong because `Predicate<String>` returns a `boolean` (via `boolean test(T t)`), not an Integer.

Option D is wrong because `Supplier<Integer>` takes no input and returns an Integer (via `T get()`), but the lambda requires a String parameter.

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

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

296
MCQhard

Refer to the exhibit. What is the result?

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

Why this answer

The code compiles and runs without error. The object referenced by a1 is a Dog instance. The code first calls the bark() method, which prints 'Bark' (defined in Dog).

Then it calls the play() method, which is not overridden in Dog, so it invokes the inherited play() method from Animal, printing 'Playing'. Therefore, the output is 'Bark' followed by 'Playing', which matches option B.

Exam trap

The trap here is that candidates may think the `play()` method must be overridden in `Dog` to be called, or that the output would be only 'Bark' because they overlook the inherited method call, leading them to choose option D.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; there is no syntax error or missing method issue. Option C is wrong because no runtime exception occurs; the `bark()` method is available on the `Dog` object, and the cast is not needed since the reference type is already `Dog`. Option D is wrong because it omits the 'Playing' output; the `play()` method is inherited and called before `bark()`, so both lines are printed.

297
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

ModuleNotFoundException is not a standard Java exception; the correct exception is java.lang.module.FindException.

Why this answer

None of the listed exceptions are correct. When a required module is missing from the module path during startup in Java 17, the module system throws `java.lang.module.FindException`, not `ModuleNotFoundException`. `ExceptionInInitializerError` occurs during static initialization, `NoClassDefFoundError` when a class is missing at runtime, and `ClassNotFoundException` at class loading. `ModuleNotFoundException` is not a standard Java exception.

Exam trap

Candidates may confuse module-level errors with class-level errors, but the actual exception for a missing module is FindException, not any of the listed options.

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.

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

299
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

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.

Page 3

Page 4 of 7

Page 5

All pages