Courseiva

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

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

Page 4

Page 5 of 7

Page 6
301
Multi-Selecteasy

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

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

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

Why this answer

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

Exam trap

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

302
MCQhard

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

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

Why this answer

The provided Singleton implementation uses double-checked locking without declaring the instance variable as volatile. Without volatile, the JVM may reorder instructions such that a thread reads a non-null reference to a partially constructed object, leading to a race condition. This is a classic pitfall in Java concurrency.

Exam trap

Oracle often tests the misconception that volatile is unnecessary in double-checked locking. Without volatile, instruction reordering can expose a partially constructed object, even with synchronized blocks.

How to eliminate wrong answers

Option A is wrong because the `volatile` keyword is necessary to ensure visibility of the instance across threads and to prevent the instruction reordering that can occur in double-checked locking. Option C is wrong because the implementation is not fully thread-safe due to the potential for instruction reordering, which can expose a partially constructed object to other threads. Option D is wrong because the constructor must be private to enforce the singleton pattern; a public constructor would allow multiple instances to be created, breaking the singleton guarantee.

303
MCQmedium

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

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

Correct. `Collectors.groupingByConcurrent` performs a concurrent reduction, using a `ConcurrentHashMap` internally, which allows efficient parallel processing with `parallelStream()`, reducing contention.

Why this answer

`Collectors.groupingByConcurrent` performs an unordered, concurrent reduction that can leverage a `ConcurrentHashMap` internally, allowing the collector to work efficiently with a parallel stream. This reduces contention and improves performance on large datasets compared to the sequential `groupingBy`.

Exam trap

The trap here is that candidates think `parallelStream()` alone is sufficient for concurrent grouping, but they overlook that the collector itself must be designed for concurrent accumulation to avoid contention and ensure thread safety.

How to eliminate wrong answers

Option B is wrong because simply calling `parallelStream()` without changing the collector does not make the grouping operation concurrent; `groupingBy` still uses a sequential `Map` and can cause thread contention. Option C is wrong because supplying a `ConcurrentHashMap` as the map supplier to `groupingBy` does not make the collector itself concurrent; the downstream collector `summarizingInt` is still applied sequentially, and the overall reduction is not thread-safe. Option D is wrong because manually updating a `ConcurrentHashMap` inside a `forEach` with a parallel stream can lead to race conditions on the `IntSummaryStatistics` objects, which are not thread-safe, and it bypasses the optimized concurrent reduction logic.

304
MCQhard

A developer wrote a method that uses a for-each loop to iterate over a list of strings and remove elements that match a certain condition. However, the method throws a ConcurrentModificationException at runtime. What is the most likely cause?

A.The loop uses a for-each loop with an array instead of a list.
B.The loop uses an iterator that is not properly initialized.
C.The list is unmodifiable.
D.The loop modifies the list by calling remove() on the list itself.
AnswerD

Modifying the list directly while iterating with a for-each loop causes ConcurrentModificationException because the iterator is not updated.

Why this answer

A for-each loop internally uses an Iterator to traverse the list. If the list is structurally modified (e.g., by calling remove() directly on the list) during iteration, the iterator's expected modCount will differ from the actual modCount, triggering a ConcurrentModificationException. This is a fail-fast behavior of the ArrayList and other Collection implementations.

Exam trap

The trap here is that candidates often confuse the ConcurrentModificationException with other exceptions (like UnsupportedOperationException) or mistakenly think the for-each loop itself is the problem, rather than recognizing that direct list modification during iteration is the root cause.

How to eliminate wrong answers

Option A is wrong because iterating over an array with a for-each loop does not involve an Iterator and thus cannot throw a ConcurrentModificationException; arrays are fixed-size and do not support structural modification. Option B is wrong because the for-each loop automatically obtains and initializes the iterator; the exception is not caused by improper initialization but by concurrent modification. Option C is wrong because an unmodifiable list would throw an UnsupportedOperationException if remove() is called, not a ConcurrentModificationException.

305
MCQhard

A team uses 'jlink' to create a custom runtime image for a modular application. They run the following command: 'jlink --module-path $JAVA_HOME/jmods:myapp --add-modules com.example.myapp --output myimage'. The application requires several non-Java native libraries (e.g., .so files) that are loaded via System.loadLibrary(). After creating the image, the application fails with an UnsatisfiedLinkError. What is the most likely cause?

A.The native library loading requires a module that exports the package containing the native method.
B.The --add-modules flag omitted transitive dependencies of com.example.myapp.
C.The native libraries were not included in the image; they must be manually copied or added using --add-modules and a custom module.
D.The --module-path must also include the directories containing the native libraries.
AnswerC

jlink images only contain Java modules; native code must be placed in the appropriate directory (e.g., lib) or bundled via a module.

Why this answer

The `jlink` tool creates a runtime image that includes only Java modules and their dependencies, not native libraries (e.g., .so files). Native libraries must be manually placed into the image's library path (e.g., `lib/` or `bin/` directory) or packaged into a custom module that is added via `--add-modules`. The `UnsatisfiedLinkError` occurs because `System.loadLibrary()` cannot find the native library in the image's expected locations.

Exam trap

The trap here is that candidates assume `jlink` automatically includes all dependencies, including native libraries, but `jlink` only handles Java modules and ignores non-Java artifacts like native `.so` or `.dll` files.

How to eliminate wrong answers

Option A is wrong because the `UnsatisfiedLinkError` is about the native library file not being found, not about module exports; exporting a package is irrelevant to native library loading. Option B is wrong because `--add-modules` with `com.example.myapp` automatically includes its transitive dependencies via the module descriptor; missing transitive dependencies would cause `ClassNotFoundException` or `NoClassDefFoundError`, not `UnsatisfiedLinkError`. Option D is wrong because `--module-path` is for Java module JARs and JMOD files, not native library directories; native libraries are not resolved via the module path.

306
MCQeasy

Which interface should be implemented to create a custom filter for deserialization in Java?

A.ObjectInputFilter
B.Serializable
C.ObjectOutput
D.FilterOutputStream
AnswerA

Defines the filter to accept or reject classes during deserialization.

Why this answer

The `ObjectInputFilter` interface (introduced in Java 9) allows you to define a custom filter that validates classes and data being deserialized from an `ObjectInputStream`. By implementing this interface, you can reject potentially malicious or unexpected classes during deserialization, which is a key security measure against deserialization attacks.

Exam trap

The trap here is that candidates confuse `ObjectInputFilter` with `Serializable` or stream-level filters like `FilterOutputStream`, missing that the question specifically asks for a filter on the deserialization process itself.

How to eliminate wrong answers

Option B is wrong because `Serializable` is a marker interface that enables an object to be serialized/deserialized, not to filter deserialization. Option C is wrong because `ObjectOutput` is an interface for writing objects to a stream (serialization), not for filtering deserialization. Option D is wrong because `FilterOutputStream` is a class that wraps an output stream to filter byte-level output, not for filtering object deserialization.

307
MCQeasy

A method returns an Optional<String>. The developer wants to transform the value inside the Optional to uppercase and print it, but only if present. Which best-practice approach uses streams?

A.opt.map(String::toUpperCase).ifPresent(System.out::println);
B.opt.ifPresent(s -> System.out.println(s.toUpperCase()));
C.opt.stream().map(String::toUpperCase).forEach(System.out::println);
D.Stream.of(opt).map(o -> o.get().toUpperCase()).forEach(System.out::println);
AnswerC

This converts Optional to a stream of one or zero elements, applies transformation, and prints. It is a stream-based best practice.

Why this answer

It converts the Optional to a Stream using opt.stream(), then applies map(String::toUpperCase) to transform the value, and finally uses forEach(System.out::println) to print it only if present. This approach leverages the Stream API's lazy evaluation and functional pipeline, which is the best practice for integrating Optional with streams.

Exam trap

The trap here is that candidates may overlook the 'uses streams' constraint and pick A or B, which are valid Optional operations but not stream-based, or pick D which misuses Stream.of to wrap the Optional instead of converting it.

How to eliminate wrong answers

Option A is wrong because opt.map(String::toUpperCase).ifPresent(System.out::println) uses Optional's map and ifPresent, not streams; the question explicitly asks for a 'streams' approach. Option B is wrong because opt.ifPresent(s -> System.out.println(s.toUpperCase())) is a direct Optional consumer, not a stream-based solution. Option D is wrong because Stream.of(opt) creates a stream of Optional, not the contained value, and calling o.get() is unsafe (throws NoSuchElementException if empty) and violates the 'only if present' requirement.

308
MCQhard

Given a list of integers, a developer wants to compute the sum of squares of numbers greater than 10. The following code is written: int sum = list.stream().filter(i -> i>10).mapToInt(i->i*i).sum(); But the sum is incorrect. What is the most likely reason?

A.The mapToInt operation is not allowed after filter.
B.The stream is not sorted.
C.The list might contain nulls causing NullPointerException.
D.The filter should be before mapToInt, but it is after.
E.The sum() method returns an OptionalInt and must be orElse(0).
AnswerC

If any element is null, unboxing in i > 10 throws NPE, making the result incorrect if caught or halting execution.

Why this answer

If the list contains null elements, the lambda expression `i -> i > 10` will attempt to unbox a null `Integer` to an `int`, causing a `NullPointerException` at runtime. The stream pipeline itself is syntactically valid, but the presence of nulls in the source list is a common pitfall when using primitive-specialized operations like `mapToInt` after a filter that does not guard against nulls.

Exam trap

Oracle often tests the misconception that `sum()` returns an `OptionalInt` (like `reduce` does) or that the order of `filter` and `mapToInt` is reversed, but the real trap is the silent NullPointerException from unboxing nulls in a lambda.

How to eliminate wrong answers

Option A is wrong because `mapToInt` is perfectly allowed after `filter`; the filter returns a `Stream<Integer>`, and `mapToInt` can be called on any `Stream` of objects to produce an `IntStream`. Option B is wrong because sorting is irrelevant to computing the sum of squares; the stream does not need to be sorted for any of the operations used. Option D is wrong because the order of `filter` before `mapToInt` is correct; filtering first reduces the number of elements to square, which is efficient and logically sound.

Option E is wrong because `sum()` on an `IntStream` returns a primitive `int`, not an `OptionalInt`; `OptionalInt` is returned only by reduction operations like `reduce()` or terminal operations like `findFirst()` on an `IntStream`.

309
MCQmedium

What does the Map.merge() method do if the specified key is absent?

A.Calls the remapping function with null and the value
B.Associates the key with the given value
C.Throws NullPointerException
D.Removes the key if present
AnswerB

If absent, put value.

Why this answer

When the specified key is absent in the map, the `Map.merge()` method associates the key with the given value without invoking the remapping function. This is specified in the Java API documentation: if the key is not present (or maps to null), the key is associated with the given non-null value.

Exam trap

Oracle often tests the misconception that the remapping function is always called, leading candidates to incorrectly choose option A, when in fact the function is only invoked for existing keys.

How to eliminate wrong answers

Option A is wrong because the remapping function is only called when the key is already present (and maps to a non-null value); when the key is absent, the function is not invoked at all. Option C is wrong because `Map.merge()` does not throw a `NullPointerException` when the key is absent; it only throws `NullPointerException` if the key or value is null (and the map does not support null keys/values), but absence of a key is a normal condition. Option D is wrong because `merge()` never removes a key when it is absent; removal only occurs if the remapping function returns null when the key is present.

310
Multi-Selecthard

Which TWO are valid multi-catch statements in Java 17? (Choose two.)

Select 2 answers
A.catch (SQLException | IOException e)
B.catch (Exception | RuntimeException e)
C.catch (SQLException | Exception e)
D.catch (IOException | FileNotFoundException e)
E.catch (IOException | RuntimeException e)
AnswersA, E

Valid; they are unrelated.

Why this answer

Java 17 allows a multi-catch clause to handle multiple exception types in a single catch block, provided the exception types are unrelated in the class hierarchy. SQLException and IOException are both checked exceptions that do not inherit from each other, so they can be caught together in a multi-catch statement.

Exam trap

The trap here is that candidates often forget the rule that multi-catch types must be unrelated in the class hierarchy, leading them to incorrectly select options that include a parent and child exception (like Exception and RuntimeException) or a subclass and its superclass (like IOException and FileNotFoundException).

311
Multi-Selecthard

Which three actions help secure a Java application that uses serialization? (Select three.)

Select 3 answers
A.Overriding resolveClass() in ObjectInputStream to validate class names.
B.Implementing ObjectInputFilter to set a deserialization filter.
C.Using transient keyword for sensitive fields.
D.Using SecureRandom to generate serialVersionUID.
E.Declaring serialVersionUID explicitly as a long constant.
AnswersA, B, C

Allows filtering of classes during deserialization.

Why this answer

Overriding `resolveClass()` in `ObjectInputStream` allows you to validate the class name before it is deserialized. This prevents deserialization attacks where an attacker sends a malicious class that could execute arbitrary code. By checking the class name against a whitelist, you can block untrusted classes from being loaded.

Exam trap

The trap here is that candidates often confuse versioning best practices (like declaring `serialVersionUID`) with security controls, or think that using `SecureRandom` for `serialVersionUID` adds security, when in fact it only breaks compatibility and does nothing to prevent deserialization attacks.

312
MCQeasy

Which loop construct guarantees that the body executes at least once?

A.for loop
B.enhanced for loop
C.while loop
D.do-while loop
AnswerD

Condition checked after body.

Why this answer

The do-while loop is the only loop construct in Java that guarantees the body executes at least once because the condition is evaluated after the loop body. This post-test loop design ensures that regardless of the initial condition value, the body runs before any check occurs.

Exam trap

The trap here is that candidates often confuse the do-while loop with the while loop, mistakenly thinking that a while loop can also guarantee at least one execution if the condition is true, but the key distinction is that only the do-while loop executes the body before checking the condition.

How to eliminate wrong answers

Option A is wrong because a for loop evaluates its condition before the first iteration; if the condition is false initially, the body never executes. Option B is wrong because an enhanced for loop (for-each) checks whether there are elements to iterate over before entering the body; if the array or collection is empty, the body never runs. Option C is wrong because a while loop evaluates its condition before the loop body; if the condition is false at the start, the body is skipped entirely.

313
MCQhard

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

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

Correct: This output matches the program's execution exactly: the pairs from i=0 and i=2, with i=1 omitted entirely.

Why this answer

The code uses a labeled continue statement 'continue outer' that, when i equals 1, skips the entire inner loop for that iteration. Thus, no output is produced when i=1. The output consists of the pairs from i=0 (j=0,1,2) and i=2 (j=0,1,2), resulting in '0 0 0 1 0 2 2 0 2 1 2 2', which is correctly represented in option D.

Exam trap

The trap here is that candidates often forget that continue outer skips the entire inner loop for the current outer iteration, not just the current inner iteration, leading them to include i=1 outputs or misformat the output.

How to eliminate wrong answers

Option A is wrong because it incorrectly includes '1-0' (i=1, j=0) which is never printed due to the continue outer when i=1. Option B is wrong because it includes all nine combinations (including i=1 rows), failing to account for the skip caused by continue outer. Option C is wrong because it uses hyphens instead of spaces between i and j values, and also omits the space between pairs; the actual output uses spaces, not hyphens.

314
MCQhard

What is the result of executing this code?

A.Compilation error
B.[b]
C.Runtime exception
D.[b, d]
AnswerC

Collectors.toUnmodifiableList returns an immutable list, calling add throws UnsupportedOperationException.

Why this answer

The code uses `Collectors.toUnmodifiableList()` which returns an unmodifiable list. Attempting to add an element to this list throws an `UnsupportedOperationException` at runtime. Therefore, option C (Runtime exception) is correct.

Exam trap

The trap is that candidates may not know that `Collectors.toUnmodifiableList()` returns an immutable list. They might think they can add elements to it, expecting the output to be something like `[b, d]`, but instead an `UnsupportedOperationException` is thrown at runtime.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; there is no syntax or type error. Option B is wrong because the code does not produce a list containing only 'b'; the removal operation triggers a runtime exception before any output. Option D is wrong because the code does not produce a list containing 'b' and 'd'; the exception occurs before the loop completes, so no output is generated.

315
MCQeasy

Given the code snippet: int x = 10; if (x > 5) { System.out.print("A"); } else if (x > 7) { System.out.print("B"); } else { System.out.print("C"); } What is the output?

A.C
B.ABC
C.A
D.B
AnswerC

The first condition is true.

Why this answer

The if-else chain evaluates conditions sequentially. Since x=10 satisfies x > 5, the first block executes and prints 'A'. The else if and else branches are skipped entirely because the first condition was true.

Thus, only 'A' is output.

Exam trap

The trap here is that candidates mistakenly think the else if condition (x > 7) is also true and will execute, or that all branches are evaluated sequentially, leading them to choose 'ABC' or 'B' instead of recognizing the exclusive nature of if-else-if.

How to eliminate wrong answers

Option A is wrong because it suggests 'C' is printed, but the else block only executes if all preceding conditions are false, which is not the case here. Option B is wrong because it implies all branches execute, but Java's if-else-if structure is mutually exclusive — only the first true branch runs. Option D is wrong because it assumes the else if condition (x > 7) is evaluated, but it is skipped once the first if condition is true.

316
MCQeasy

Which of the following correctly converts an array of strings to a List?

A.Collections.toList(array) converts the array.
B.List.of(array) returns a mutable list.
C.Arrays.asList(array) returns a fixed-size list backed by the array.
D.Arrays.asList(array) returns a new ArrayList with a copy of the elements.
AnswerC

Arrays.asList returns a list view of the array, fixed-size and mutable via set operations.

Why this answer

`Arrays.asList(array)` returns a fixed-size list backed by the original array, meaning changes to the list (like `set`) reflect in the array, but structural modifications (like `add` or `remove`) throw `UnsupportedOperationException`. This is the standard, exam-relevant way to convert an array to a List in Java.

Exam trap

The trap here is that candidates confuse `Arrays.asList()` with creating a fully mutable `ArrayList`, or they think `List.of()` returns a mutable list, but the exam specifically tests the fixed-size, array-backed nature of `Arrays.asList()` versus the immutability of `List.of()`.

How to eliminate wrong answers

Option A is wrong because `Collections.toList(array)` does not exist in the Java Collections Framework; the correct method is `Arrays.asList()`. Option B is wrong because `List.of(array)` returns an immutable list (not mutable), and any attempt to modify it throws `UnsupportedOperationException`. Option D is wrong because `Arrays.asList(array)` does not create a new `ArrayList` with a copy; it returns a fixed-size list backed directly by the original array, so changes to the list affect the array and vice versa.

317
Multi-Selecteasy

Which two statements are true about the peek method of the Stream API? (Choose two.)

Select 2 answers
A.It is primarily used for debugging purposes.
B.It is an intermediate operation.
C.It can be used to modify the elements of the stream.
D.It is a terminal operation.
E.It can be used to transform the elements into a new value.
AnswersA, B

peek is intended to aid in debugging by allowing observation of elements as they pass through the pipeline.

Why this answer

The `peek` method is designed as a debugging aid to observe elements as they flow through a stream pipeline. It performs the provided action on each element without modifying them, making it ideal for logging or printing intermediate states.

Exam trap

The trap here is that candidates confuse `peek` with `map`, thinking `peek` can modify or transform elements, when in fact `peek` only observes and returns the same elements unchanged.

318
Drag & Dropmedium

Arrange the steps to create a custom exception class in Java in the correct order.

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

Custom exceptions extend Exception (checked) or RuntimeException (unchecked). Constructors typically call super(message) or super(cause).

319
MCQeasy

A class `Account` has a method `public void deposit(double amount)`. Which approach correctly demonstrates method overloading?

A.Adding a method `public void deposit(int amount)`
B.Adding a method `public void deposit(double amount)` with different implementation
C.Adding a method `public int deposit(double amount)`
D.Adding a method `protected void deposit(double amount)`
AnswerA

Different parameter type overloads correctly.

Why this answer

Method overloading requires methods to have the same name but different parameter lists. Changing the parameter type from `double` to `int` satisfies this requirement, allowing the compiler to distinguish the methods at compile time based on the argument type.

Exam trap

The trap here is that candidates often confuse method overloading with method overriding, or mistakenly believe that changing the return type or access modifier alone is sufficient for overloading, when in fact only the parameter list matters.

How to eliminate wrong answers

Option B is wrong because it has the same name and same parameter list (`double amount`), which is a redefinition, not overloading — the compiler will treat it as a duplicate method declaration, causing a compilation error. Option C is wrong because changing only the return type (from `void` to `int`) while keeping the same parameter list does not constitute overloading; the return type is not part of the method signature in Java. Option D is wrong because changing only the access modifier (from `public` to `protected`) while keeping the same parameter list does not change the method signature; it is still a duplicate method declaration.

320
MCQmedium

A developer wants to include a module in a custom runtime image using jlink. The module's `module-info.java` does not explicitly export any packages. When running the application from the custom image, a ClassNotFoundException is thrown for a class from that module. What is the most likely cause?

A.The application does not require the module.
B.The module's packages are not exported, making them invisible to other modules.
C.The module uses an automatic module that is not present.
D.The module was not included in the jlink command.
AnswerB

Unexported packages are not accessible, causing ClassNotFoundException.

Why this answer

If a module's `module-info.java` does not explicitly export any packages, those packages are not accessible to other modules at runtime. Even if the module is included in the custom runtime image via jlink, the `ClassNotFoundException` occurs because the class is not exported, making it invisible to other modules. The `jlink` tool includes the module's classes in the image, but without an `exports` directive, the packages remain encapsulated.

Exam trap

The trap here is that candidates assume including a module in the jlink command is sufficient to make all its classes accessible, but the Java module system enforces encapsulation at the package level, so without explicit `exports`, the classes are invisible to other modules.

How to eliminate wrong answers

Option A is wrong because the application may still `require` the module in its `module-info.java`, but that only grants compile-time and runtime access to the module's exported packages; if no packages are exported, requiring the module does not make its internal classes visible. Option C is wrong because the issue is about a named module with no exports, not about an automatic module; automatic modules export all their packages by default, so a missing automatic module would cause a different error (e.g., `ModuleNotFoundException`). Option D is wrong because if the module were not included in the jlink command, the custom image would not contain the module at all, leading to a `ModuleNotFoundException` or `NoClassDefFoundError` rather than a `ClassNotFoundException` for a class from that module.

321
MCQhard

Refer to the exhibit. What is the output?

A.88.0
B.88.33333333333333
C.85.0
D.85.75
AnswerB

Correct. The average of 85, 92, and 88 is (85+92+88)/3 = 265/3 = 88.33333333333333.

Why this answer

The code creates an IntStream with values 85, 92, and 88, then calls average() to compute the arithmetic mean. This returns an OptionalDouble, and orElse(0.0) extracts the value. The sum 85+92+88 = 265, divided by 3 gives 88.33333333333333, which matches option B exactly.

No integer division occurs because average() always returns a double.

Exam trap

The trap here is that candidates might mistakenly think integer division applies (e.g., 265/3 = 88 with truncation) or misread the output format, but the stream's `average()` method always returns a `double` with full precision.

How to eliminate wrong answers

Option A is wrong because it duplicates the correct output but is listed as a separate option; the question marks B as correct, so A is not the intended answer. Option C is wrong because 85.0 would result from averaging only the first number (85) or from integer division without casting, but the stream correctly sums all three integers and divides by 3.0. Option D is wrong because 85.75 would require a different set of numbers (e.g., 85, 86, 86) or a miscalculation of the sum (265/3 = 88.333..., not 85.75).

322
MCQmedium

A company uses serialization to transfer objects between microservices. To prevent deserialization attacks, they want to restrict which classes can be deserialized. Which approach should be used in Java 17?

A.Override resolveClass in ObjectInputStream
B.Use SecurityManager with a policy file
C.Use ObjectInputFilter with a custom filter
D.Implement Externalizable and control fields
AnswerC

ObjectInputFilter is the recommended approach to restrict deserialized classes in modern Java.

Why this answer

Java 17 provides the `ObjectInputFilter` API (introduced in Java 9) as the standard mechanism to restrict which classes can be deserialized. By setting a custom filter via `ObjectInputStream.setObjectInputFilter()` or a system-wide `jdk.serialFilter` property, you can whitelist or blacklist classes based on patterns, effectively preventing deserialization attacks without modifying the serialization stream itself.

Exam trap

The trap here is that candidates often confuse `resolveClass` (which loads a class) with `ObjectInputFilter` (which filters class resolution), or they assume `SecurityManager` is still the correct tool for this task despite its deprecation in Java 17.

How to eliminate wrong answers

Option A is wrong because overriding `resolveClass` in `ObjectInputStream` only controls which class is loaded for a given stream descriptor, but it does not provide a flexible, pattern-based filtering mechanism and can be bypassed if not carefully implemented; it is also not the recommended approach in modern Java. Option B is wrong because `SecurityManager` with a policy file is deprecated for removal in Java 17 and was never designed specifically to filter deserialization classes—it controls permissions, not the content of serialized streams. Option D is wrong because implementing `Externalizable` controls the serialization format and fields, but it does not restrict which classes can be deserialized; an attacker could still send a malicious serialized object of a different class.

323
MCQmedium

A developer is building a file synchronization tool that runs on multiple threads. Multiple threads may read and write to the same file concurrently. The developer wants to ensure that a thread does not read a file while another thread is writing to it, and that concurrent reads are allowed. Which locking mechanism should be used?

A.Use a ReentrantReadWriteLock in Java with the file as a resource.
B.Use synchronized blocks on the File object.
C.Use a Semaphore with permits equal to the number of threads.
D.Use java.nio.channels.FileLock with shared lock for reading and exclusive lock for writing.
AnswerD

FileLock with shared/exclusive modes allows concurrent reads and exclusive writes, and works across processes.

Why this answer

Java.nio.channels.FileLock provides a platform-independent mechanism for locking files, supporting shared locks for concurrent reads and exclusive locks for writes. This ensures that a thread cannot read a file while another thread is writing to it, while allowing multiple threads to read simultaneously, which matches the requirement exactly.

Exam trap

The trap here is that candidates often confuse in-memory concurrency mechanisms (like ReentrantReadWriteLock or synchronized) with file-level locking, forgetting that file access across threads or processes requires OS-level coordination provided by FileLock.

How to eliminate wrong answers

Option A is wrong because ReentrantReadWriteLock is a Java concurrency utility that works on in-memory objects, not on file system resources; it cannot coordinate access across threads that may be in different JVMs or processes. Option B is wrong because synchronized blocks on the File object only provide mutual exclusion within the same JVM, and they do not differentiate between read and write access, thus blocking concurrent reads unnecessarily. Option C is wrong because a Semaphore with permits equal to the number of threads can limit concurrency but does not distinguish between read and write operations, so it cannot allow concurrent reads while blocking writes.

324
Multi-Selecteasy

Which TWO statements about the break and continue statements in Java are correct?

Select 2 answers
A.The break statement without a label always terminates the innermost enclosing loop or switch.
B.The continue statement can be used inside any loop, including for, while, and do-while loops.
C.The continue statement can be used inside a switch statement to skip the rest of the switch body.
D.The break statement can be used only inside loops and switch statements.
E.The continue statement without a label skips the current iteration and proceeds to the next iteration without reevaluating the loop condition.
AnswersA, B

break without a label exits the innermost loop or switch.

Why this answer

The break statement without a label, when executed inside a loop or switch, immediately terminates the innermost enclosing loop or switch construct. This is defined by the Java Language Specification (JLS §14.15), which states that an unlabeled break statement transfers control to the immediately enclosing statement of the break target.

Exam trap

The trap here is that candidates often confuse the behavior of continue in different loop types (for vs. while) and incorrectly assume it skips condition reevaluation, or they mistakenly think break can only target loops and switches, ignoring its use with labeled blocks.

325
MCQmedium

A developer needs to filter a list of transactions where the amount is greater than 100 and collect the results into a new list. Which approach is best practice for readability and performance?

A.transactions.stream().filter(t -> t.getAmount() > 100).collect(Collectors.toList())
B.List<Transaction> result = new ArrayList<>(); for(Transaction t : transactions) { if(t.getAmount() > 100) result.add(t); }
C.transactions.stream().filter(t -> t.getAmount() > 100).toArray()
D.transactions.removeIf(t -> t.getAmount() <= 100)
AnswerA

Stream API is best practice for filtering and collecting into a new list.

Why this answer

It uses the Stream API's `filter` method to declaratively select transactions with an amount greater than 100, and `collect(Collectors.toList())` to gather results into a new list. This approach is both readable and performant, leveraging lazy evaluation and internal iteration for efficient processing.

Exam trap

The trap here is that candidates may choose Option D, thinking `removeIf` is a filter, but it mutates the original collection and does not create a new list, which is explicitly required by the question.

How to eliminate wrong answers

Option B is wrong because it uses imperative external iteration with a for-each loop and manual list addition, which is more verbose, less readable, and can be slower due to lack of optimization like parallel stream support. Option C is wrong because `toArray()` returns an array, not a List, failing the requirement to collect into a new list. Option D is wrong because `removeIf` modifies the original list in-place, which violates the requirement to collect results into a new list and may cause side effects or ConcurrentModificationException if the list is unmodifiable.

326
MCQmedium

What is the output of the above code?

A.[a, b]
B.[a, c]
C.[a, b, c]
D.[b, c]
E.Compilation fails
AnswerB

Correct: "b" is removed, leaving a and c.

Why this answer

The code uses `List.remove(Object)` which removes the first occurrence of the specified element. After removing "b" from the list [a, b, c], the list becomes [a, c]. Option B is correct because the output is [a, c].

Exam trap

The trap here is that candidates may confuse `remove(Object)` with `remove(int index)` and think the code removes the element at index 1 (which would be "b" as well), but the correct understanding is that `remove(Object)` removes by value, not by index.

How to eliminate wrong answers

Option A is wrong because it suggests the list remains [a, b], but the removal of "b" changes the list. Option C is wrong because it implies no removal occurred, but the remove operation successfully removes "b". Option D is wrong because it suggests both "a" and "b" are removed, but only "b" is removed.

Option E is wrong because the code compiles and runs without error; `List.remove(Object)` is a valid method.

327
MCQeasy

You are developing a Java application that processes sensitive user data. The application runs on a server with strict security policies. You need to read configuration properties from a file located at /etc/app/config.properties. The application uses a SecurityManager. During testing, you get a security exception: java.security.AccessControlException: access denied (java.io.FilePermission /etc/app/config.properties read). You have already added a file permission grant in the policy file for the application codebase. However, the exception persists. What is the most likely cause?

A.The application codebase URL in the policy file is incorrect.
B.A library or caller on the execution stack does not have the required FilePermission.
C.The file path is relative and needs to be resolved against user.dir.
D.The policy file is not being loaded because the JVM was not started with -Djava.security.policy.
AnswerB

SecurityManager requires all callers in the chain to have permission.

Why this answer

Even if the application's own codebase has the required FilePermission, any library or caller on the execution stack that does not have the permission will cause an AccessControlException. The SecurityManager performs stack inspection: every class on the call stack must have the required permission. If a library or framework method invoked by your code lacks the grant, the check fails.

Exam trap

The trap here is that candidates assume granting permission to the application codebase alone is sufficient, forgetting that the SecurityManager checks all callers on the execution stack, not just the top-level application code.

How to eliminate wrong answers

Option A is wrong because an incorrect codebase URL would prevent the policy grant from being applied to your code, but the question states you already added the grant and the exception persists, so the URL is likely correct. Option C is wrong because the file path is absolute (/etc/app/config.properties), not relative, so there is no resolution against user.dir. Option D is wrong because if the policy file were not loaded at all, the exception would still occur, but the question says you added a grant and the exception persists, implying the policy file is loaded but the grant is insufficient due to stack inspection.

328
MCQmedium

A team is migrating a large legacy application from Java 8 to Java 17. The application consists of multiple JAR files that are placed on the classpath. Some of these JAR files have been updated to include module-info.class files, making them named modules. After migration, the application throws `IllegalAccessError` for several deep reflection calls that used to work in Java 8. The team has added `--add-opens` JVM flags to open the required packages, but the error persists. The application also uses a third-party library that is not modularized and is placed on the classpath. The team notices that the `--add-opens` flags are being ignored for packages in the modularized JARs. What is the most likely reason?

A.The `--add-opens` flags are being overridden by other JVM flags.
B.The application does not have a module-info.java file for its own code.
C.The modularized JARs are being loaded from the classpath, so they become unnamed modules, and `--add-opens` does not apply to unnamed modules.
D.The classpath is deprecated and ignored in Java 17, so all JARs are treated as modules.
AnswerC

`--add-opens` only applies to named modules. JARs on the classpath, even if they have module-info, are treated as unnamed modules if placed on the classpath. They must be on the module path to be named modules.

Why this answer

When a JAR file containing a module-info.class is placed on the classpath instead of the module path, it is treated as an unnamed module. The `--add-opens` JVM flag only applies to named modules (those on the module path) and has no effect on unnamed modules. Since the modularized JARs are loaded from the classpath, they become unnamed modules, and the `--add-opens` flags are ignored, causing the `IllegalAccessError` to persist.

Exam trap

Oracle often tests the misconception that placing a modularized JAR on the classpath still makes it a named module, leading candidates to overlook the critical distinction between classpath (unnamed module) and module path (named module) in Java 9+.

How to eliminate wrong answers

Option A is wrong because there is no evidence or common mechanism by which other JVM flags would override `--add-opens`; these flags are additive and not overridden by default. Option B is wrong because the absence of a module-info.java for the application's own code does not cause `--add-opens` to be ignored; unnamed modules can still benefit from `--add-opens` if the target packages are in named modules, but here the target packages are in unnamed modules. Option D is wrong because the classpath is not deprecated or ignored in Java 17; it still works, but JARs on the classpath are treated as unnamed modules, not as named modules.

329
MCQhard

A Java application needs to refer to a file using the path "data/input.txt". To ensure platform independence (correct file separator), which approach is recommended?

A.FileSystems.getDefault().getPath("data", "input.txt")
B.new File("data/input.txt").toPath().normalize()
C.new File("data/input.txt").toPath()
D.Paths.get("data", "input.txt")
AnswerD

Correct. Paths.get() uses the default file system's path separator, ensuring platform independence.

Why this answer

`Paths.get("data", "input.txt")` uses the default file system's path separator, ensuring platform independence. This method internally calls `FileSystems.getDefault().getPath()` to construct the path with the correct separator for the operating system (e.g., '/' on Linux/macOS, '\' on Windows).

Exam trap

The trap here is that candidates often think `new File("data/input.txt").toPath()` is sufficient, but it fails platform independence because the string literal contains a hardcoded forward slash, which is not the correct separator on Windows.

How to eliminate wrong answers

Option A is wrong because `FileSystems.getDefault().getPath("data", "input.txt")` is functionally equivalent to `Paths.get("data", "input.txt")`, but it is more verbose and not the recommended approach for simplicity. Option B is wrong because `new File("data/input.txt").toPath().normalize()` uses a hardcoded forward slash, which is not platform-independent, and `normalize()` only removes redundant path elements like '.' or '..', not the separator. Option C is wrong because `new File("data/input.txt").toPath()` still relies on a hardcoded forward slash in the string, which will fail on Windows where the separator is backslash.

330
MCQmedium

A Java application uses SecurityManager with a policy file. Which permission is required to allow the application to read all files in the /var/log directory, including subdirectories?

A.permission java.io.FilePermission "/var/log", "read";
B.permission java.io.FilePermission "/var/log/-", "read";
C.permission java.io.FilePermission "/var/log/*", "read,write";
D.permission java.io.FilePermission "/var/log/*", "read";
AnswerB

"-" grants access to all files and subdirectories recursively.

Why this answer

The trailing '-' in the path pattern '/var/log/-' is a recursive wildcard that matches all files and subdirectories under /var/log, which is required to read all files in that directory tree. The permission grants 'read' access, which is the only action needed for reading files.

Exam trap

The trap here is that candidates often confuse the single-level wildcard '*' with the recursive wildcard '-', leading them to choose option D which only grants access to files directly in /var/log, not subdirectories.

How to eliminate wrong answers

Option A is wrong because '/var/log' without a wildcard matches only the directory entry itself, not its contents or subdirectories. Option C is wrong because it includes 'write' permission, which is unnecessary for reading files, and uses '*' which matches only direct children, not recursive subdirectories. Option D is wrong because '*' matches only files and directories directly inside /var/log, not those in subdirectories.

331
MCQhard

A financial services company runs a Java 17 Spring Boot application that processes real-time stock trades. The application uses a class `TradeProcessor` containing a method `void process(Trade trade)`. This method is invoked by multiple threads concurrently. The `Trade` class is immutable and has fields like `String symbol`, `int quantity`, `double price`. The `TradeProcessor` method updates a shared `HashMap<String, Double>` that tracks the average price per symbol. The update logic is: retrieve the current average for the symbol, compute a new average, and put it back. During high-load testing, the average prices are occasionally incorrect. The development team suspects a race condition. Which course of action should be taken to fix the issue with minimal performance impact?

A.Use an `AtomicReference` to wrap the `HashMap`.
B.Replace `HashMap` with `ConcurrentHashMap` and use the `compute` method to atomically update the average.
C.Synchronize the entire `process` method.
D.Change the `HashMap` to `Hashtable`.
AnswerB

ConcurrentHashMap provides atomic compute methods suitable for this scenario without explicit locking.

Why this answer

`ConcurrentHashMap` provides thread-safe atomic operations like `compute`, which allows you to atomically update the average price per symbol without external synchronization. This avoids the race condition where two threads read the same old average, compute a new one, and overwrite each other's result. Using `compute` ensures the read-modify-write sequence is performed atomically, with minimal performance overhead compared to synchronizing the entire method.

Exam trap

The trap here is that candidates often think `ConcurrentHashMap` alone solves all concurrency issues, but without using atomic methods like `compute`, `merge`, or `replace`, the read-modify-write race condition persists; the exam tests whether you know that `ConcurrentHashMap`'s per-operation thread safety does not automatically compose into atomic compound actions.

How to eliminate wrong answers

Option A is wrong because wrapping a `HashMap` with `AtomicReference` does not make the map's internal operations thread-safe; it only provides atomicity for replacing the entire map reference, not for individual read-modify-write operations on entries. Option C is wrong because synchronizing the entire `process` method would serialize all trade processing, causing a severe performance bottleneck under high load, which contradicts the requirement for minimal performance impact. Option D is wrong because `Hashtable` uses method-level synchronization on every operation, which is coarse-grained and leads to contention, but more importantly, it does not provide atomic compound operations like `compute`; the race condition would still occur because the get-and-put sequence is not atomic.

332
MCQmedium

A company processes financial transactions. Each transaction is represented by a Transaction object with fields: amount (double), currency (String), and type (String). The requirement is to compute the total amount of all transactions of type 'SALE' in USD. The transactions are stored in a List<Transaction>. Which code correctly accomplishes this using streams?

A.transactions.stream().mapToDouble(Transaction::amount).filter(t -> t.type().equals("SALE")).sum()
B.transactions.stream().filter(t -> t.type().equals("SALE")).filter(t -> t.currency().equals("USD")).mapToDouble(Transaction::amount).sum()
C.transactions.stream().map(Transaction::amount).reduce(0.0, (a, b) -> a + b)
D.transactions.stream().filter(t -> t.type().equals("SALE") && t.currency().equals("USD")).mapToDouble(Transaction::amount).sum()
AnswerD

Correctly filters by type and currency, then sums amounts.

Why this answer

Ly filters transactions to only those with type 'SALE' and currency 'USD', then maps each to its amount as a double, and sums them using sum(). This satisfies the requirement exactly: total amount of 'SALE' transactions in USD.

Exam trap

Oracle often tests the order of stream operations — specifically that filter must come before mapToDouble when the filter condition depends on object fields, otherwise the stream loses access to the original object type.

How to eliminate wrong answers

Option A is wrong because it maps to double before filtering, so the filter cannot access the Transaction object's type field — it would attempt to filter on a double, causing a compilation error. Option B is wrong because it filters for both 'SALE' and 'USD', but the requirement only asks for 'SALE' transactions in USD — this is actually correct in logic but the filter order is inefficient; however, the real issue is that it is not the most direct answer and D is more concise. Option C is wrong because it maps all transactions to their amounts without any filtering, summing all amounts regardless of type or currency, which does not meet the requirement.

333
MCQmedium

Which design pattern is best suited for creating a family of related objects without specifying their concrete classes?

A.Builder
B.Singleton
C.Abstract Factory
D.Factory Method
AnswerC

Abstract Factory creates families of related objects.

Why this answer

The Abstract Factory pattern is designed to create families of related or dependent objects without specifying their concrete classes. It provides an interface for creating families of products, ensuring that the products from one family are used together, which is a core requirement of the question.

Exam trap

The trap here is that candidates often confuse Factory Method (which creates a single product) with Abstract Factory (which creates a family of products), leading them to select Factory Method when the question explicitly asks for a family of related objects.

How to eliminate wrong answers

Option A is wrong because the Builder pattern focuses on constructing a complex object step by step, separating the construction from its representation, not on creating families of related objects. Option B is wrong because the Singleton pattern ensures a class has only one instance and provides a global point of access, which is unrelated to object family creation. Option D is wrong because the Factory Method pattern defines an interface for creating a single object but lets subclasses decide which class to instantiate, which does not address creating a family of related objects.

334
MCQhard

A financial application processes a daily batch of 10 million transactions. Each transaction is an object with fields: id, amount, and status (an enum: PENDING, APPROVED, REJECTED). The requirement is to find the first APPROVED transaction with amount greater than 1000. The current implementation uses a while loop with a nested if-else structure that checks each transaction sequentially. The loop also logs each transaction status, which involves a moderately expensive file write operation. Performance analysis shows the method is a bottleneck, often taking over 12 seconds. The development team is considering refactoring. Which course of action will most effectively reduce execution time while maintaining the requirement?

A.Refactor the while loop into a recursive method that processes one transaction per call and stops when the condition is met.
B.Replace the while loop with a parallel stream and use findFirst() to get the first matching transaction.
C.Replace the while loop with a for-each loop that breaks when the condition is met, but keep the logging inside the loop.
D.Replace the while loop with a traditional for loop that uses a break when the first match is found, and defer the logging to a separate batch process after the loop.
AnswerD

Early break reduces iterations, and removing logging I/O from the loop drastically improves performance. Batch logging can be done asynchronously.

Why this answer

It removes the expensive file write operation from the loop, which is the primary cause of the bottleneck. By deferring logging to a separate batch process, the loop can iterate quickly and break immediately upon finding the first APPROVED transaction with amount > 1000, drastically reducing execution time while still meeting the requirement.

Exam trap

In an Oracle Java exam, the trap is that candidates focus on loop structure (while vs for vs recursion) or parallelism, but overlook the real bottleneck: the expensive file write operation inside the loop, which must be removed or deferred to achieve significant performance gains.

How to eliminate wrong answers

Option A is wrong because recursion does not eliminate the expensive logging operation and introduces stack overhead for 10 million transactions, likely causing a StackOverflowError. Option B is wrong because parallel streams with findFirst() do not guarantee order preservation in a way that finds the first sequential match; findFirst() on a parallel stream still respects encounter order but incurs significant synchronization overhead, and the logging cost remains. Option C is wrong because it keeps the expensive logging inside the loop, so even with a break, the file write per transaction still dominates execution time.

335
MCQmedium

A developer needs to ensure that a class `Shape` cannot be instantiated but can be extended. Which modifier should be used?

A.private
B.final
C.abstract
D.sealed
AnswerC

Abstract classes cannot be instantiated and are meant to be extended.

Why this answer

The `abstract` modifier is correct because an abstract class cannot be instantiated directly, but it can be extended by subclasses. This enforces the design intent that `Shape` serves as a base class for specific shapes like `Circle` or `Rectangle`, while preventing the creation of a generic `Shape` object.

Exam trap

The trap here is that candidates often confuse `abstract` with `final` or `sealed`, mistakenly thinking that preventing instantiation requires a modifier that blocks extension, when in fact `abstract` is the only modifier that both prevents instantiation and allows extension.

How to eliminate wrong answers

Option A is wrong because `private` is an access modifier that restricts visibility, not instantiation; a private class cannot be accessed outside its enclosing scope, but it can still be instantiated within that scope. Option B is wrong because `final` prevents a class from being extended, which is the opposite of the requirement to allow extension. Option D is wrong because `sealed` restricts which classes can extend it to a predefined set, but it does not prevent instantiation of the sealed class itself; a sealed class can still be instantiated unless it is also abstract.

336
MCQmedium

Consider the following code snippet: try { // some code } catch (IOException e) { // handle } catch (FileNotFoundException e) { // Line X // handle } What will be the result?

A.The code compiles and runs without issues.
B.The code compiles but throws a ClassCastException at runtime.
C.The code compiles but the second catch never executes.
D.Compilation fails at Line X with an error about an exception already caught.
AnswerD

Correct: FileNotFoundException is already caught by IOException.

Why this answer

In Java, when catching exceptions, the more specific exception subclass must be caught before the more general superclass. FileNotFoundException is a subclass of IOException, so catching IOException first makes the catch for FileNotFoundException unreachable, causing a compilation error at Line X.

Exam trap

The trap here is that candidates may think the code compiles and the second catch simply never runs, but Java enforces this at compile time to prevent unreachable code, not just at runtime.

How to eliminate wrong answers

Option A is wrong because the code does not compile due to the order of catch blocks. Option B is wrong because the code fails to compile, so no runtime exception like ClassCastException can occur. Option C is wrong because the code does not compile; the second catch block is not merely unreachable at runtime but causes a compile-time error.

337
Multi-Selectmedium

Which TWO statements about Java module types are true?

Select 2 answers
A.An automatic module exports all its packages.
B.An automatic module can access all packages of named modules without explicit requires.
C.The unnamed module can read only the java.base module.
D.A named module requires a module-info.java file at compile time.
E.The unnamed module is a named module.
AnswersA, D

Automatic modules export every package in the JAR.

Why this answer

The Java module system automatically exports all packages of an automatic module, making them accessible to other modules without explicit export declarations. This is a key characteristic of automatic modules, which are created from JAR files placed on the module path without a module-info.java file.

Exam trap

The trap here is confusing the 'reads all other modules' capability of automatic modules with the ability to access all packages of those modules, when in fact only exported packages are accessible.

338
MCQeasy

A web application allows users to upload profile pictures. The application saves the files to a directory using the original filename provided by the user. After a security review, the team discovered a critical path traversal vulnerability. Which remediation is most effective in preventing exploitation while maintaining usability?

A.Store the files in a database BLOB instead of the filesystem.
B.Sanitize the filename by removing all occurrences of "../" and "/".
C.Check that the file extension is allowed (e.g., .jpg, .png) and no special characters.
D.Generate a random UUID as the filename and store the original filename in a database.
AnswerD

By not using the user-provided filename in the path, traversal is impossible.

Why this answer

Generating a random UUID as the filename eliminates the user's control over the file path, making path traversal attacks impossible. The original filename can be stored in a database for display purposes, preserving usability while ensuring the file is saved with a safe, unpredictable name.

Exam trap

The trap here is that candidates often think sanitizing input (Option B) or checking extensions (Option C) is sufficient, but they fail to realize that path traversal can be achieved through encoding tricks or by combining traversal sequences with valid extensions.

How to eliminate wrong answers

Option A is wrong because storing files in a database BLOB does not prevent path traversal; it only changes the storage medium, and the vulnerability could still exist if the filename is used in retrieval logic. Option B is wrong because removing only "../" and "/" is insufficient; attackers can use encoded variants (e.g., "..%2f") or other traversal patterns like "....//" to bypass the filter. Option C is wrong because checking the file extension alone does not prevent path traversal; an attacker could still include directory traversal sequences in the filename (e.g., "../../etc/passwd.jpg") that pass the extension check.

339
MCQmedium

A method uses an enhanced for loop to iterate over a list of strings and prints each string. The code is: ```java List<String> list = List.of("A", "B", "C"); for (String s : list) { if (s.equals("B")) { break; } System.out.print(s); } ``` What is the result?

A.The code throws a ConcurrentModificationException.
B.ABC
C.A
D.AB
AnswerC

Prints A, then breaks at B.

Why this answer

The enhanced for loop iterates over the list, and when it encounters the string "B", the break statement immediately exits the loop. Therefore, only "A" is printed before the loop terminates. Option C is correct because the output is just "A".

Exam trap

The trap here is that candidates may think the break statement causes a ConcurrentModificationException or that it prints "AB" because they forget that break exits the loop before executing the print statement for the matched element.

How to eliminate wrong answers

Option A is wrong because the enhanced for loop does not allow structural modification of the list during iteration, but here no modification occurs—only a break statement is used, so no ConcurrentModificationException is thrown. Option B is wrong because the break statement prevents printing "B" and "C", so the output is not "ABC". Option D is wrong because the break occurs before printing "B", so only "A" is printed, not "AB".

340
MCQeasy

Refer to the exhibit. The exhibit shows a stack trace from a Java application. Which line in the code caused the NullPointerException?

A.Line 10: System.out.println(len);
B.Line 12: String s = "hello";
C.Line 5: int x = 10;
D.Line 8: int len = s.length();
AnswerD

The stack trace explicitly shows line 8.

Why this answer

The NullPointerException occurs when invoking the `length()` method on a null reference. In the stack trace, the exception is thrown at line 8, where `s.length()` is called, but `s` has not been assigned a non-null value (it is null by default if declared as a field, or uninitialized locally). The JVM throws NullPointerException when any instance method is called on a null object reference.

Exam trap

The trap here is that candidates may confuse the line where the exception is thrown (line 8) with the line where the variable is declared (line 12), mistakenly thinking the declaration itself causes the error, but the exception only occurs when the null reference is actually used.

How to eliminate wrong answers

Option A is wrong because `System.out.println(len)` on line 10 simply prints the integer variable `len`, which would have been assigned a value if line 8 succeeded; it does not cause a NullPointerException. Option B is wrong because `String s = "hello";` on line 12 assigns a non-null String literal to `s`, which is a safe operation and does not throw NullPointerException. Option C is wrong because `int x = 10;` on line 5 is a primitive assignment that never involves object references, so it cannot produce a NullPointerException.

341
MCQeasy

A developer has created a modular Java application. They want to distribute a minimal runtime image containing only the required modules. Which tool should they use?

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

jlink creates a custom runtime image with only required modules.

Why this answer

B is correct because `jlink` is the Java tool specifically designed to assemble and optimize a minimal runtime image containing only the modules explicitly required by the application and its transitive dependencies. It links the specified modules and their dependencies into a custom JRE that excludes unused modules, reducing footprint for distribution.

Exam trap

The trap here is that candidates confuse `jpackage` (which creates installers) with `jlink` (which creates the runtime image), or assume `jar` can produce a runnable image because it can create executable JARs with a manifest.

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 runtime images or handle module linking. Option C is wrong because `jar` packages compiled classes and resources into a JAR archive, but it cannot produce a standalone runtime image with a custom JRE. Option D is wrong because `jpackage` packages a self-contained application installer for a target platform, but it relies on `jlink` internally to create the runtime image; the question asks for the tool to create the minimal runtime image itself, not the installer.

342
MCQmedium

A method returns a List<Integer>. The caller wants to ensure the list cannot be modified. Which is the best approach?

A.return Arrays.asList(list.toArray());
B.return new ArrayList<>(list);
C.return (List<Integer>) list.clone();
D.return Collections.unmodifiableList(list);
AnswerD

Returns an unmodifiable view.

Why this answer

`Collections.unmodifiableList()` returns a read-only view of the specified list. Any attempt to modify the returned list (e.g., via `add`, `remove`, `set`) will throw an `UnsupportedOperationException`. This is the standard, recommended approach in the Java Collections Framework to provide an unmodifiable wrapper without copying the underlying data.

Exam trap

The trap here is that candidates often confuse 'unmodifiable view' with 'immutable copy' and may pick options like `Arrays.asList()` or `clone()` thinking they prevent modification, but those still allow structural changes or mutation through the backing array.

How to eliminate wrong answers

Option A is wrong because `Arrays.asList(list.toArray())` creates a fixed-size list backed by the array, but the list itself is still modifiable via `set` and the underlying array can be mutated; it does not guarantee immutability. Option B is wrong because `new ArrayList<>(list)` creates a new mutable copy of the list, allowing the caller to modify it freely. Option C is wrong because `list.clone()` returns a shallow copy of the list, but the returned list is still mutable; additionally, the cast to `List<Integer>` is redundant and the clone method's contract does not guarantee immutability.

343
MCQhard

A developer is migrating a classpath-based application to modules. They have two JARs on the classpath that both contain a package with the same name, com.example.util. When they move both JARs to the module path, they encounter a module resolution error. What is the most likely cause?

A.The --add-exports option is missing
B.Named modules cannot have split packages
C.The JARs need to be merged into one module
D.Automatic modules cannot have split packages
AnswerB

Both JARs become automatic modules (named), and split packages are disallowed among named modules.

Why this answer

In the Java module system, a package can be defined in at most one module on the module path. When both JARs contain com.example.util, moving them to the module path creates a split package, which is illegal for named modules. The module system enforces this to ensure reliable configuration and encapsulation, resulting in a module resolution error.

Exam trap

Candidates often confuse the leniency of automatic modules regarding module readability with the rules for split packages. In fact, split packages are illegal for any named module, including automatic modules. The module system strictly enforces that each package is defined in at most one module on the module path.

How to eliminate wrong answers

Option A is wrong because --add-exports is used to export a package from a module to another module at runtime, not to resolve split packages; the error occurs at module resolution, not at access time. Option C is wrong because merging the JARs into one module is a possible solution, but the question asks for the most likely cause of the error, not the fix; the cause is the split package violation. Option D is wrong because automatic modules can indeed have split packages with other automatic modules or with the unnamed module; the restriction against split packages applies strictly to named modules.

344
Multi-Selecthard

Which THREE statements are true about HashSet in Java 17? (Choose three.)

Select 3 answers
A.Does not maintain insertion order
B.Allows duplicate elements
C.Is thread-safe
D.Has constant-time performance for basic operations
E.Allows at most one null element
AnswersA, D, E

Order is not guaranteed.

Why this answer

HashSet is backed by a HashMap, which uses hash codes to store elements in buckets. The iteration order depends on the hash values and bucket distribution, which can change when the set is resized, so insertion order is not preserved.

Exam trap

The trap here is that candidates often confuse HashSet's lack of ordering with the ability to hold duplicates, or assume that 'constant-time performance' means guaranteed O(1) regardless of hash collisions, but the exam expects you to know that it is amortized constant-time under typical conditions.

345
MCQhard

You are developing a high-frequency trading application that processes a stream of market data ticks. Each tick is represented by a Tick object with fields: long timestamp, String symbol, double price, int volume. Ticks arrive in real-time and must be processed in order. A bug is reported: the application occasionally processes a tick out of order, causing incorrect trade decisions. The processing logic uses a while loop to read from a blocking queue and process each tick. The code is: BlockingQueue<Tick> queue = new LinkedBlockingQueue<>(); while (true) { Tick tick = queue.take(); process(tick); } After investigation, you find that the queue is fed by multiple producer threads that sometimes reorder ticks due to network delays. Which course of action best ensures ticks are processed in the correct chronological order without sacrificing throughput?

A.Use a SynchronousQueue and have producers wait for the consumer to acknowledge.
B.After taking from the queue, sort a batch of ticks before processing.
C.Replace LinkedBlockingQueue with a PriorityBlockingQueue that orders by timestamp.
D.Add a delay before processing to allow out-of-order ticks to arrive.
AnswerC

PriorityBlockingQueue maintains ordering by timestamp.

Why this answer

PriorityBlockingQueue maintains elements in natural order (or by a provided Comparator), so ticks are automatically ordered by timestamp when inserted. This ensures the consumer always processes the chronologically earliest tick first, even if producers add them out of order, without requiring additional sorting or blocking.

Exam trap

The trap here is that candidates may think sorting after retrieval (Option B) is sufficient, but they overlook that PriorityBlockingQueue provides automatic ordering at insertion time, which is more efficient and maintains correctness without batching delays.

How to eliminate wrong answers

Option A is wrong because SynchronousQueue has zero capacity and requires each producer to wait for the consumer to take the element, which serializes access and severely reduces throughput in a multi-producer scenario. Option B is wrong because sorting a batch after taking from the queue introduces latency and does not guarantee global chronological order if ticks arrive continuously; it also violates the real-time processing requirement. Option D is wrong because adding a fixed delay does not guarantee that all out-of-order ticks will arrive before processing, and it unnecessarily increases latency, reducing throughput.

346
Multi-Selectmedium

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

Select 2 answers
A.A module can export a package only to specific modules using 'exports ... to ...'
B.The module-info.java file must be compiled with javac and placed in the root of the JAR.
C.All packages in a module are automatically exported.
D.The jdeps tool can be used to create a module graph.
E.The jlink tool creates a JAR file containing the module.
AnswersA, B

Qualified exports limit access to specified modules.

Why this answer

The 'exports ... to ...' directive in module-info.java restricts the exported package to only the specified target modules, providing fine-grained access control. This is a key feature of the Java module system introduced in Java 9, allowing a module to expose its packages only to trusted modules rather than all other modules.

Exam trap

Oracle often tests the misconception that all packages in a module are automatically exported, but in reality, only explicitly exported packages are accessible outside the module, and the jlink tool creates a runtime image, not a JAR file.

347
Multi-Selecthard

Which TWO are secure coding practices for Java I/O that help prevent resource leaks and unauthorized access? (Choose two.)

Select 2 answers
A.Mark sensitive fields in a Serializable class as transient to prevent serialization.
B.Use Scanner instead of BufferedReader when reading untrusted input.
C.Always use BufferedReader for reading text files to improve performance.
D.Use try-with-resources for any stream, reader, or writer to ensure automatic closure.
E.Grant FilePermission in the security policy to restrict file access for untrusted code.
AnswersA, D

Prevents sensitive data from being exposed in serialized streams, reducing the risk of data leakage.

Why this answer

Marking sensitive fields as transient prevents them from being serialized, which mitigates the risk of exposing confidential data through serialization streams. This is a secure coding practice that directly addresses unauthorized access to sensitive information during I/O operations.

Exam trap

Oracle Java 17 exams often test the distinction between performance optimizations and security practices, so candidates may incorrectly select 'Always use BufferedReader' or 'Grant FilePermission' as security measures when they are actually about performance or access control misconfiguration.

348
MCQeasy

Which of the following is a checked exception in Java?

A.NullPointerException
B.ArithmeticException
C.IOException
D.IllegalArgumentException
AnswerC

Checked exception, must be handled or declared.

Why this answer

IOException is a checked exception in Java. Checked exceptions are subclasses of Exception (excluding RuntimeException and its subclasses), and the compiler enforces that they are either caught or declared in the method's throws clause. IOException directly extends Exception, making it a checked exception that must be handled at compile time.

Exam trap

The trap here is that candidates often confuse any exception that occurs at runtime with a 'checked exception', forgetting that only subclasses of Exception that are not subclasses of RuntimeException are checked, so they incorrectly select NullPointerException or ArithmeticException.

How to eliminate wrong answers

Option A is wrong because NullPointerException extends RuntimeException, making it an unchecked exception; the compiler does not require it to be caught or declared. Option B is wrong because ArithmeticException also extends RuntimeException, so it is an unchecked exception that can occur at runtime without mandatory handling. Option D is wrong because IllegalArgumentException extends RuntimeException, thus it is an unchecked exception and does not need to be declared or caught.

349
Multi-Selectmedium

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

Select 2 answers
A.Case values can be variables that are not final.
B.It can be used with String objects.
C.It requires a default case.
D.It can be used as an expression that yields a value.
E.Each case must have a unique code block.
AnswersB, D

String is allowed in switch since Java 7.

Why this answer

Java's switch statement supports String objects since Java 7, allowing comparison based on the string's hashCode() and equals() methods. Option D is correct because switch can be used as an expression (e.g., with the arrow syntax) that yields a value, which can be assigned to a variable or returned.

Exam trap

Oracle often tests the misconception that case values can be any variable, but the trap here is that they must be compile-time constants (final or literals), and that switch expressions require exhaustiveness, not a default case.

350
Matchingmedium

Match each annotation to its retention policy.

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

Concepts
Matches

SOURCE

RUNTIME

SOURCE

RUNTIME

RUNTIME

Why these pairings

Retention policies determine how long annotations are retained: SOURCE (discarded by compiler), CLASS (retained in class file but not at runtime), RUNTIME (retained at runtime via reflection). @Override and @SuppressWarnings are SOURCE because they are only used by the compiler. @Deprecated and @FunctionalInterface are RUNTIME because they are accessed via reflection.

351
MCQmedium

A developer is implementing a batch processing application that reads records from a list and processes them. The method uses a for loop with an index variable. Inside the loop, if a record is null, the developer wants to skip that iteration and continue with the next index. The developer writes: for (int i = 0; i < records.size(); i++) { if (records.get(i) == null) continue; process(records.get(i)); updateCounter(); } However, the counter is not updated correctly. The developer expects the counter to reflect the number of processed (non-null) records. What is the problem?

A.The continue statement is only valid inside a while loop.
B.The continue statement should be replaced with a break.
C.The continue statement skips the rest of the loop body, including the counter update.
D.The counter variable should be declared as volatile.
AnswerC

continue causes the loop to proceed to the next iteration, skipping subsequent statements.

Why this answer

The `continue` statement immediately jumps to the next iteration of the loop, skipping any remaining code in the current iteration. In this case, `updateCounter()` is placed after the `continue` in the loop body, so when a null record is encountered, the counter update is never executed, causing the counter to not reflect the number of processed (non-null) records.

Exam trap

The trap here is that candidates may think `continue` only affects the current iteration's processing but forget that it also skips all subsequent statements in the loop body, including counter updates, leading them to choose options like A or D instead of recognizing the control flow issue.

How to eliminate wrong answers

Option A is wrong because `continue` is valid inside `for`, `while`, and `do-while` loops in Java, not just `while` loops. Option B is wrong because `break` would exit the loop entirely, stopping all processing, which is not the intended behavior (the developer wants to skip only the null record and continue with the next index). Option D is wrong because the `volatile` keyword ensures visibility of variable changes across threads, but this is a single-threaded batch processing application, and the counter update issue is purely about control flow, not concurrency.

352
MCQhard

An application uses `--add-opens java.base/java.lang=ALL-UNNAMED` to allow reflective access to `java.lang` internals from the classpath. After migrating to a module, the flag is changed to `--add-opens java.base/java.lang=com.example.app`. Yet reflective access still fails with `InaccessibleObjectException`. What is the most likely reason?

A.The class performing reflection is in an unnamed module.
B.The module does not read the module java.base.
C.The module name in --add-opens is misspelled.
D.The reflective call is made from a different module than com.example.app.
AnswerD

--add-opens opens only for the specified target module(s); if the code is in another module, it fails.

Why this answer

`--add-opens` specifies which module's package is opened to which target module. When the flag is changed from `ALL-UNNAMED` to `com.example.app`, only code in the `com.example.app` module is granted reflective access. If the reflective call originates from a different module (e.g., a third-party library or another application module), the `InaccessibleObjectException` will still be thrown because that module is not listed as the target.

Exam trap

The trap here is that candidates assume `--add-opens` with a specific module name opens the package to all modules, when in fact it only opens to the named module, and the reflective caller must belong to that exact module.

How to eliminate wrong answers

Option A is wrong because the class performing reflection is now in a named module (the application was migrated to a module), not an unnamed module; the flag targets `com.example.app`, so if the reflective class were unnamed, the flag would need `ALL-UNNAMED`. Option B is wrong because every module implicitly reads `java.base` (it is the base module), so the module does read `java.base`; the issue is not about reading but about opening packages. Option C is wrong because the question states the flag is changed to `--add-opens java.base/java.lang=com.example.app`, and if it were misspelled, the JVM would typically emit a warning or fail to parse, but the error described is a runtime `InaccessibleObjectException`, not a startup failure; the most likely cause is a module mismatch.

353
Multi-Selecthard

Which TWO statements about lambda expressions are true? (Choose two.) A. A lambda expression can be assigned to a functional interface variable. B. A lambda expression can access final or effectively final local variables. C. A lambda expression can throw any checked exception. D. A lambda expression can be used to create an instance of an abstract class. E. A lambda expression can be used to implement multiple abstract methods.

Select 2 answers
A.A lambda expression can throw any checked exception.
B.A lambda expression can be assigned to a functional interface variable.
C.A lambda expression can access final or effectively final local variables.
D.A lambda expression can be used to implement multiple abstract methods.
E.A lambda expression can be used to create an instance of an abstract class.
AnswersB, C

True: A lambda can be assigned to a functional interface variable because it provides an implementation for the single abstract method.

Why this answer

False: A lambda expression can only throw checked exceptions that are declared in the functional interface's abstract method, not any checked exception. Options B and C are true: a lambda can be assigned to a functional interface variable, and it can access final or effectively final local variables. Option D is false: a lambda can only implement one abstract method (functional interface).

Option E is false: lambdas cannot instantiate abstract classes; they only implement functional interfaces.

Exam trap

The trap is that candidates think lambdas can implement multiple abstract methods or instantiate abstract classes, but they can only implement a single abstract method of a functional interface.

354
Multi-Selecteasy

Which TWO statements about HashMap are true? (Select two.)

Select 2 answers
A.It allows null values.
B.It uses red-black trees for collision resolution.
C.It guarantees insertion order.
D.It allows null keys.
E.It is thread-safe.
AnswersA, D

HashMap allows null values for any key.

Why this answer

HashMap allows null values; you can store null as a value for any key, including null keys. This is explicitly permitted by the HashMap specification, which does not restrict value types.

Exam trap

The trap here is that candidates often confuse HashMap with TreeMap (which does not allow null keys) or with ConcurrentHashMap (which does not allow null keys or values), and may incorrectly assume HashMap is thread-safe because it is widely used in single-threaded contexts.

355
MCQhard

A company's Java 17 application processes large log files and stores word counts. Initially, they used a TreeMap<String, Integer> to maintain sorted word counts. After adding 10 million entries, insertion performance became unacceptably slow. The team switched to a HashMap<String, Integer> for fast insertions, but now they need to produce sorted reports. They are considering two approaches: (1) Keep the HashMap and, when a sorted report is needed, extract all entries into an ArrayList<Map.Entry<String, Integer>> and sort it using Collections.sort with a comparator, or (2) Use a ConcurrentSkipListMap instead. The application is single-threaded, and reports are requested infrequently. What is the best course of action?

A.Use ConcurrentSkipListMap
B.Use LinkedHashMap and convert to sorted list when needed
C.Use HashMap and sort with Collections.sort when needed
D.Revert to TreeMap because it always keeps data sorted
AnswerC

Optimal balance: fast inserts, sorting only on demand.

Why this answer

The application is single-threaded and reports are infrequent, so the overhead of sorting a HashMap's entries only when needed is acceptable and avoids the continuous insertion cost of a TreeMap. HashMap provides O(1) insertions, and sorting an ArrayList of 10 million entries with Collections.sort (which uses TimSort, O(n log n)) is efficient for occasional use, making this the best balance of performance and simplicity.

Exam trap

The trap here is that candidates assume sorted data must always be maintained in a sorted structure, overlooking the performance trade-off between continuous sorting overhead (TreeMap) and on-demand sorting (HashMap) when insertions are frequent and reads are rare.

How to eliminate wrong answers

Option A is wrong because ConcurrentSkipListMap is designed for concurrent access and provides sorted order, but it has higher overhead per insertion (O(log n)) than HashMap, and the application is single-threaded, so its thread-safety features are unnecessary and degrade performance. Option B is wrong because LinkedHashMap maintains insertion order, not sorted order, so converting it to a sorted list still requires a full sort, offering no advantage over HashMap and adding extra memory overhead for the linked list. Option D is wrong because reverting to TreeMap would reintroduce the original performance problem: TreeMap maintains sorted order at all times with O(log n) insertions, which caused unacceptable slowness with 10 million entries, and the requirement is for fast insertions with only occasional sorted reports.

356
MCQmedium

Refer to the exhibit. What is the output? ```java import java.util.stream.IntStream; public class Example { public static void main(String[] args) { int sum = IntStream.rangeClosed(0, 5) .filter(i -> i >= 0) .sum(); System.out.println(sum); } } ```

A.0
B.15
C.10
D.5
AnswerB

Correct.

Why this answer

The stream pipeline starts with `IntStream.rangeClosed(0, 5)` producing the integers 0, 1, 2, 3, 4, 5. The filter passes all these values, and the map is an identity function (or absent). The reduction sums them: 0+1+2+3+4+5 = 15.

Therefore, the output is 15.

Exam trap

The trap here is that candidates often miscount the number of elements produced by `rangeClosed` versus `range`, leading to off-by-one errors in the sum.

How to eliminate wrong answers

Option A is wrong because 0 would only occur if the stream was empty or the identity was used exclusively, but the stream has elements 0 through 5. Option C is wrong because 10 is the sum of 0 through 4 (5 elements) but the stream includes 5 as well, making the sum 15. Option D is wrong because 5 is the count of elements from 0 to 4, not the sum; the sum of 0 through 5 is 15.

357
MCQmedium

Consider: List<Integer> list = new LinkedList<>(); list.add(10); list.add(20); list.add(0,5); System.out.println(list); What is the output?

A.[10,5,20]
B.[5,10,20]
C.[10,20,5]
D.[5,10,20] but with type warning
AnswerB

add(0,5) inserts at the beginning.

Why this answer

The code creates a LinkedList and adds 10, then 20. The third call `list.add(0,5)` inserts 5 at index 0, shifting existing elements to the right. The resulting list is [5,10,20], so option B is correct.

Exam trap

The trap here is that candidates often confuse the `add(index, element)` method with `set(index, element)`, or incorrectly assume that adding at index 0 replaces the first element rather than inserting before it.

How to eliminate wrong answers

Option A is wrong because it suggests the list is [10,5,20], which would result from adding 5 at index 1, not index 0. Option C is wrong because [10,20,5] would result from adding 5 at the end (no index specified) or at index 2, not index 0. Option D is wrong because there is no type warning; the code compiles cleanly with generics, and the output is exactly [5,10,20] without any warning.

358
Multi-Selecteasy

Which two statements about the Stream API are true? (Choose two.)

Select 2 answers
A.The 'reduce()' operation can produce a result of a different type than the stream elements.
B.The 'flatMap()' operation is a terminal operation.
C.The 'findFirst()' operation is a short-circuiting terminal operation.
D.The 'collect()' operation is an intermediate operation.
E.Streams can be reused after a terminal operation.
AnswersA, C

The `reduce()` operation can produce a result of a different type than the stream elements. For example, `stream.reduce(0, (sum, i) -> sum + i, Integer::sum)` reduces an `IntStream` to an `Integer`.

Why this answer

The `reduce()` operation in the Stream API uses a combiner function that can transform the stream elements into an accumulated result of a different type. For example, `stream.reduce(0, (sum, i) -> sum + i, Integer::sum)` returns an `Integer` from an `IntStream`, or you can reduce a `Stream<String>` to a `StringBuilder`. This is explicitly allowed by the `reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)` signature.

Exam trap

Oracle Java certification exams often test the distinction between intermediate and terminal operations. The trap here is that candidates confuse `flatMap()` (intermediate) with a terminal operation or assume `collect()` is intermediate because it doesn't produce a single value like `reduce()`, but it is terminal because it consumes the stream.

359
Drag & Dropmedium

Arrange the steps to use a lambda expression to sort a list of strings by length.

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

Comparator is a functional interface; lambda provides concise implementation. Integer.compare() handles comparison safely.

360
MCQmedium

Refer to the exhibit. Which statement is true about the com.example.app.internal package?

A.It is accessible for deep reflection only by com.example.lib.
B.It is accessible for deep reflection by any module.
C.It is not accessible for reflection at all.
D.It is exported to all modules.
AnswerA

The opens ... to directive grants reflective access to the named module only.

Why this answer

The exhibit shows that `com.example.app.internal` is declared with `opens com.example.app.internal to com.example.lib`. The `opens` directive grants deep reflection (access to private members) at runtime, but only to the specified module `com.example.lib`. Other modules cannot reflectively access this package unless they are explicitly listed.

Exam trap

Oracle often tests the distinction between `exports` (compile-time and runtime access to public types) and `opens` (runtime reflective access, including private members), and the trap here is that candidates confuse `opens` with `exports` or assume `opens` grants access to all modules unless a `to` clause is specified.

How to eliminate wrong answers

Option B is wrong because the `opens` directive restricts deep reflection to only `com.example.lib`, not to any module. Option C is wrong because the package is explicitly opened to `com.example.lib`, so reflection is allowed for that module. Option D is wrong because the package is not exported; it is only opened for reflection, meaning it is not accessible at compile time or via direct code access from other modules.

361
MCQhard

A HashMap uses a mutable object as a key. After adding the key-value pair, the key's fields are changed such that its hashCode changes. Which statement is true?

A.The value can still be retrieved using the modified key
B.The value may not be retrievable using the modified key
C.The entry is automatically moved to the correct bucket
D.An IllegalArgumentException is thrown when modifying the key
AnswerB

Changed hash leads to lookup in wrong bucket.

Why this answer

When a HashMap uses a mutable object as a key and the key's hashCode changes after insertion, the key is stored in the bucket corresponding to its original hash code. The modified key's new hash code will likely map to a different bucket during retrieval, so the value may not be found. Option B is correct because the value may not be retrievable using the modified key, depending on whether the new hash code leads to the same bucket and whether equals() still matches.

Exam trap

The trap here is that candidates assume HashMap automatically handles key mutations or that Java enforces key immutability, but in reality, the contract requires keys to be immutable for correct behavior, and no runtime check is performed.

How to eliminate wrong answers

Option A is wrong because changing the key's hashCode after insertion does not guarantee retrieval; the modified key's new hash code will likely map to a different bucket, so the value may not be found. Option C is wrong because the HashMap does not automatically rehash or move entries when a key's fields change; it only rehashes when the map is resized or when explicitly triggered. Option D is wrong because modifying a mutable key's fields does not throw an IllegalArgumentException; the Java runtime does not enforce immutability of keys at the language level.

362
MCQmedium

A Java application reads configuration from a file using FileInputStream. The application must handle the case where the configuration file is missing by logging a warning and using default values. Which design approach best meets this requirement?

A.Wrap the FileInputStream in a try-with-resources and catch Exception to handle missing file.
B.Use Files.exists() to check file existence before opening the stream, and if absent, log a warning and use defaults.
C.Catch FileNotFoundException inside the try block and set default values.
D.Use File.exists() to check file existence before opening the stream, and if absent, log a warning and use defaults.
AnswerB

Proactive check avoids exception overhead and is clear.

Why this answer

It explicitly checks for file existence using `Files.exists()` before attempting to open the stream, allowing the application to log a warning and fall back to default values without throwing an exception. This approach aligns with the requirement to handle a missing configuration file gracefully, avoiding unnecessary exception handling overhead. The `Files.exists()` method is part of the modern `java.nio.file` API, which is preferred over the legacy `File.exists()` for its better integration with symbolic links and file system operations.

Exam trap

The trap here is that candidates often confuse `File.exists()` (legacy, less reliable) with `Files.exists()` (modern, recommended), and they may incorrectly assume that catching `FileNotFoundException` is the standard way to handle missing files, overlooking the cleaner pre-check approach that avoids exceptions entirely.

How to eliminate wrong answers

Option A is wrong because catching `Exception` is too broad and may mask other unexpected errors (e.g., security or permission issues), and `try-with-resources` alone does not provide a clean way to log a warning and set defaults without throwing an exception. Option C is wrong because catching `FileNotFoundException` inside the try block still requires the stream to be opened, which will throw the exception before any logging or default assignment can occur, and the code structure is awkward. Option D is wrong because `File.exists()` is a legacy method that does not handle symbolic links correctly and is less reliable than `Files.exists()` from the `java.nio.file` package, which is the recommended approach in modern Java.

363
MCQhard

Refer to the exhibit. What is the most direct way to fix the compilation error without changing the access modifier of the field?

A.Change line 14 to System.out.println(emp.getName());
B.Move the main method to another class in the same package.
C.Import the class in the same file and create a subclass.
D.Change line 14 to System.out.println(emp.name); and make the field protected.
AnswerA

Using the public getter method getName() accesses the private field correctly.

Why this answer

The compilation error is caused by attempting to access a private field `name` directly via `emp.name` from a different class. The most direct fix without changing the access modifier is to use the public getter method `getName()`, which provides controlled access to the private field. This adheres to encapsulation principles and resolves the visibility issue.

Exam trap

Oracle often tests the misconception that moving code to the same package or using inheritance can bypass `private` access, but the trap here is that `private` members are strictly class-local and cannot be accessed from any other class, regardless of package or subclass relationship, unless a public accessor method is used.

How to eliminate wrong answers

Option B is wrong because moving the `main` method to another class in the same package does not change the fact that the private field `name` is still inaccessible from outside its own class; private members are not visible to any other class, even within the same package. Option C is wrong because importing the class and creating a subclass does not grant access to a private field; private members are not inherited and cannot be accessed by subclasses. Option D is wrong because it suggests changing the access modifier to `protected` (which is not allowed per the question's constraint) and still uses direct field access `emp.name`, which would only work if the field were `public` or if accessed within the same package or via inheritance; the option incorrectly implies that `protected` alone would fix the issue from a different class without subclassing.

364
MCQmedium

A developer is writing a method that takes a Collection<Integer> and returns a List<Integer> containing the same elements in sorted order. The method should not modify the original collection. The developer tries the following code: public List<Integer> sortCollection(Collection<Integer> col) { return col.stream().sorted().collect(Collectors.toList()); } The code compiles and runs, but the team lead says it is not optimal. What improvement should be made?

A.Use parallelStream() for better performance
B.Use a TreeSet and then convert to List
C.Convert the collection to an ArrayList first, then call Collections.sort() on it
D.Return an unmodifiable list using collect(Collectors.toUnmodifiableList())
AnswerD

Ensures result cannot be modified, good practice for API design.

Why this answer

The current code creates a mutable list via `Collectors.toList()`, but the method contract does not require mutability. Using `Collectors.toUnmodifiableList()` returns an unmodifiable list, which is more memory-efficient and thread-safe, and it aligns with the principle of returning immutable collections when modification is not needed. This improvement does not affect sorting correctness but optimizes the result for immutability.

Exam trap

The trap here is that candidates often focus on performance improvements like parallelism or sorting efficiency, but the actual optimization is about immutability and API design, which is a common subtlety in Java collections questions.

How to eliminate wrong answers

Option A is wrong because `parallelStream()` would introduce overhead for small collections and does not guarantee sorted order without additional synchronization; the current sequential stream is already optimal for sorting. Option B is wrong because using a `TreeSet` would remove duplicate elements (since `TreeSet` is a `Set`), which violates the requirement to preserve all elements from the original collection. Option C is wrong because converting to an `ArrayList` and calling `Collections.sort()` would modify the original collection if the input is already an `ArrayList` (since `Collections.sort()` sorts in place), and it also requires an extra copy step, making it less efficient than the stream-based approach.

365
Multi-Selecteasy

Which TWO of the following will sort a List<String> in natural (ascending) order?

Select 2 answers
A.list.sort(Comparator.naturalOrder());
B.list.sort((a,b) -> b.compareTo(a));
C.Collections.sort(list, Collections.reverseOrder());
D.Collections.sort(list);
E.Arrays.sort(list);
AnswersA, D

Correct: naturalOrder comparator sorts in ascending order.

Why this answer

`Comparator.naturalOrder()` returns a comparator that imposes the natural (ascending) ordering on `String` objects, which is lexicographic order based on Unicode values. The `List.sort()` method accepts this comparator and sorts the list in place, making it a concise and idiomatic way to sort a list in ascending order.

Exam trap

The trap here is that candidates often confuse `Collections.sort(list)` (which sorts in natural order) with `Collections.sort(list, Collections.reverseOrder())` (which sorts in reverse order), and may also mistakenly think `Arrays.sort()` works on a `List` without realizing it requires an array.

366
MCQmedium

What is the output of the code above?

A.18
B.15
C.9
D.27
AnswerA

Correct: (2*3)+(4*3)=6+12=18.

Why this answer

The code creates a stream of lists containing numbers 1 through 9, flatMaps to a single stream of integers, filters for numbers divisible by 3 (leaving 3, 6, 9), and reduces them by summing. The sum is 3+6+9=18, making option A correct.

Exam trap

Oracle often tests the interaction between `flatMap`, `filter`, and `limit` or `skip`, where candidates forget that `limit` truncates the stream after the filter, leading to an incorrect sum based on the first few elements rather than all matching elements.

How to eliminate wrong answers

Option B (15) is wrong because it would result from summing 4+5+6 (the first three numbers after filtering) but incorrectly omitting the 7, 8, 9 or miscalculating the sum. Option C (9) is wrong because it represents the sum of 4+5, or a misunderstanding of the filtering or reduction step. Option D (27) is wrong because it might come from summing 4+5+6+7+8+9 = 39 and then subtracting 12, or from a different incorrect operation like multiplying instead of summing.

367
MCQmedium

Given: TreeSet<Integer> set = new TreeSet<>(List.of(3,1,2)); set.add(2); System.out.println(set); What is the output?

A.[1,2]
B.[1,3,2]
C.[3,1,2]
D.UnsupportedOperationException
E.[1,2,3]
AnswerE

Correct: sorted order, duplicates ignored.

Why this answer

E is correct because TreeSet maintains elements in their natural sorted order (ascending for integers). The list [3,1,2] is sorted to [1,2,3], and adding 2 again has no effect since TreeSet does not allow duplicates. The output is [1,2,3].

Exam trap

The trap here is that candidates often confuse TreeSet with HashSet or List, expecting insertion order or allowing duplicates, but TreeSet enforces sorted order and uniqueness via its underlying tree structure.

How to eliminate wrong answers

Option A is wrong because it omits the element 3, but TreeSet retains all unique elements after sorting. Option B is wrong because it shows [1,3,2], which is not sorted order; TreeSet always sorts elements. Option C is wrong because it shows the original insertion order [3,1,2], but TreeSet does not preserve insertion order.

Option D is wrong because UnsupportedOperationException is not thrown; TreeSet supports add() and duplicates are silently ignored.

368
MCQeasy

Given the code in the exhibit, which of the following is true about this custom exception?

A.It cannot be used with multi-catch because it is unchecked.
B.It is an unchecked exception.
C.It must be caught or declared in the method signature.
D.It must implement the Serializable interface.
AnswerB

Extends RuntimeException.

Why this answer

The custom exception extends RuntimeException, which makes it an unchecked exception. Unchecked exceptions do not require handling or declaration in the method signature, and they can be used in multi-catch blocks.

Exam trap

Oracle often tests the misconception that all custom exceptions must be checked exceptions, but the trap here is that a custom exception extending RuntimeException is unchecked, so it does not require handling or declaration, and it can still be used in multi-catch blocks.

How to eliminate wrong answers

Option A is wrong because unchecked exceptions can be used with multi-catch; multi-catch works with any exception type, checked or unchecked, as long as the types are not in the same inheritance hierarchy. Option C is wrong because unchecked exceptions (subclasses of RuntimeException) do not need to be caught or declared in the method signature; only checked exceptions have that requirement. Option D is wrong because implementing Serializable is not a requirement for custom exceptions; it is optional and only relevant if the exception needs to be serialized (e.g., for remote method invocation).

369
Multi-Selecthard

Which are valid method references in Java 17?

Select 4 answers
A.String::new
B.String::isEmpty
C.null::equals
D.Math::random
E.this::toString
AnswersA, B, D, E

Valid constructor reference, equivalent to () -> new String().

Why this answer

A is a constructor reference, a valid type of method reference. B is a reference to an instance method of an arbitrary object of type String. D is a reference to a static method.

E is a reference to an instance method of the current object, valid in an instance context. C is invalid because null cannot be a qualifier.

Exam trap

A common trap is incorrectly excluding constructor references like String::new, assuming they are not method references. Another trap is considering null::equals valid, but null cannot be a qualifier. Some may incorrectly think this::toString is invalid, but it is valid in an instance context.

370
MCQeasy

What is the output of the following code snippet? int x = 5; if(x > 0) { System.out.print('A'); } else if(x > 2) { System.out.print('B'); } else { System.out.print('C'); }

A.AB
B.C
C.B
D.A
AnswerD

x > 0 is true, so the first branch executes and prints 'A'.

Why this answer

The condition `x > 0` evaluates to true (x = 5), so the code prints 'A' and then exits the entire if-else-if chain. The subsequent `else if` and `else` blocks are skipped entirely, so only 'A' is output.

Exam trap

The trap here is that candidates mistakenly think the `else if` condition is also evaluated or that multiple branches can execute, confusing the if-else-if chain with a series of independent if statements.

How to eliminate wrong answers

Option A is wrong because it suggests both 'A' and 'B' are printed, but once the first `if` condition is true, the rest of the chain is bypassed — no fall-through occurs in if-else-if structures. Option B is wrong because it implies the `else` block executes, which only happens if all preceding conditions are false; here `x > 0` is true, so the `else` is never reached. Option C is wrong because it assumes the `else if` condition `x > 2` is evaluated, but it is skipped entirely when the first `if` is true.

371
MCQmedium

A financial application uses BigDecimal for monetary calculations. Which rounding mode should be used to round to the nearest neighbor, and if both neighbors are equidistant, round to the even neighbor?

A.RoundingMode.HALF_UP
B.RoundingMode.HALF_DOWN
C.RoundingMode.UNNECESSARY
D.RoundingMode.HALF_EVEN
AnswerD

Correct: HALF_EVEN rounds to the nearest neighbor, and if equidistant, to the even neighbor. This is the standard for financial calculations.

Why this answer

RoundingMode.HALF_EVEN rounds to the nearest neighbor, and when both neighbors are equidistant (i.e., the fractional part is exactly 0.5), it rounds to the even neighbor. This is the standard rounding mode for financial calculations to minimize cumulative rounding bias over many operations.

Exam trap

The trap here is that candidates often confuse HALF_EVEN with HALF_UP, assuming 'nearest neighbor' always means rounding up at 0.5, but the exam specifically tests the 'round to even' rule for equidistant cases.

How to eliminate wrong answers

Option A is wrong because RoundingMode.HALF_UP rounds to the nearest neighbor but always rounds up when equidistant (e.g., 2.5 rounds to 3), which introduces a systematic upward bias. Option B is wrong because RoundingMode.HALF_DOWN rounds to the nearest neighbor but always rounds down when equidistant (e.g., 2.5 rounds to 2), introducing a systematic downward bias. Option C is wrong because RoundingMode.UNNECESSARY throws an ArithmeticException if rounding is required (i.e., if the result has a non-terminating decimal), so it cannot be used when rounding is needed.

372
MCQmedium

A developer needs to sort a List of Employee objects by salary (double) in descending order. Which approach is correct and efficient?

A.Collections.sort(list, Collections.reverseOrder());
B.list.stream().sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary())).collect(Collectors.toList());
C.Collections.sort(list, (e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary()));
D.Collections.sort(list);
AnswerC

Uses Comparator with descending order via Double.compare.

Why this answer

It uses `Collections.sort()` with a custom `Comparator` that performs an in-place sort of the original list, which is both efficient (no new list created) and correctly orders by salary descending via `Double.compare(e2.getSalary(), e1.getSalary())`. This avoids the overhead of stream pipeline creation and collection, and directly mutates the list as required.

Exam trap

The trap here is that candidates often choose the stream-based approach (Option B) thinking it is more modern or functional, but the exam tests understanding that `Collections.sort()` with a custom comparator is the correct and efficient way to sort a mutable list in-place, while streams create a new collection and are less efficient for this specific requirement.

How to eliminate wrong answers

Option A is wrong because `Collections.reverseOrder()` reverses the natural ordering of `Employee` objects, but `Employee` does not implement `Comparable` (or its natural ordering is not by salary), so this will cause a compilation error or use an unintended ordering. Option B is wrong because it creates a new sorted list via a stream and `collect(Collectors.toList())`, which is less efficient than an in-place sort and does not modify the original list as the question implies. Option D is wrong because `Collections.sort(list)` uses the natural ordering of `Employee` (via `Comparable`), which is not defined for salary descending, and will likely result in a compile-time error if `Employee` does not implement `Comparable`.

373
MCQeasy

Given: String[] array = {"A", "B"}; List<String> list = Arrays.asList(array); list.set(0, "C"); array[1] = "D"; What is the content of the list?

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

Both modifications affect the list.

Why this answer

`Arrays.asList()` returns a fixed-size list backed by the original array. Modifications to the list via `set()` directly affect the backing array, and modifications to the array elements are reflected in the list. After `list.set(0, "C")`, the first element of both the list and the array becomes "C".

After `array[1] = "D"`, the second element of both becomes "D". Thus the list content is [C, D].

Exam trap

The trap here is that candidates often forget that `Arrays.asList()` returns a list backed by the original array, so modifications through either reference are reflected in both, leading them to choose options that reflect only one of the two changes.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes only the array modification affects the list, ignoring the `list.set(0, "C")` operation. Option C is wrong because it assumes the list remains unchanged, failing to recognize that both `set()` and direct array assignment modify the shared backing structure. Option D is wrong because it reflects only the `set()` operation but ignores the effect of `array[1] = "D"`, which also updates the list.

374
MCQhard

Given: outer: for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { if(j==1) continue outer; } } How many times does the innermost loop body execute?

A.3
B.0
C.9
D.6
AnswerA

Correct: only j=0 runs for each i, so 3 times.

Why this answer

The outer loop runs with i=0,1,2. For each i, the inner loop starts j=0, executes the body once, then j=1 triggers 'continue outer', which skips the rest of the inner loop and increments i. Thus the inner loop body executes exactly once per outer iteration, for a total of 3 times.

Exam trap

The trap here is that candidates often forget the inner loop body executes for j=0 before the continue, leading them to think it never runs or runs all 9 times.

How to eliminate wrong answers

Option B is wrong because the inner loop body does execute — it runs for j=0 before the continue is encountered. Option C is wrong because the continue outer prevents the inner loop from completing all 9 iterations; only 3 iterations occur. Option D is wrong because the inner loop does not execute 6 times; the continue outer resets to the outer loop after j=1, so only j=0 runs each time.

Page 4

Page 5 of 7

Page 6

All pages