Courseiva

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

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

Page 1

Page 2 of 7

Page 3
76
MCQhard

Given an exception chain where a custom exception is created with a cause, which method is used to set the cause after construction?

A.The cause can only be set via constructor.
B.setCause(Throwable)
C.addSuppressed(Throwable)
D.initCause(Throwable)
AnswerD

Allows setting the cause after construction.

Why this answer

`initCause(Throwable)` is the method provided by the `Throwable` class to set the cause of an exception after the exception has been constructed. This is useful when the exception must be created without a cause (e.g., via a no-arg constructor) and the cause is determined later. The cause can only be set once; a second call will throw an `IllegalStateException`.

Exam trap

The trap here is that candidates confuse `initCause(Throwable)` with `addSuppressed(Throwable)`, or assume the cause can only be set via constructor, missing the post-construction capability that `initCause` provides.

How to eliminate wrong answers

Option A is wrong because the cause can be set both via a constructor (e.g., `Throwable(String message, Throwable cause)`) and after construction using `initCause(Throwable)`. Option B is wrong because there is no method named `setCause(Throwable)` in the `Throwable` class or any standard Java exception class; the correct method is `initCause(Throwable)`. Option C is wrong because `addSuppressed(Throwable)` is used to add suppressed exceptions (typically in try-with-resources) and does not set the causal chain; it adds exceptions that were suppressed, not the root cause.

77
MCQhard

Given the stack trace, which statement is true about the exception handling?

A.Both exceptions are checked, and the code must handle both.
B.The RuntimeException is caused by a checked exception, so it must be declared in the throws clause.
C.The SQLException is a checked exception, and the code must handle it or declare it.
D.The RuntimeException is an unchecked exception, so it cannot be caught.
AnswerC

SQLException is checked and must be handled or declared.

Why this answer

SQLException is a checked exception (a subclass of Exception but not RuntimeException), so the Java compiler enforces that it must be either caught in a try-catch block or declared in the throws clause of the enclosing method. The stack trace indicates that an SQLException occurred, and the code must handle this checked exception to compile successfully.

Exam trap

The trap here is that candidates often confuse the 'must handle or declare' rule for checked exceptions with the idea that unchecked exceptions cannot be caught at all, leading them to incorrectly select Option D.

How to eliminate wrong answers

Option A is wrong because not both exceptions are checked; RuntimeException is an unchecked exception, so the code does not have to handle it. Option B is wrong because a RuntimeException caused by a checked exception does not require the RuntimeException to be declared in the throws clause; only the checked exception itself must be handled or declared. Option D is wrong because RuntimeException, though unchecked, can still be caught; the statement that it 'cannot be caught' is false.

78
Drag & Dropmedium

Order the steps to properly handle resources using try-with-resources in Java.

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

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

try-with-resources ensures each resource is closed at the end of the statement. Resources are closed in the opposite order they were created.

79
Multi-Selecthard

Which THREE statements about the SecurityManager and security policies in Java 17 are true? (Choose three.)

Select 3 answers
A.System.setProperty("java.security.policy", "policy.url") loads a new policy.
B.The SecurityManager class is deprecated in Java 17.
C.By default, Java 17 applications run with a SecurityManager installed.
D.A security policy file can contain grant entries for code sources.
E.AccessController.doPrivileged() allows code to temporarily escalate privileges.
AnswersB, D, E

Deprecated since Java 18? Actually Java 17 already marks it deprecated.

Why this answer

The SecurityManager class is deprecated for removal in Java 17 (JEP 411). This deprecation means that while the class still exists for compatibility, it is no longer recommended for use and may be removed in a future release. The core reasoning is that the SecurityManager architecture is considered legacy and difficult to maintain, so Oracle has deprecated it to encourage developers to adopt alternative security mechanisms.

Exam trap

The trap here is that candidates often confuse setting a system property with actually loading a policy, and they assume the SecurityManager is active by default in modern Java versions, when in fact it is deprecated and disabled by default since Java 17.

80
Multi-Selecthard

Which TWO statements about the Stream API are correct? (Choose two.) A. A stream can be traversed multiple times. B. The peek() method is an intermediate operation. C. The findFirst() method returns an Optional. D. The collect() method is an intermediate operation. E. The map() method returns a stream of the same type.

Select 2 answers
A.A stream can be traversed multiple times.
B.The peek() method is an intermediate operation.
C.The findFirst() method returns an Optional.
D.The collect() method is an intermediate operation.
E.The map() method returns a stream of the same type.
AnswersB, C

This statement is true. peek() is an intermediate operation that returns the same stream elements after performing an action.

Why this answer

The correct statements are B and C. Option B is correct because peek() is an intermediate operation that allows performing an action on each element without modifying the stream. Option C is correct because findFirst() returns an Optional describing the first element, or an empty Optional if the stream is empty.

Option A is incorrect because a stream can only be consumed once; it cannot be traversed multiple times. Option D is incorrect because collect() is a terminal operation, not an intermediate operation. Option E is incorrect because map() can change the element type; for example, mapping a Stream<String> to Stream<Integer> is common.

Exam trap

The main trap in this question is confusing intermediate and terminal operations. Candidates often mistake collect() as intermediate or think that peek() is terminal. Another trap is assuming streams can be reused, but they are single-use only.

81
Multi-Selectmedium

Which TWO statements about method references are true? (Choose two.)

Select 2 answers
A.Constructor references use the syntax Class::new.
B.Array constructor references are not supported.
C.Instance method references always use the keyword static.
D.A method reference can be used in place of a lambda expression of compatible functional interface.
E.Method references cannot refer to methods declared in the same class.
AnswersA, D

Constructor references follow ClassName::new syntax.

Why this answer

Constructor references use the syntax `Class::new` to refer to a constructor of a class, which can be used with a functional interface whose method matches the constructor's signature. This allows creating instances without explicitly invoking `new`, leveraging the same target type inference as lambda expressions.

Exam trap

The trap here is that candidates often confuse instance method references with static method references, mistakenly thinking the `static` keyword is required, or they overlook that array constructor references are indeed supported via `Type[]::new`.

82
Matchingmedium

Match each functional interface to its abstract method signature.

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

Concepts
Matches

T get()

void accept(T t)

R apply(T t)

boolean test(T t)

T apply(T t)

Why these pairings

The correct matches are Predicate -> boolean test(T), Consumer -> void accept(T), Supplier -> T get(). Common confusions involve swapping method signatures between interfaces.

83
MCQmedium

Given: int x=1; switch(x) { case 1: System.out.print("A"); case 2: System.out.print("B"); break; default: System.out.print("C"); } What is printed?

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

Correct: prints A then B due to fall-through.

Why this answer

The switch statement does not have a break after case 1, so execution falls through to case 2 after printing 'A'. Case 2 prints 'B' and then hits the break, exiting the switch. The default case is skipped because a matching case was found.

Thus, 'AB' is printed.

Exam trap

The trap here is that candidates forget that without a break, execution falls through to the next case, so they incorrectly assume only the matching case executes.

How to eliminate wrong answers

Option A is wrong because the default case is only executed if no matching case is found, but here case 1 matches, so 'C' is not printed. Option B is wrong because the break after case 2 prevents fall-through to the default, so 'C' is not printed. Option D is wrong because it ignores the fall-through from case 1 to case 2, which causes 'B' to be printed as well.

84
MCQmedium

A company needs to process a stream of orders and filter out orders that are not in the 'SHIPPED' status. Then they want to collect the order IDs into a list. Which of the following correctly uses lambda expressions to achieve this?

A.orders.stream().filter(o -> o.getStatus() != "SHIPPED").map(Order::getId).collect(Collectors.toList())
B.orders.stream().map(Order::getId).filter(id -> id.equals("SHIPPED")).collect(Collectors.toList())
C.orders.stream().filter(Order::getStatus).map(o -> o.getId()).collect(Collectors.toList())
D.orders.stream().filter(o -> o.getStatus().equals("SHIPPED")).map(Order::getId).collect(Collectors.toList())
AnswerD

Correctly filters SHIPPED orders and maps to IDs.

Why this answer

It first filters the stream to include only orders with status 'SHIPPED' using a lambda expression that calls equals() on the status string, then maps each order to its ID using a method reference, and finally collects the IDs into a list. This correctly uses lambda expressions and the Stream API to achieve the requirement.

Exam trap

Oracle often tests the distinction between using equals() vs == for string comparison in lambda expressions, and the correct order of stream operations (filter before map) to avoid type mismatches or logical errors.

How to eliminate wrong answers

Option A is wrong because it filters orders where the status is NOT equal to 'SHIPPED' (using !=), which is the opposite of what is required. Option B is wrong because it maps orders to IDs first, then tries to filter IDs by comparing them to the string 'SHIPPED', which is a type mismatch and logically incorrect. Option C is wrong because it uses a method reference Order::getStatus as a predicate, but getStatus returns a String, not a boolean, so it does not compile or work as a filter.

85
Multi-Selectmedium

Which THREE of the following are valid ways to create a Stream<String>? (Choose three.)

Select 3 answers
A.Arrays.stream(new String[]{"a", "b"})
B.Stream.of("a", "b")
C.List.of("a", "b").stream()
D."ab".chars()
E.new Stream<String>()
AnswersA, B, C

Arrays.stream for object arrays returns a Stream of the array elements.

Why this answer

`Arrays.stream(T[])` returns a `Stream<T>` from an array. Passing `new String[]{"a", "b"}` creates a `Stream<String>` directly, as the method is overloaded for object arrays.

Exam trap

The trap here is that candidates often confuse `chars()` as returning a `Stream<Character>` or `Stream<String>`, when in fact it returns an `IntStream` of code points, and they may also mistakenly think `Stream` can be instantiated with `new` like a regular class.

86
MCQeasy

Which is the best practice for securing a Java application that reads sensitive configuration files?

A.Restrict access to the file using operating system permissions.
B.Define a Java security policy file with FilePermission for the configuration file.
C.Make the file read-only at the OS level.
D.Store credentials in the source code and use encryption.
AnswerA

Correct. Restricting access via OS permissions is a standard, platform-independent best practice that does not rely on deprecated Java features.

Why this answer

Restricting access to sensitive files using operating system permissions is a fundamental security practice that applies regardless of the Java version. In Java 17, the Security Manager is deprecated for removal (JEP 411), so relying on a Java security policy file (Option B) is no longer considered a best practice. OS-level permissions provide a robust, platform-native access control that does not depend on deprecated features.

Options C and D are insufficient: making a file read-only does not prevent unauthorized access, and storing credentials in source code is highly insecure.

Exam trap

Candidates may think that using Java's Security Manager with a policy file is the best practice, but in Java 17 it is deprecated. The correct modern approach is to rely on OS-level permissions.

How to eliminate wrong answers

Option A is wrong because OS permissions are external to the JVM and can be bypassed if the application runs with the same user account that owns the file, or if the OS is compromised; they do not provide Java-level access control. Option C is wrong because making a file read-only at the OS level prevents writing but does not prevent reading, which is the primary concern for sensitive configuration files; it also does not restrict access from unauthorized Java code. Option D is wrong because storing credentials in source code is a severe security anti-pattern—it exposes secrets in version control and to anyone with code access—and encryption alone does not control who can decrypt or access the data at runtime.

87
MCQeasy

In a try-finally block, what happens to a return statement inside the finally block?

A.The return in the finally block is executed, and the try block return is ignored.
B.The finally block is skipped if there is a return in try.
C.The return in the try block takes precedence.
D.If the try block throws an exception, the finally block's return is skipped.
AnswerA

Correct. The finally block's return is executed and its value is returned, ignoring any prior return in try.

Why this answer

In a try-finally block, the finally block is always executed. If the finally block contains a return statement, that return value overrides any return value from the try block. Therefore, option A is correct.

Option B is incorrect because the finally block always executes regardless of a return in try. Option C is incorrect because the finally return overrides the try return. Option D is incorrect because a return in finally is executed even if an exception occurs, overriding the exception.

Exam trap

Candidates often assume the finally block only runs for cleanup and cannot affect the return value, but the Java Language Specification explicitly allows a return in finally to override any prior return. Be careful with exception overriding: while it's true that a return in finally can suppress an exception, this question focuses strictly on the return statement's effect on return values.

How to eliminate wrong answers

Option B is wrong because the finally block is never skipped when a return is in the try block; the Java Language Specification guarantees that the finally block executes after the try block completes, regardless of control flow statements like return. Option C is wrong because the return in the try block does not take precedence; the finally block's return executes after the try block's return is evaluated but before the method actually returns, so the finally return value is what the caller receives.

88
MCQmedium

A developer needs to read a very large text file (over 1 GB) efficiently with minimal memory overhead. Which approach is most suitable?

A.Use Scanner to read tokens.
B.Use BufferedReader to read lines.
C.Use FileInputStream and read byte by byte.
D.Use FileChannel with a ByteBuffer to read in chunks.
AnswerD

FileChannel with ByteBuffer allows efficient chunked reading, minimizing memory usage.

Why this answer

FileChannel with a ByteBuffer allows reading a large file in configurable chunks, leveraging the operating system's native I/O for high throughput and minimal memory overhead. This approach avoids loading the entire file into memory and reduces context switching compared to stream-based readers.

Exam trap

The trap here is that candidates often choose BufferedReader for its simplicity, not realizing that reading lines from a multi-GB file still requires holding entire lines in memory, which can cause OutOfMemoryError or severe performance degradation.

How to eliminate wrong answers

Option A is wrong because Scanner is designed for parsing tokens with delimiters and has high memory overhead due to internal buffering and regex processing, making it inefficient for large files. Option B is wrong because BufferedReader reads lines into memory, which for a 1 GB file would require storing entire lines (potentially huge) and causes significant memory pressure. Option C is wrong because reading byte by byte with FileInputStream incurs excessive system calls and overhead, resulting in abysmal performance for large files.

89
MCQhard

Given the output of `java --list-modules` from a Java 17 installation, which module is NOT included by default when using the `--release 17` flag with `javac`?

A.jdk.jfr
B.jdk.incubator.foreign
C.java.net.http
D.java.sql
AnswerB

Correct: Incubator modules are not included when using --release.

Why this answer

The `--release 17` flag restricts `javac` to the standard Java SE 17 API, which does not include incubator modules like `jdk.incubator.foreign`. Incubator modules are preview features that are not part of the Java SE specification and must be explicitly added with `--add-modules`.

Exam trap

Oracle often tests the distinction between standard modules (always included with `--release`) and incubator/preview modules (explicitly opt-in), causing candidates to assume all listed modules are part of the default API.

How to eliminate wrong answers

Option A is wrong because `jdk.jfr` (Java Flight Recorder) is a standard JDK module included in Java SE 17 and is part of the default API when using `--release 17`. Option C is wrong because `java.net.http` (HTTP Client) is a standard module introduced in Java 11 and is included in the Java SE 17 API. Option D is wrong because `java.sql` (JDBC API) is a core Java SE module that has been part of the standard API since Java 8 and is included by default with `--release 17`.

90
MCQeasy

Which functional interface is most appropriate for a lambda that takes a String and returns nothing?

A.Predicate<String>
B.Function<String, Void>
C.Supplier<String>
D.Consumer<String>
AnswerD

Consumer<String> accepts a String and returns void, best suited for side-effect operations.

Why this answer

A lambda that takes a String and returns nothing matches the `Consumer<String>` functional interface, which has a single abstract method `void accept(String t)`. `Consumer` is designed for operations that consume an input and produce no output, such as printing or logging the string.

Exam trap

The trap here is that candidates mistakenly choose `Function<String, Void>` thinking `Void` represents 'nothing', but `Void` is a class that requires a return value of `null`, making it unsuitable for a lambda that truly returns nothing.

How to eliminate wrong answers

Option A is wrong because `Predicate<String>` returns a `boolean`, not nothing. Option B is wrong because `Function<String, Void>` returns a `Void` object (which requires a return statement with `null`), not nothing; the lambda would need to explicitly return `null`. Option C is wrong because `Supplier<String>` takes no arguments and returns a `String`, the opposite of the required signature.

91
Multi-Selecthard

Which TWO statements about the java.util.Collections class are true?

Select 2 answers
A.Collections.sort(List) returns a new sorted list.
B.Collections.reverse(List) returns a new reversed list.
C.Collections.shuffle(List) returns a new shuffled list.
D.Collections.synchronizedList(List) returns a synchronized list backed by the specified list.
E.Collections.unmodifiableList(List) returns an unmodifiable view of the specified list.
AnswersD, E

It returns a thread-safe list backed by the specified list.

Why this answer

Collections.synchronizedList(List) returns a synchronized (thread-safe) list backed by the specified list. This method wraps the provided list in a synchronized wrapper, ensuring that all access to the underlying list is serialized when accessed through the returned list. It does not create a new independent list but provides a view that synchronizes all method calls.

Exam trap

The trap here is that candidates often confuse mutating methods like sort, reverse, and shuffle with methods that return new collections, when in fact these methods modify the list in place and return void, whereas synchronizedList and unmodifiableList return wrapper views.

92
Multi-Selecteasy

Which two of the following statements are true about the continue statement in a loop?

Select 2 answers
A.continue can be used in a while loop.
B.continue cannot be used in a do-while loop.
C.continue can be used in a for loop.
D.continue can be used in a switch statement.
E.continue can be used in a try block without a loop.
AnswersA, C

continue is valid in a while loop to skip the current iteration.

Why this answer

The continue statement can be used in any loop construct in Java, including while loops. When executed, continue skips the remaining body of the loop for the current iteration and proceeds to the next iteration's condition check.

Exam trap

The trap here is that candidates often confuse continue with break, or mistakenly think continue is restricted to for loops only, when in fact it works in all loop types (while, do-while, for) but not in switch or standalone try blocks.

93
MCQmedium

A method receives a List<String> and needs to transform it to a Map where the key is the first three characters of each string and the value is the string itself. If two strings have the same prefix, the later one should override the earlier. Which collector achieves this?

A.Collectors.groupingBy(s -> s.substring(0,3))
B.Collectors.toMap(s -> s.substring(0,3), Function.identity())
C.Collectors.toConcurrentMap(s -> s.substring(0,3), Function.identity())
D.Collectors.toMap(s -> s.substring(0,3), Function.identity(), (a,b) -> b)
AnswerD

Correct: The merge function (a,b) -> b keeps the later value.

Why this answer

`Collectors.toMap` with a merge function `(a, b) -> b` ensures that when duplicate keys (first three characters) occur, the later string in the stream order replaces the earlier one. The merge function is invoked on key collision, and returning `b` (the second argument) keeps the later value, satisfying the requirement.

Exam trap

The trap here is that candidates often pick `toMap` without a merge function (Option B) or `groupingBy` (Option A), forgetting that duplicate keys cause exceptions or produce the wrong map type, respectively.

How to eliminate wrong answers

Option A is wrong because `groupingBy` groups all strings with the same prefix into a `List<String>`, not a single string per key, so the result is `Map<String, List<String>>` instead of `Map<String, String>`. Option B is wrong because `toMap` without a merge function throws `IllegalStateException` when duplicate keys are encountered, which will happen if any two strings share the same first three characters. Option C is wrong because `toConcurrentMap` also requires a merge function for duplicate keys and will throw an exception without one; additionally, it is designed for parallel streams and is not necessary for this sequential requirement.

94
MCQhard

A developer implements a reduction using reduce() to concatenate strings from a stream. The code: Optional<String> result = stream.reduce((s1, s2) -> s1.concat(s2)); The operation works but the developer is concerned about performance with large streams. Which change would most likely improve performance?

A.Use StringBuffer with collect() instead.
B.Use a sequential stream.
C.Use parallelStream with reduce.
D.Use reduce with identity "".
AnswerA

StringBuilder (or StringBuffer) as a mutable reduction with collect() reduces intermediate allocations.

Why this answer

`StringBuffer` is mutable and thread-safe, making it efficient for accumulating strings in a parallel or sequential stream via `collect()`. The `reduce()` operation with `concat()` creates a new `String` object for each pair, leading to O(n) string copying and quadratic time complexity. Using `collect()` with `StringBuffer` avoids this overhead by reusing a mutable buffer.

Exam trap

The trap here is that candidates assume `reduce()` with an identity or parallel streams will fix performance, but the core issue is the immutable nature of `String` concatenation, which `collect()` with a mutable container like `StringBuffer` or `StringBuilder` resolves.

How to eliminate wrong answers

Option B is wrong because using a sequential stream does not address the fundamental inefficiency of `reduce()` with `concat()`, which still creates many intermediate `String` objects. Option C is wrong because `parallelStream` with `reduce()` would introduce thread-safety issues and still suffer from string copying overhead, potentially degrading performance further. Option D is wrong because providing an identity `""` to `reduce()` does not change the underlying concatenation mechanism; it still creates new `String` objects per reduction step.

95
MCQeasy

Refer to the exhibit. What is the purpose of this code?

A.Compress data.txt and write to data.enc
B.Encrypt data.txt and write to data.enc
C.Encrypt data.enc and write to data.txt
D.Decrypt data.txt and write to data.enc
AnswerB

The cipher is in encrypt mode, and data from data.txt is written to data.enc via CipherOutputStream.

Why this answer

The code uses a CipherOutputStream with a cipher initialized in ENCRYPT_MODE, reading from data.txt and writing to data.enc, thus encrypting the plaintext file and producing an encrypted output file. This is the standard pattern for file encryption in Java using the JCA (Java Cryptography Architecture).

Exam trap

Oracle often tests the distinction between encryption and compression, and the direction of the cipher mode (ENCRYPT vs DECRYPT) relative to the input/output file names, leading candidates to confuse the source and destination or the operation type.

How to eliminate wrong answers

Option A is wrong because compression is not performed; the code uses a Cipher, not a compression algorithm like GZIPOutputStream. Option C is wrong because the input is data.txt and output is data.enc, not the reverse; the cipher is in ENCRYPT_MODE, not DECRYPT_MODE. Option D is wrong because the cipher is in ENCRYPT_MODE, not DECRYPT_MODE, so it cannot decrypt; also the input/output mapping is reversed for decryption.

96
MCQmedium

Refer to the exhibit. What is the output when the program is executed?

A.0 0 0 1 0 2 1 0 1 1 1 2
B.0 0 0 1 0 2 1 0 1 1 2 0 2 1 2 2
C.0 0 0 1 0 2 1 0 1 1
D.0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2
AnswerC

Correct output: prints all pairs until (1,2) triggers the break.

Why this answer

The code uses nested for loops with break labels. The outer loop iterates i from 0 to 2, and the inner loop iterates j from 0 to 2. When i == 1 and j == 1, the break outer; statement exits both loops, so after printing 0 0, 0 1, 0 2, 1 0, 1 1, the program terminates.

This matches option C.

Exam trap

Oracle OCP Java 17 often tests the distinction between a simple break (which exits only the innermost loop) and a labeled break (which exits the specified outer loop), causing candidates to mistakenly assume the inner loop continues or the outer loop resumes.

How to eliminate wrong answers

Option A is wrong because it includes 1 2 after the break, which would require the inner loop to continue after j==1, but the break outer; exits both loops immediately. Option B is wrong because it continues printing after the break, including 2 0, 2 1, 2 2, which would only happen if the break were not executed or if it were a simple break (not labeled). Option D is wrong because it includes 1 2 and all iterations of i==2, which would require the outer loop to continue after the break, but the labeled break terminates the outer loop entirely.

97
MCQeasy

A development team is working on a Java 17 application that must be packaged as a custom runtime image for deployment on a Linux server without a JDK installed. The application uses `java.base`, `java.logging`, and `java.sql` modules, and also requires the `jdk.crypto.cryptoki` module for hardware security module (HSM) integration. The team wants to minimize the image size while ensuring all necessary modules are included. They run `jlink --add-modules java.base,java.logging,java.sql,jdk.crypto.cryptoki --output myapp-runtime`. The resulting image runs the application but fails at startup with a `ClassNotFoundException` for `javax.crypto.spec.SecretKeySpec`. Which action should the team take to resolve the issue?

A.Manually add the `java.security.jgss` module to the `--add-modules` list.
B.Use the `--list-modules` option with jlink to verify which modules are included, then add any missing ones.
C.Add `ALL-MODULE-PATH` to the `--add-modules` list to include all available modules.
D.Add `--bind-services` to the jlink command to include service provider modules.
AnswerD

Correct: --bind-services links service provider modules required by the specified modules, which may include necessary crypto implementations.

Why this answer

The `jdk.crypto.cryptoki` module is a service provider module that provides cryptographic services via the Java Cryptography Architecture (JCA). When using `jlink`, service provider modules are not automatically included unless `--bind-services` is specified, because `jlink` only includes modules directly referenced in the module graph. The `javax.crypto.spec.SecretKeySpec` class is part of `java.base`, but the actual provider implementation that makes it available at runtime is in `jdk.crypto.cryptoki`; without `--bind-services`, the service linkage is missing, causing the `ClassNotFoundException`.

Exam trap

The trap here is that candidates assume adding the module name to `--add-modules` is sufficient, but they overlook that `jlink` requires `--bind-services` to include service provider modules that are discovered via the service loader mechanism.

How to eliminate wrong answers

Option A is wrong because `java.security.jgss` is unrelated to the missing `javax.crypto.spec.SecretKeySpec`; that class is in `java.base`, and the issue is about service provider resolution, not a missing module dependency. Option B is wrong because `--list-modules` only shows which modules are currently included; it does not fix the missing service provider linkage, and the team already knows the module is included. Option C is wrong because `ALL-MODULE-PATH` would include every module on the module path, defeating the purpose of minimizing image size and potentially including unnecessary modules; it also does not address the service binding issue.

98
MCQmedium

What is the output? ```java int x = 10; do { System.out.print(x); } while (x-- > 10); ```

A.9
B.15
C.10
D.6
AnswerC

This is correct because the missing code outputs 10 as the first and only value.

Why this answer

10 because in the missing code, the loop condition likely uses pre-decrement or the print statement occurs before the decrement, so the first value printed is the initial value of x, which is 10. The post-decrement trap described in the current explanation does not apply.

Exam trap

The trap here is that candidates often forget that the post-decrement operator uses the original value in the condition before decrementing, leading them to think the first printed value is 10 instead of 9.

How to eliminate wrong answers

Option B (15) is wrong because it assumes the loop runs 15 times or that x is incremented, but the loop decrements x from 10 to 1, printing each value once. Option C (10) is wrong because it ignores the post-decrement operator; the condition checks x before decrementing, so the first printed value is 9, not 10. Option D (6) is wrong because it might result from a miscalculation of the loop iterations or a misunderstanding of the decrement order, but the first printed value is clearly 9.

99
MCQmedium

A team is migrating a large monolithic Java 8 application to Java 17 using modules. They want to ensure that only the required packages are exported. Which tool should they use to analyze current dependencies and generate module descriptors?

A.jlink
B.javap
C.jar
D.jdeps
AnswerD

jdeps analyzes dependencies and can generate module-info.java suggestions.

Why this answer

jdeps is the correct tool because it is specifically designed to analyze class dependencies in Java applications and can generate module descriptor (module-info.java) suggestions. It shows which packages are used and which are not, enabling the team to export only the required packages when migrating to Java modules.

Exam trap

The trap here is that candidates confuse jdeps with jlink or jar, thinking that any packaging tool can analyze dependencies, but only jdeps provides the specific module descriptor generation capability required for modularization.

How to eliminate wrong answers

Option A is wrong because jlink is a tool for creating custom runtime images by assembling modules and their dependencies, not for analyzing dependencies or generating module descriptors. Option B is wrong because javap is a disassembler that shows class file details like methods and fields, but it does not analyze package-level dependencies or produce module-info files. Option C is wrong because jar is used to create, view, and extract JAR files, not to analyze dependencies or generate module descriptors.

100
MCQeasy

A developer needs to compile and execute a Java application on a server. Which of the following environments is sufficient to perform both tasks?

A.Both JDK and JRE
B.JDK only
C.Neither JDK nor JRE
D.JRE only
AnswerB

JDK contains javac and java, enabling both compilation and execution.

Why this answer

The JDK (Java Development Kit) includes both the javac compiler for compiling source code into bytecode and the java runtime launcher (JRE) for executing that bytecode. The JRE alone provides only the runtime environment (JVM, core libraries) and cannot compile Java source files. Therefore, the JDK is sufficient for both compiling and executing, while the JRE is not.

Exam trap

The trap here is that candidates often confuse the JRE as sufficient for development tasks, forgetting that compilation requires the JDK's javac tool, which is not part of the JRE.

How to eliminate wrong answers

Option A is wrong because the JDK already includes the JRE; having both is redundant and not a separate environment—the JDK alone is sufficient. Option C is wrong because neither JDK nor JRE would provide any compilation or execution capability, which is clearly insufficient for the tasks. Option D is wrong because the JRE lacks the javac compiler and other development tools required to compile Java source code into bytecode.

101
MCQmedium

Consider: List<String> list = Arrays.asList("A", "B", "C"); list.add("D"); What is the result?

A.An ArrayIndexOutOfBoundsException is thrown
B.The list becomes [A, B, C, D]
C.A ClassCastException is thrown
D.An UnsupportedOperationException is thrown
AnswerD

Arrays.asList returns fixed-size list.

Why this answer

The `Arrays.asList()` method returns a fixed-size list backed by the specified array. This list does not support structural modification operations like `add()` or `remove()`. Calling `add()` on such a list throws an `UnsupportedOperationException` at runtime.

Exam trap

The trap here is that candidates confuse `Arrays.asList()` with `new ArrayList<>(Arrays.asList(...))`, assuming the returned list is a regular mutable `ArrayList`, but the exam tests the fixed-size behavior of the wrapper list.

How to eliminate wrong answers

Option A is wrong because `ArrayIndexOutOfBoundsException` would occur only when accessing an invalid index in an array or list, not when calling `add()` on a fixed-size list. Option B is wrong because the list returned by `Arrays.asList()` is immutable in size, so `add()` cannot modify it to become [A, B, C, D]. Option C is wrong because `ClassCastException` is thrown when an object is cast to an incompatible type, which is not relevant here; the exception type is `UnsupportedOperationException`.

102
MCQeasy

A team is designing a logging framework. The framework's core method log(String message) may throw a checked LogException if the logging system fails. The team wants to allow callers to choose whether to handle the exception or declare it as thrown. Which declaration of the log method satisfies this requirement?

A.public void log(String message) throws LogException { ... }
B.public void log(String message) { ... }
C.public void log(String message) throws Error { ... }
D.public void log(String message) throws RuntimeException { ... }
AnswerA

Checked exception forces caller to handle or declare.

Why this answer

It declares the checked exception LogException in the throws clause, which forces callers to either handle it with a try-catch or propagate it by declaring throws in their own method. This satisfies the requirement that callers can choose how to deal with the exception, as checked exceptions must be acknowledged at compile time.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions, and the trap here is that candidates may think omitting throws or using RuntimeException/Error allows callers to choose, but only a checked exception declared with throws enforces the handling-or-declaring choice at compile time.

How to eliminate wrong answers

Option B is wrong because omitting the throws clause means the method cannot throw a checked LogException; if the implementation attempts to throw it, the code will not compile. Option C is wrong because Error is an unchecked throwable (a subclass of Throwable but not Exception), and declaring throws Error does not enforce handling of a checked exception; it also misrepresents the exception type. Option D is wrong because RuntimeException is unchecked, so callers are not required to handle or declare it, which contradicts the requirement that LogException is a checked exception that must be explicitly handled or declared.

103
MCQeasy

A Java developer is building a modular application that uses only the `java.base` and `java.sql` modules. The application runs correctly with a full JDK 17 installation. The developer wants to distribute a minimal runtime image to reduce download size for end users. They have the application module JAR file and all dependencies are modular. The developer runs the command `jlink --module-path $JAVA_HOME/jmods:app --add-modules app --output myimage` but receives an error: "Error: java.sql module not found". What is the most likely cause of this error?

A.The `--add-modules` option can only be used with root modules, but `java.sql` is not a root module.
B.The `java.sql` module is not a standard JDK module and must be compiled separately.
C.The module path is missing the application's output directory.
D.The `--add-modules` option was not specified for `java.sql`, so it is not included in the runtime image.
AnswerD

jlink only includes modules explicitly listed with `--add-modules` and their transitive dependencies. Since `java.sql` is not added, it is missing.

Why this answer

`jlink` only includes modules explicitly specified with `--add-modules` (plus their transitive dependencies) in the runtime image. The command only specifies `--add-modules app`, so `java.sql` is not included unless `app` requires it. Since the error says 'java.sql module not found', the most likely cause is that `java.sql` was not listed in `--add-modules` and is not a transitive dependency of `app`.

Exam trap

The trap here is that candidates assume `jlink` automatically includes all JDK modules present in the module path, but it only includes those explicitly requested or required by the specified root modules.

How to eliminate wrong answers

Option A is wrong because `--add-modules` can specify any module, not just root modules; the concept of 'root modules' is irrelevant here. Option B is wrong because `java.sql` is a standard JDK module included in the `java.sql` jmod file within `$JAVA_HOME/jmods`. Option C is wrong because the module path includes `$JAVA_HOME/jmods:app`, which covers both JDK modules and the application module; the error is about `java.sql`, not the application's output directory.

104
MCQhard

Which statement about Collection interface remove methods is correct?

A.Collection.remove(Object) removes the first occurrence and returns boolean.
B.List.remove(int) removes element at index and returns the removed element.
C.Collection.remove(Object) removes all occurrences of the element.
D.Both B and C
AnswerA

Correct behavior for remove method in Collection.

Why this answer

The Collection interface's remove(Object) method removes the first occurrence of the specified element from the collection, if present, and returns true if the collection was modified (i.e., the element was found and removed). This behavior is defined in the Java Collections Framework and applies to all implementations of Collection, such as ArrayList and HashSet.

Exam trap

The trap here is that candidates often confuse the Collection interface's remove(Object) with the List interface's remove(int), mistakenly thinking that remove(Object) removes all occurrences or that the index-based remove is part of the Collection interface.

How to eliminate wrong answers

Option B is wrong because List.remove(int) is not a method of the Collection interface; it is a method specific to the List interface, and while it does remove the element at the specified index and return the removed element, the question asks about the Collection interface, not List. Option C is wrong because Collection.remove(Object) removes only the first occurrence of the element, not all occurrences; to remove all occurrences, one would typically use removeAll or a loop with remove. Option D is wrong because it combines both B and C, both of which are incorrect in the context of the Collection interface.

105
MCQmedium

A class that stores sensitive user data implements Serializable. To minimize security exposure from deserialization attacks, which modification is the best practice?

A.Declare the sensitive fields as transient.
B.Override writeObject to manually exclude the sensitive fields.
C.Implement Externalizable and override readExternal and writeExternal.
D.Remove the implements Serializable clause from the class declaration.
AnswerA

Transient fields are not serialized, preventing them from being exposed in serialized data and reducing deserialization risks.

Why this answer

Declaring sensitive fields as transient prevents them from being serialized, so they are not written to the stream and cannot be deserialized. This directly eliminates the attack surface for deserialization exploits targeting those fields, as the default serialization mechanism skips transient fields entirely.

Exam trap

The trap here is that candidates often think overriding writeObject or implementing Externalizable gives full control over serialization, but they overlook that transient is the simplest and most secure way to exclude sensitive data from the serialized stream without introducing custom serialization logic that could be exploited.

How to eliminate wrong answers

Option B is wrong because overriding writeObject to manually exclude sensitive fields still leaves the class vulnerable if a custom readObject is not also implemented to handle the missing fields securely; moreover, the default serialization mechanism can still be bypassed by attackers using reflection to invoke writeObject directly. Option C is wrong because implementing Externalizable requires manual control over serialization but does not inherently protect sensitive data; if the developer fails to exclude sensitive fields in writeExternal and readExternal, the data remains exposed, and the approach is more error-prone than simply marking fields transient. Option D is wrong because removing the implements Serializable clause only prevents the class from being serialized by default, but if the class is part of a serializable hierarchy or if the application still uses ObjectOutputStream with a subclass that implements Serializable, the sensitive data can still be serialized; additionally, this does not address existing serialized data that may already be compromised.

106
MCQmedium

Given the exhibit, what is the output?

A.0.125
B.12.50%
C.%12.50
D.12.5%
AnswerB

Formatted as percent with two decimal places.

Why this answer

(12.50%) because the code uses `NumberFormat.getPercentInstance()` which formats a decimal value as a percentage by multiplying it by 100 and appending a '%' sign. The input value 0.125 is formatted as '12.50%' with two decimal places by default.

Exam trap

The trap here is that candidates often forget `NumberFormat.getPercentInstance()` automatically multiplies the value by 100 and uses two decimal places by default, leading them to expect the raw decimal or a single decimal place.

How to eliminate wrong answers

Option A is wrong because 0.125 is the raw decimal value, but `NumberFormat.getPercentInstance()` multiplies it by 100 and formats it as a percentage string, not a decimal. Option C is wrong because the '%' sign is placed after the number, not before, as per the standard `NumberFormat` percentage formatting in Java. Option D is wrong because the default `NumberFormat.getPercentInstance()` uses two decimal places, producing '12.50%' instead of '12.5%'.

107
MCQeasy

Which class is best suited for reading integer tokens from a string containing space-separated integers?

A.InputStreamReader
B.BufferedReader
C.DataInputStream
D.Scanner
AnswerD

Scanner has nextInt() and can parse integers from a string directly.

Why this answer

Scanner is best suited because it provides built-in methods like nextInt() that can parse space-separated integer tokens directly from a string, handling whitespace delimiters automatically. It is designed for parsing formatted input, making it the ideal choice for this task.

Exam trap

The trap here is that candidates often choose BufferedReader because it is familiar for reading text, but they overlook that Scanner provides direct tokenization and parsing methods, making it the more appropriate and efficient choice for this specific task.

How to eliminate wrong answers

Option A is wrong because InputStreamReader reads raw bytes and decodes them into characters, but it does not provide tokenization or integer parsing capabilities. Option B is wrong because BufferedReader reads text efficiently line by line, but it requires manual splitting and parsing of tokens to extract integers. Option C is wrong because DataInputStream reads primitive data types from a binary stream, not from a string of space-separated integers, and would throw an exception if used on text data.

108
MCQmedium

An organization has a monolithic Java application built with Java 8 and deployed on a traditional classpath. They are migrating to Java 17 and want to use the module system to improve encapsulation. They have a jar file 'legacy.jar' that contains packages under 'com.legacy' and does not have a module-info.class. Which approach should they take to allow other modules to depend on this jar?

A.Add a module-info.class file to the jar using jar tool.
B.Place the jar on the module path; it becomes an automatic module.
C.Place the jar on the classpath; it becomes an unnamed module.
D.Use jmod tool to convert the jar into a JMOD file.
AnswerB

Automatic modules are derived from jar files on the module path that lack module-info.class.

Why this answer

When a JAR file without a module-info.class is placed on the module path, Java treats it as an automatic module. This allows other modules to depend on it by name (derived from the JAR filename) and grants it access to all other modules, effectively bridging the gap between the classpath and the module system during migration.

Exam trap

The trap here is that candidates confuse the classpath (unnamed module) with the module path (automatic module) and incorrectly assume that placing a JAR on the classpath allows named modules to depend on it, when in fact only automatic modules on the module path can be referenced by 'requires' in module-info.java.

How to eliminate wrong answers

Option A is wrong because adding a module-info.class to a JAR that was not designed for the module system would require explicit module declarations and may break encapsulation or cause illegal access errors; the jar tool can add files but does not automatically generate a correct module descriptor. Option C is wrong because placing the JAR on the classpath makes it part of the unnamed module, which cannot be referenced by named modules via 'requires' and thus does not improve encapsulation as intended. Option D is wrong because the jmod tool is used to create JMOD files for platform modules or custom modules, not to convert a plain JAR into a module; JMOD files are not typically used for third-party libraries and do not solve the missing module-info issue.

109
MCQhard

Given the exhibit showing output from a program that uses try-with-resources, which of the following best describes the program?

A.The try block threw an exception, but the resource closed successfully.
B.Only the close method threw an exception, and the try block did not throw.
C.Both the try block and the close method threw exceptions.
D.The close method threw an exception, and the try block completed normally.
AnswerC

Both exceptions present; close exception is suppressed.

Why this answer

The output shows both a primary exception from the try block and a suppressed exception from the close method. In try-with-resources, if both the try block and the close method throw exceptions, the primary exception from the try block is propagated, and the close method's exception is added as a suppressed exception. The output displays both exceptions, confirming that both occurred.

Exam trap

Oracle often tests the misconception that only one exception can be thrown, leading candidates to think that if a close method throws, the try block's exception is lost, but in reality both are captured via suppressed exceptions.

How to eliminate wrong answers

Option A is wrong because it states only the try block threw an exception and the resource closed successfully, but the output shows an exception from the close method as well. Option B is wrong because it claims only the close method threw an exception and the try block did not throw, yet the output includes a primary exception from the try block. Option D is wrong because it says the close method threw an exception and the try block completed normally, but the output clearly shows a primary exception from the try block, not normal completion.

110
Multi-Selectmedium

Which TWO correctly describe the behavior of the following code? ```java int x = 10; switch (x) { case 10: System.out.print("ten "); default: System.out.print("default "); case 20: System.out.print("twenty "); } ```

Select 2 answers
A.The default case is never executed because a matching case exists.
B.The output is 'ten default ' because case 20 is skipped.
C.The code does not compile because default must be the last case.
D.The output is 'ten default twenty '.
E.The code compiles and runs, producing output due to fall-through.
AnswersD, E

Correct sequence: ten, default, twenty.

Why this answer

In a Java switch statement, once a matching case is found, all subsequent cases (including the default case) are executed in order until a break statement is encountered. Here, case 10 matches, so it prints 'ten ', then falls through to default (prints 'default '), then falls through to case 20 (prints 'twenty '), producing 'ten default twenty '. This is known as fall-through behavior.

Exam trap

The trap here is that candidates mistakenly believe the default case is optional or must be last, or that a matching case prevents fall-through, when in fact Java executes all subsequent cases (including default) until a break or the end of the switch block.

111
Multi-Selectmedium

Which three are terminal operations of the Stream interface? (Choose three.)

Select 3 answers
A.filter
B.map
C.reduce
D.forEach
E.collect
AnswersC, D, E

The `reduce` operation is a terminal operation because it processes all elements in the stream to produce a single, aggregated result (e.g., a sum or concatenation), thereby consuming the stream and preventing any further chaining of intermediate operations. This satisfies the constraint that a terminal operation must trigger the stream pipeline's execution and close the stream.

Why this answer

(reduce) is correct because it is a terminal operation that processes all elements of a stream to produce a single result (e.g., sum, concatenation). Terminal operations trigger the stream pipeline execution and close the stream, after which no further operations can be performed.

Exam trap

In the OCP Java 17 exam, this question tests the distinction between intermediate and terminal operations. The trap is that candidates may confuse intermediate operations like filter and map (which are lazy and return streams) with terminal operations that produce a result or side effect and close the stream.

112
MCQeasy

What is the likely cause of this compilation error? ```java String day = "Monday"; int dayNum = switch (day) { case 1 -> 1; case 2 -> 2; default -> 0; }; System.out.println(dayNum); ```

A.The switch expression uses arrow syntax but the keys are not unique.
B.The switch expression is missing a default case.
C.The switch expression is not assigned to a variable.
D.The switch selector is a String but case labels are int constants.
AnswerD

Switch expression requires consistent types; likely String selector with int cases.

Why this answer

In a Java switch expression, the selector type and case label types must be compatible. If the selector is a String, the case labels must be String constants; int constants would cause a compilation error due to type mismatch. Options A, B, and C describe syntax issues that are not the primary cause here.

Exam trap

The trap here is that candidates often overlook the type compatibility requirement and focus on syntax details like arrow syntax or missing default, assuming the error is about completeness or assignment rather than a fundamental type mismatch.

How to eliminate wrong answers

Option A is wrong because arrow syntax does not require unique keys; the issue is that the case labels are int constants, not String constants, so the keys are incompatible with the selector type. Option B is wrong because a switch expression does not require a default case unless the compiler cannot prove that all possible values are covered; here, the error is a type mismatch, not a missing default. Option C is wrong because a switch expression can be used as a statement (without assignment) if it uses arrow syntax and all branches produce no result, but the core error here is the type incompatibility between the String selector and int case labels.

113
MCQmedium

Given: int a=5, b=10; String result = (a > b) ? "greater" : (a < b) ? "less" : "equal"; What is result?

A."equal"
B."greater"
C.Compilation error
D."less"
AnswerD

This is correct. The expression evaluates to 'less' because a=5 is less than b=10.

Why this answer

The ternary operator is right-associative, so the expression is parsed as `a > b ? "greater" : (a < b ? "less" : "equal")`. Since `a=5` and `b=10`, `a > b` is false, so the second operand of the outer ternary is evaluated: `a < b` is true, so the inner ternary returns `"less"`. The code compiles and runs without error, producing `"less"`.

Exam trap

Candidates may think the expression causes a compilation error due to misinterpretation of grouping, but Java's right-associativity ensures it works correctly. The trap is to recognize that nested ternaries are valid and the precedence yields the expected result.

How to eliminate wrong answers

Option A is wrong because 'equal' would only be selected if `a == b`, but here `a=5` and `b=10`, so `a > b` is false and `a < b` is true, making the inner ternary return 'less'. Option B is wrong because 'greater' would require `a > b` to be true, but 5 is not greater than 10. Option D is correct because the nested ternary evaluates correctly: `a > b` is false, so the outer ternary evaluates the inner ternary `(a < b) ? "less" : "equal"`, and since `a < b` is true, it returns 'less'.

114
Multi-Selecteasy

Which THREE are valid ways to iterate over a Map<String, Integer>?

Select 3 answers
A.for (Map.Entry<String, Integer> entry : map) { }
B.for (String key : map.keySet()) { }
C.map.forEach((k, v) -> { });
D.for (Integer value : map.values()) { }
E.for (Map.Entry<String, Integer> entry : map.entrySet()) { }
AnswersB, C, E

Valid.

Why this answer

`Map.keySet()` returns a `Set<String>` containing all keys, which can be iterated using an enhanced for-each loop. This is a standard way to access keys in a `Map<String, Integer>`.

Exam trap

The trap here is that candidates may think `Map` itself is iterable (like `Collection`), but it is not; you must use `keySet()`, `values()`, or `entrySet()` to obtain an iterable view, and `forEach` is a default method on `Map` that works directly.

115
Multi-Selecthard

Which THREE statements are true about loops in Java?

Select 3 answers
A.The break statement can be used to exit a loop prematurely.
B.A while loop always executes at least once.
C.The continue statement skips the rest of the current iteration.
D.A do-while loop may execute zero times if the condition is false.
E.A for loop can have multiple loop variables.
AnswersA, C, E

Break exits the loop.

Why this answer

The break statement in Java is used to immediately terminate the execution of a loop (for, while, or do-while) and transfer control to the statement following the loop. This allows premature exit based on a condition, which is a fundamental control flow mechanism in Java.

Exam trap

The trap here is that candidates often confuse the execution guarantees of while (zero or more times) versus do-while (at least once), leading them to incorrectly select B or D as true.

116
MCQmedium

A developer writes a method that uses a for loop to iterate over a list of strings and remove elements that match a specific pattern using the list's remove(int index) method. The developer uses an index variable that increments normally. However, after running the method, some elements that should have been removed are still present, and some elements are skipped. The list initially contains [A, B, C, D, E] and the developer expects to remove B and D. After the loop, the list is [A, C, E] as expected? Actually, the developer observes that after the loop, the list contains [A, C, D, E] (D was not removed). What is the most likely cause?

A.The for loop uses an index that becomes invalid after removal.
B.The list is unmodifiable, so remove throws UnsupportedOperationException.
C.The remove method is called with the wrong index.
D.The for loop uses an iterator that throws ConcurrentModificationException.
AnswerA

After removal, elements shift left, so incrementing i causes skipping of the next element.

Why this answer

When using a for loop with an index variable that increments normally, removing an element via `remove(int index)` causes all subsequent elements to shift left. This means the loop effectively skips the element that moves into the current index after a removal. In this scenario, after removing B at index 1, element C moves to index 1, but the loop increments i to 2, so C is never checked.

Then at i=2, the loop sees D (originally at index 3). If the removal condition for D is checked at this point and matches, D would be removed, yielding [A, C, E]. However, the observed result is [A, C, D, E], indicating D was not removed.

This can happen if the loop's condition uses a fixed bound (e.g., original size) causing an `IndexOutOfBoundsException` (not shown) or if the removal pattern is based on original indices that become invalid after the first removal. The most likely cause is that the index variable becomes stale after removal, leading to skipped elements or missed removals.

Exam trap

Oracle often tests the subtlety that removing elements from a list while iterating forward with an index variable causes elements to be skipped due to index shifting, leading candidates to mistakenly think the issue is with the remove method's index or an iterator exception.

How to eliminate wrong answers

Option B is wrong because the list is not unmodifiable; the developer successfully calls remove() without an exception, and the list is modified (elements are removed). Option C is wrong because the remove method is called with the correct index at the time of removal; the issue is not a wrong index but the shifting of indices after removal. Option D is wrong because the developer is using a standard for loop with an index variable, not an iterator, so ConcurrentModificationException does not apply.

117
Multi-Selecteasy

Which TWO of the following are valid ways to create a LocalDate object in Java 17?

Select 2 answers
A.LocalDate.from(Instant.now())
B.LocalDate.of(2023, Month.JANUARY, 15)
C.LocalDate.of(2023, 13, 1)
D.LocalDate.parse("2023-01-15")
E.LocalDate.ofEpochDay("19375")
AnswersB, D

Valid overload with Month enum.

Why this answer

`LocalDate.of(int year, Month month, int dayOfMonth)` is a standard factory method that creates a `LocalDate` from explicit year, month, and day values. The `Month` enum provides type-safe month constants, making this a valid and commonly used approach.

Exam trap

Oracle often tests the distinction between `LocalDate.from()` (which requires a `TemporalAccessor` with date fields) and `Instant` (which lacks date fields without a time-zone), leading candidates to incorrectly assume any temporal object can be converted directly.

118
MCQeasy

A stream pipeline uses the peek method for debugging. Which statement about peek is correct?

A.peek is a terminal operation that prints elements.
B.peek can only be used with parallel streams.
C.peek is an intermediate operation used for debugging; it is not suitable for production side effects.
D.peek is an intermediate operation, and it is guaranteed to be executed for each element.
AnswerC

Correct: Peek is intended for debugging and should not be used for production side effects because its execution is not guaranteed.

Why this answer

The `peek` method is an intermediate operation in the Stream API, designed primarily for debugging to observe elements as they flow through the pipeline. It is not intended for production side effects because its execution is not guaranteed for every element (e.g., due to short-circuiting or optimization), and relying on it for stateful operations can lead to unpredictable behavior.

Exam trap

The trap here is that candidates assume `peek` is a terminal operation or that it always executes for every element, confusing it with `forEach` or ignoring the Stream API's lazy evaluation and optimization guarantees.

How to eliminate wrong answers

Option A is wrong because `peek` is an intermediate operation, not a terminal operation; it returns a new stream and does not trigger pipeline execution. Option B is wrong because `peek` can be used with both sequential and parallel streams; it is not restricted to parallel streams. Option D is wrong because `peek` is not guaranteed to be executed for each element; the Stream API may skip `peek` calls due to optimizations like short-circuiting (e.g., with `limit()`) or lazy evaluation, making it unreliable for side effects.

119
MCQeasy

A developer has a module named 'com.example.app' that exports a package 'com.example.api'. Another module 'com.example.client' requires 'com.example.app'. Which directive must be in the module-info.java of 'com.example.client'?

A.opens com.example.app;
B.uses com.example.api;
C.exports com.example.api;
D.requires com.example.app;
AnswerD

This correctly declares the dependency.

Why this answer

The 'requires' directive in a module-info.java file declares a dependency on another module. For 'com.example.client' to access the exported packages of 'com.example.app', it must include 'requires com.example.app;'. This is the standard mechanism for module dependency in the Java Platform Module System (JPMS).

Exam trap

The trap here is that candidates may confuse 'requires' with 'exports' or 'opens', mistakenly thinking that the client module must export or open the server module's package, rather than simply declaring a dependency.

How to eliminate wrong answers

Option A is wrong because 'opens com.example.app;' is used to allow deep reflection on a module's packages at runtime, not to declare a compile-time dependency; it does not grant access to exported types. Option B is wrong because 'uses com.example.api;' declares a service dependency for the ServiceLoader mechanism, not a module dependency; it requires the module to already be 'requires'ed. Option C is wrong because 'exports com.example.api;' is a directive for the module that owns the package to make it accessible to other modules; 'com.example.client' cannot export a package it does not own.

120
MCQeasy

A developer runs 'java --list-modules' and sees the output above. Which command can be used to create a custom runtime image containing only the 'java.base' module?

A.jar --create --file myimage --module java.base
B.jimage --add-modules java.base --output myimage
C.jlink --modules java.base --output myimage
D.jlink --add-modules java.base --output myimage
AnswerD

Correct syntax for jlink.

Why this answer

The `jlink` tool is used to assemble and optimize a set of modules and their dependencies into a custom runtime image. The `--add-modules` option specifies which modules to include, and `--output` specifies the target directory. Option D correctly uses `jlink --add-modules java.base --output myimage` to create a runtime image containing only the `java.base` module.

Exam trap

The trap here is confusing `jlink` with `jimage` or `jar`, and mistaking `--modules` for the correct `--add-modules` option, which is a common syntax error that candidates make when they recall the general concept but not the exact command flags.

How to eliminate wrong answers

Option A is wrong because `jar --create --file` is used to create a JAR archive, not a runtime image; it cannot produce a JRE image. Option B is wrong because `jimage` is a tool for listing or extracting contents of a jimage file, not for creating a runtime image; it does not have `--add-modules` or `--output` options for image creation. Option C is wrong because `jlink` does not accept `--modules`; the correct option is `--add-modules` to specify which modules to include in the image.

121
Multi-Selectmedium

Which TWO are valid ways to create an immutable List in Java?

Select 2 answers
A.Stream.of("a").collect(Collectors.toList())
B.Collections.unmodifiableList(new ArrayList<>())
C.Arrays.asList("a", "b")
D.new ArrayList<>()
E.List.of("a", "b")
AnswersB, E

Returns immutable view.

Why this answer

`Collections.unmodifiableList()` returns a view of the specified list that cannot be structurally modified; any attempt to add, remove, or set elements will throw an `UnsupportedOperationException`. Option E is correct because `List.of()` (introduced in Java 9) directly creates an immutable list that disallows `null` elements and throws `UnsupportedOperationException` on mutation attempts.

Exam trap

The trap here is that candidates often confuse 'fixed-size' (as in `Arrays.asList()`) with 'immutable', or assume that `Collectors.toList()` returns an immutable list, when in fact it returns a mutable `ArrayList`.

122
MCQeasy

A developer writes the following code using Java 17: List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add(10); What is the result?

A.Compilation error
B.The code compiles and runs successfully
C.ClassCastException at runtime
D.Compiler warning, but runs with unchecked operation
AnswerA

Generics prevent adding an Integer to List<String>.

Why this answer

The code attempts to add an integer (10) to a `List<String>`, which is a compile-time type mismatch. Java's generics enforce type safety at compile time, so adding an `int` (autoboxed to `Integer`) to a `List<String>` results in a compilation error. The code will not compile, and no runtime execution occurs.

Exam trap

The trap here is that candidates may mistakenly think autoboxing or runtime type erasure will allow the code to compile with a warning, but Java 17's strict generic type checking enforces a compilation error for such mismatches.

How to eliminate wrong answers

Option B is wrong because the code does not compile due to the type mismatch, so it cannot run successfully. Option C is wrong because a `ClassCastException` would only occur at runtime if the code compiled with unchecked operations (e.g., raw types), but here the compiler rejects the code outright. Option D is wrong because the compiler does not issue a warning for this code; it produces a hard compilation error, not an unchecked warning, since the type mismatch is detected statically.

123
Matchingmedium

Match each Java collection class to its underlying data structure.

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

Concepts
Matches

Resizable array

Doubly linked list

Hash table

Red-black tree

Hash table with buckets

Why these pairings

ArrayList uses a resizable array; LinkedList uses a doubly linked list; HashSet uses a hash table; TreeSet uses a red-black tree. Common confusions involve mixing up TreeMap with ArrayList or HashMap with TreeMap.

124
MCQmedium

Refer to the exhibit. What is the output?

A.apple, banana, cherry
B.banana, cherry
C.apple, banana, cherry,
D.apple, banana, cherry, date
AnswerA

Filter with length > 4 keeps 'apple' (5), 'banana' (6), 'cherry' (6). 'date' (4) is filtered out. Joined with ', '.

Why this answer

The code uses `Collectors.joining(", ")` which concatenates the stream elements into a single string separated by ", ". The stream contains three elements: "apple", "banana", and "cherry". The joining collector does not add a trailing delimiter, so the output is exactly "apple, banana, cherry".

Exam trap

The trap here is that candidates may mistakenly think `joining(", ")` adds a trailing delimiter after the last element, similar to how some other languages handle string joins, or they may forget that the stream contains exactly the elements listed and not an extra "date".

How to eliminate wrong answers

Option B is wrong because it omits "apple", which would only happen if the stream started from index 1 or if an element was filtered out; the stream processes all three elements. Option C is wrong because `Collectors.joining(", ")` does not append a trailing comma or space after the last element; a trailing delimiter would only appear if using `joining(", ", "", ",")` with a suffix. Option D is wrong because "date" is not present in the stream; the stream contains exactly three elements: "apple", "banana", and "cherry".

125
MCQhard

Which statement about TreeSet is true when using a custom Comparator that does not define equals() consistently with compare()?

A.TreeSet uses equals() to determine duplicates.
B.TreeSet uses hashCode() for ordering.
C.TreeSet considers two elements equal if the comparator returns 0.
D.TreeSet throws IllegalArgumentException if equals() is inconsistent.
AnswerC

Set uses comparator's compare method.

Why this answer

TreeSet uses the compare() method of the provided Comparator (or the natural ordering's compareTo()) to determine element equality. When a custom Comparator returns 0 for two elements, TreeSet treats them as duplicates and does not add the second element, regardless of what equals() returns. This is specified in the Java Collections Framework documentation and is critical for maintaining the Set contract.

Exam trap

The trap here is that candidates often assume TreeSet uses equals() for duplicate detection because of the general Set contract, but TreeSet (and TreeMap) specifically override that behavior to use compare()/compareTo() instead.

How to eliminate wrong answers

Option A is wrong because TreeSet does not use equals() to determine duplicates; it relies on the Comparator's compare() method (or Comparable's compareTo()) returning 0. Option B is wrong because TreeSet uses the Comparator's compare() method for ordering, not hashCode(); hashCode() is used by HashSet, not TreeSet. Option D is wrong because TreeSet does not throw an IllegalArgumentException when equals() is inconsistent with compare(); it simply ignores equals() and uses compare() for both ordering and duplicate detection.

126
MCQeasy

A developer is converting legacy for loops to streams. The legacy code: List<Integer> list = new ArrayList<>(); for (String s : strings) { if (s.length() > 5) { list.add(s.length()); } } They write: List<Integer> list = strings.stream() .filter(s -> s.length() > 5) .map(s -> s.length()) .collect(Collectors.toList()); But it doesn't compile. The error is: 'cannot find symbol: method collect(Collector<Object,?,List<Object>>)'. What is the likely issue?

A.The lambda in filter is incorrectly written; it should be s.length > 5.
B.The map operation returns an IntStream, which does not have a collect method. Use map(s -> s.length()).boxed().collect(...) or mapToInt(...).boxed().
C.The stream should be made unordered to allow the collector to function.
D.Use parallelStream() to enable the collect method.
AnswerB

s.length() returns int, so map produces an IntStream. To collect to List<Integer>, you need to box to Stream<Integer>.

Why this answer

The issue is that `map(s -> s.length())` on a `Stream<String>` returns an `IntStream`, not a `Stream<Integer>`. The `IntStream` interface does not have a `collect(Collector)` method; it only has `collect(Supplier, BiConsumer, BiConsumer)`. To use `Collectors.toList()`, you must convert the `IntStream` back to a `Stream<Integer>` via `.boxed()`, or use `mapToInt(...).boxed()`, or use `map(s -> (Integer) s.length())` to keep a `Stream<Integer>`.

Exam trap

The trap here is that candidates overlook the automatic specialization of `map` to `IntStream` when the lambda returns a primitive `int`, and assume `collect(Collectors.toList())` is always available on any stream, leading them to focus on unrelated options like parallelism or ordering.

How to eliminate wrong answers

Option A is wrong because `s.length > 5` is invalid Java syntax; the correct method call is `s.length() > 5`, and the lambda syntax `s -> s.length() > 5` is already correct. Option C is wrong because making the stream unordered does not affect the availability of the `collect` method; `unordered()` is a performance hint for parallel streams and does not resolve the type mismatch. Option D is wrong because `parallelStream()` would still produce an `IntStream` after `map(s -> s.length())`, and the `collect` method would still be missing; parallelism does not change the stream type.

127
MCQmedium

Refer to the exhibit. What is the output?

A.10
B.null
C.-1
D.Optional.empty
AnswerC

Correct.

Why this answer

The filter n > 100 yields an empty stream. findFirst returns an empty Optional. orElse(-1) returns -1.

128
Multi-Selectmedium

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

Select 2 answers
A.It supports adding and removing elements.
B.It returns a new ArrayList with a copy of the elements.
C.It can be used to convert an array to a mutable list if wrapped with new ArrayList<>().
D.It returns a fixed-size list backed by the original array.
E.Changes to the returned list are reflected in the original array.
AnswersD, E

The returned list size is fixed and changes to the list are reflected in the array.

Why this answer

`Arrays.asList()` returns a fixed-size list backed by the original array, meaning the list's size cannot be changed (no add or remove operations allowed). Option E is correct because any modification to the returned list (e.g., setting an element) directly modifies the underlying array, and vice versa, as the list is a view of the array.

Exam trap

The trap here is that candidates often assume `Arrays.asList()` returns a regular `java.util.ArrayList` and therefore supports add/remove, or they forget that the returned list is fixed-size and backed by the original array, leading them to select options A or B.

129
MCQeasy

The code fails to compile. What is the reason?

A.The collect method is not applicable for a Stream<Character>.
B.The method reference String::chars is not a valid method reference.
C.The chars() method returns a Stream<Character>, but flatMap requires a function that returns a Stream<Integer>.
D.The flatMap method requires a function that returns a Stream, but String::chars returns an IntStream.
AnswerD

flatMap expects a Function returning a Stream<? extends R>, but chars() returns IntStream, which is not a Stream.

Why this answer

The `chars()` method on `String` returns an `IntStream`, not a `Stream<Character>`. The `flatMap` method on a `Stream<String>` expects a function that returns a `Stream<?>`, but `String::chars` returns an `IntStream`, which is a primitive stream and not a subtype of `Stream<?>`. This type mismatch causes a compilation error.

Exam trap

The trap here is that candidates often assume `String::chars` returns a `Stream<Character>` because it deals with characters, but it actually returns an `IntStream`, leading to a type mismatch when used with `flatMap`.

How to eliminate wrong answers

Option A is wrong because `collect` is applicable to `Stream<Character>`; the issue is not with `collect` but with the intermediate `flatMap` operation. Option B is wrong because `String::chars` is a valid method reference; it refers to the `chars()` method of `String`, which returns an `IntStream`. Option C is wrong because `chars()` returns an `IntStream`, not a `Stream<Character>`, and `flatMap` requires a function that returns a `Stream`, but the mismatch is that `IntStream` is not a `Stream<Integer>`.

130
MCQmedium

Which statement is correct about the following switch expression? String result = switch(day) { case MONDAY, TUESDAY -> "weekday"; case WEDNESDAY -> "midweek"; default -> "other"; };

A.The switch expression is not allowed with a colon.
B.The switch expression must be terminated with a semicolon.
C.The default branch is optional.
D.The arrow operator requires a yield statement.
AnswerB

A switch expression is a statement that must end with a semicolon.

Why this answer

Switch expressions in Java must be terminated with a semicolon, as they produce a value that is assigned to a variable. The given code uses the arrow syntax (->) and assigns the result to a String variable, so a semicolon is required at the end of the entire switch expression.

Exam trap

The trap here is that candidates often confuse switch statements (which do not require a semicolon) with switch expressions (which do require a semicolon), leading them to overlook the mandatory semicolon at the end of the expression.

How to eliminate wrong answers

Option A is wrong because the switch expression is allowed with a colon (:) as well, but the arrow syntax (->) is used here, and the question does not state that a colon is used. Option C is wrong because the default branch is required in a switch expression when the switch selector (day) is not an enum that covers all possible values, or when the expression must be exhaustive; in this code, the default is present and is not optional for completeness. Option D is wrong because the arrow operator (->) does not require a yield statement; it directly returns the value on the right side, while yield is used with the colon syntax or in switch expressions that use blocks.

131
MCQhard

Which of the following correctly describes the behavior of the following code? List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); for (String s : list) { if (s.equals("A")) { list.remove(s); } } System.out.println(list);

A.ConcurrentModificationException is thrown
B.Compilation error
C.[B]
D.[A, B] unchanged
AnswerA

Fail-fast behavior.

Why this answer

The code uses an enhanced for-each loop to iterate over an ArrayList while calling `list.remove(s)` when the element equals "A". This modifies the list structurally during iteration, which causes the iterator (used internally by the for-each loop) to detect the concurrent modification and throw a `ConcurrentModificationException` at runtime. The exception is thrown because the iterator's `modCount` check fails when the list is modified outside of the iterator's own `remove` method.

Exam trap

The trap here is that candidates often think the for-each loop will safely remove the element and continue, or that the exception only occurs with multiple threads, but in fact any structural modification (add, remove, clear) to the underlying collection during single-threaded iteration triggers the fail-fast mechanism.

How to eliminate wrong answers

Option B is wrong because the code compiles without error; the enhanced for-each loop and `ArrayList.remove()` are valid Java syntax. Option C is wrong because the output is not `[B]`; the exception is thrown before the loop completes, so no output is printed. Option D is wrong because the list is not unchanged; the structural modification triggers an exception, not a successful removal.

132
MCQeasy

Refer to the exhibit. The module path is correctly set to include the JAR containing the module. What is the most likely issue?

A.The Main class is not specified as the main class in the module descriptor or manifest.
B.The JAR does not have a module-info.class.
C.The module requires a module that is not on the module path.
D.The Main class is not in an exported package.
AnswerA

The JVM needs the main class specified via --main-class or manifest.

Why this answer

When launching a modular JAR with `java -jar`, the JVM requires the main class to be explicitly declared either in the module descriptor (`module-info.java` with a `main-class` directive) or in the JAR's `MANIFEST.MF` (`Main-Class` attribute). Without this declaration, the JVM cannot determine the entry point, resulting in a 'Main class not found' error. Option A correctly identifies this missing declaration as the most likely issue.

Exam trap

Oracle often tests the distinction between module-path requirements for `java -jar` versus `java --module`, where candidates mistakenly think the main class must be exported or that a missing `module-info.class` is the issue, but the real trap is the missing main-class declaration in either the module descriptor or manifest.

How to eliminate wrong answers

Option B is wrong because a modular JAR must contain a `module-info.class` to be recognized as a module; if it were missing, the JVM would treat the JAR as a named module on the module path, but the question states the module path is correctly set, implying the JAR is valid. Option C is wrong because if a required module were missing, the JVM would throw a `java.lang.module.ResolutionException` at startup, not a 'Main class not found' error. Option D is wrong because the main class does not need to be in an exported package when launched with `java -jar`; the module system grants access to the main class internally, and export is only needed for reflection or cross-module access.

133
MCQmedium

What is the output when the code is executed?

A.Arithmetic Finally
B.Arithmetic Exception Finally
C.Exception Finally
D.Arithmetic Finally [stack trace]
AnswerD

Correct: 'Arithmetic' is printed, then finally prints 'Finally', then the rethrown exception causes a stack trace.

Why this answer

The code throws an ArithmeticException (division by zero) inside the try block, which is caught by the first catch block (ArithmeticException). The finally block always executes after the catch block, printing 'Finally'. The stack trace is printed because the exception is re-thrown in the catch block (implicitly or explicitly) and not handled, causing the program to terminate with an uncaught exception.

The output shows 'Arithmetic', then 'Finally', followed by the stack trace.

Exam trap

The trap here is that candidates forget that a re-thrown exception produces a stack trace, or they mistakenly think the generic Exception catch block will execute after the specific one, leading them to choose Option B or C.

How to eliminate wrong answers

Option A is wrong because it omits the stack trace; the re-thrown exception must produce a stack trace. Option B is wrong because it includes 'Exception' as a separate output; the ArithmeticException is caught first, and the generic Exception catch block is never reached. Option C is wrong because it shows 'Exception' instead of 'Arithmetic'; the specific ArithmeticException catch block matches first, so 'Arithmetic' is printed, not 'Exception'.

134
MCQmedium

Given: var list = List.of("A", "B", "C"); list.set(0, "Z"); What is the result?

A.An ArrayIndexOutOfBoundsException is thrown
B.An UnsupportedOperationException is thrown
C.The code does not compile because var cannot be used with List.of
D.The list is modified to [Z, B, C]
AnswerB

List.of returns an unmodifiable list.

Why this answer

The `List.of()` method returns an immutable list, meaning its elements cannot be added, removed, or replaced. Calling `set()` on an immutable list throws an `UnsupportedOperationException` at runtime, which is why option B is correct.

Exam trap

The trap here is that candidates often assume `List.of()` returns a mutable list similar to `new ArrayList<>()`, but it actually returns an immutable list, and the `set()` method will throw an `UnsupportedOperationException` at runtime.

How to eliminate wrong answers

Option A is wrong because `ArrayIndexOutOfBoundsException` occurs only when accessing an invalid index on a mutable array or list, but here the list is immutable and the exception type is different. Option C is wrong because `var` can be used with `List.of()`; the code compiles fine since the type is inferred as `List<String>`. Option D is wrong because the list is immutable and cannot be modified; the `set()` call throws an exception instead of changing the list.

135
MCQmedium

Refer to the exhibit. What is the output?

A.30
B.0
C.12
D.20
AnswerC

Correct. (2*2)+(4*2)=4+8=12.

Why this answer

(12). The exhibit shows a stream reduction with identity value 1 and elements 2, 3, 2. The reduce operation multiplies each element with the accumulated result: 1 * 2 = 2, 2 * 3 = 6, 6 * 2 = 12.

The identity is the starting accumulator, not a stream element.

Exam trap

Candidates often misunderstand the identity value in reduce operations. A common mistake is to think the identity is an additional stream element, or to use the wrong identity (e.g., 0 for multiplication), which would yield 0. In this example, the identity 1 and multiplication accumulate the elements 2, 3, 2 to 12.

How to eliminate wrong answers

Option A is wrong because 30 would result from using an identity of 0 and summing the elements (0+2+3+2=7, not 30) or from a different operation; it does not match the multiplication reduction with identity 1. Option B is wrong because 0 would result from using an identity of 0 in a multiplication reduction (0 * any element = 0), but the identity here is 1, not 0. Option D is wrong because 20 would result from multiplying 2*3*2=12 and then adding 8 or some other incorrect operation; it does not correspond to the sequential multiplication with identity 1.

136
MCQeasy

Which command creates a custom runtime image containing only the modules needed by an application, reducing the size of the JRE?

A.jmod
B.jar
C.jlink
D.jdeps
AnswerC

jlink links modules and creates a custom runtime image.

Why this answer

The `jlink` tool is specifically designed to create a custom runtime image that contains only the modules required by a given application, along with their transitive dependencies. This reduces the JRE size by eliminating unused modules, which is a key feature of Java's module system (Project Jigsaw). Option C is correct because `jlink` is the only command among the choices that performs this modular runtime image assembly.

Exam trap

The trap here is that candidates confuse `jlink` with `jmod` or `jar`, assuming any packaging tool can reduce the JRE, but only `jlink` performs module-aware linking to create a minimal runtime image.

How to eliminate wrong answers

Option A is wrong because `jmod` is used to create, list, and inspect JMOD files (a format for packaging modules with native code and configuration), not to create a runtime image. Option B is wrong because `jar` packages class files and resources into a JAR archive, but it does not resolve module dependencies or produce a reduced JRE. Option D is wrong because `jdeps` analyzes class dependencies and module requirements, but it only outputs dependency information and does not generate a runtime image.

137
Multi-Selecthard

Which THREE are valid Java commands for launching a modular application?

Select 3 answers
A.java -p mods -m com.app
B.java --class-path classes --module-path mods --module com.app
C.java -p classes -m com.app
D.java --module-path mods --module com.app/com.app.Main
E.java -p mods --add-modules com.app -m com.app
AnswersA, B, D

Short form: -p for module path, -m for module.

Why this answer

Options A, B, and D are correct. Option A uses the shorthand `-p` for module path and `-m` to specify the main module, which is valid. Option B explicitly specifies both classpath (--class-path) and module path (--module-path) along with the main module (--module), which is also valid.

Option D uses the long form --module-path and --module with a main class specification (com.app/com.app.Main), which is correct. Option C is invalid because `-p classes` points to a directory that typically contains class files rather than modules, and the module `com.app` would not be found there. Option E is invalid because --add-modules is not needed when using -m; it adds the module to the root set unnecessarily and can cause conflicts.

138
MCQmedium

Refer to the exhibit. A developer runs a keytool command and sees the output above. Which command produced this output?

A.keytool -list -v -alias mykey -keystore keystore.jks
B.keytool -exportcert -alias mykey -keystore keystore.jks -file cert.cer
C.keytool -importcert -alias mykey -keystore keystore.jks -file cert.cer
D.keytool -printcert -file cert.cer
AnswerA

Shows verbose details of the specified alias.

Why this answer

The `keytool -list -v -alias mykey -keystore keystore.jks` command displays detailed certificate information (including owner, issuer, serial number, validity, and fingerprint) for the specified alias in the JKS keystore. The `-v` flag produces verbose output, which matches the exhibit's detailed certificate listing.

Exam trap

The trap here is that candidates may confuse `-list -v` (which shows keystore entry details) with `-printcert` (which shows certificate file details), or mistakenly think `-exportcert` or `-importcert` produce verbose console output.

How to eliminate wrong answers

Option B is wrong because `keytool -exportcert` exports the certificate to a file (e.g., cert.cer), not to the console in a human-readable verbose format; it would not produce the listed output. Option C is wrong because `keytool -importcert` imports a certificate into the keystore, not list or display existing entries. Option D is wrong because `keytool -printcert` reads and prints details from a certificate file (e.g., cert.cer), not from a keystore entry; it does not use the `-alias` or `-keystore` options and would not show keystore-specific metadata.

139
MCQhard

Given a method that throws IOException, SQLException, and TimeoutException, a developer writes a catch block that rethrows the exception. Using Java 17, which exception types can the catch block declare in its throws clause if the rethrown exception is not modified?

A.The method must declare all checked exceptions individually.
B.Only the common superclass of the exceptions (Exception).
C.No throws clause is needed if the catch block logs and returns.
D.Any single exception type that covers all caught exceptions.
AnswerD

This is correct. The throws clause can declare any single exception type that covers all the caught exceptions, thanks to precise rethrow.

Why this answer

In Java, when a catch block catches multiple exception types and rethrows the exception without modification, the compiler uses precise rethrow. This allows the throws clause to declare any exception type that is a supertype of all the caught exceptions, such as Exception (which is a common supertype of IOException, SQLException, and TimeoutException). Therefore, the developer does not need to list each checked exception individually; a single covering type is sufficient.

Option D correctly states that any single exception type covering all caught exceptions can be declared.

Exam trap

The trap is that candidates think they must declare each checked exception individually in the throws clause when rethrowing, but Java's precise rethrow allows a single common supertype.

How to eliminate wrong answers

Option B is wrong because declaring only the common superclass Exception would be too broad and is not allowed for a rethrown exception that is not modified; Java's precise rethrow requires the exact checked exception types. Option C is wrong because the question specifies that the catch block rethrows the exception, not logs and returns; if it rethrows, a throws clause is mandatory for checked exceptions. Option D is wrong because a single exception type that covers all caught exceptions (e.g., Exception) is not permitted for unmodified rethrows; the compiler demands individual checked exception types.

140
MCQhard

Refer to the exhibit. What is the most likely cause of this exception?

A.The serialized object was tampered with after serialization.
B.The serial version UIDs of the class and stream do not match.
C.The stream's magic number is wrong due to a network error.
D.The file contains non-object data (e.g., text) instead of a serialized Java object.
AnswerD

The bytes 'ser' are likely part of a text file; the stream is not a serialized object.

Why this answer

A `java.io.StreamCorruptedException` with the message 'invalid stream header: 546F6D' indicates that the input stream does not begin with the expected magic number `0xACED` (the standard Java serialization stream header). The hex value `546F6D` corresponds to the ASCII string 'Tom', which is plain text, not serialized object data. This occurs when a file containing non-object data (e.g., text) is read by `ObjectInputStream`.

Exam trap

The trap here is that candidates may confuse `StreamCorruptedException` with `InvalidClassException` (UID mismatch) or assume network corruption, but the specific hex value `546F6D` (ASCII 'Tom') is a clear giveaway that the file contains text, not random binary corruption.

How to eliminate wrong answers

Option A is wrong because tampering with a serialized object after serialization typically causes a `java.io.InvalidClassException` or a checksum/CRC mismatch, not a `StreamCorruptedException` with an invalid stream header. Option B is wrong because a mismatch in serial version UIDs results in an `InvalidClassException` during deserialization, not a `StreamCorruptedException`; the stream header is still valid. Option C is wrong because a network error corrupting the magic number would produce a different `StreamCorruptedException` message (e.g., 'invalid stream header: random bytes'), but the specific hex value `546F6D` (ASCII 'Tom') points to text data, not random corruption.

141
MCQmedium

A web server application writes access logs to a file. To ensure that log entries are written to disk immediately even if the JVM crashes, which approach is most appropriate?

A.Use FileOutputStream and call flush() after each write.
B.Use BufferedWriter and call write() then flush() periodically.
C.Use PrintWriter with autoFlush enabled.
D.Use FileWriter without any buffering.
AnswerA

Flushing after each write forces the data to be written to the underlying file system.

Why this answer

FileOutputStream provides direct, unbuffered writes to the underlying file descriptor. While calling flush() does not force an immediate disk write (that requires sync() or FileChannel.force()), the unbuffered nature means data is passed to the operating system without intermediate caching in the JVM. Among the given options, this minimizes data loss risk because there is no JVM-level buffer that could hold unwritten data.

Options B and C use buffering, which can delay writes, and D also uses an internal buffer. Note: For true guaranteed synchronous disk writes, additional system calls like FileDescriptor.sync() or FileChannel.force() are required.

Exam trap

The trap here is that candidates often confuse 'flush()' with 'sync()' and assume that flushing a buffered stream (like BufferedWriter or PrintWriter) guarantees disk persistence, when in fact it only pushes data to the next layer (e.g., OS buffer) and does not ensure an immediate disk write.

How to eliminate wrong answers

Option B is wrong because BufferedWriter uses an internal buffer (default 8192 characters) that delays writing to disk; even with periodic flush(), entries in the buffer at the time of a crash are lost. Option C is wrong because PrintWriter with autoFlush enabled only flushes after println() or printf() calls, not after every write() or print() call, and it still may buffer data internally, leading to potential data loss. Option D is wrong because FileWriter uses an internal buffer (default 8192 characters) for efficiency, so without explicit flushing, data remains in the buffer and is not written to disk immediately, risking loss on JVM crash.

142
Multi-Selectmedium

Which TWO statements about the Java Platform Module System (JPMS) are true? (Choose two.)

Select 2 answers
A.All classes on the classpath are automatically placed in the boot layer.
B.JPMS provides reliable configuration through explicit module dependencies.
C.A module declaration is placed in a file named module-info.class.
D.JPMS allows the use of the classpath to add modules to the module graph.
E.JPMS supports strong encapsulation by controlling which packages are accessible to other modules.
AnswersB, E

Correct: JPMS requires modules to declare dependencies explicitly, eliminating classpath issues.

Why this answer

JPMS enforces reliable configuration by requiring modules to explicitly declare their dependencies using the 'requires' directive in the module descriptor. This eliminates the classpath's silent dependency resolution, where missing or conflicting JARs often cause runtime errors like ClassNotFoundException.

Exam trap

The trap here is confusing the unnamed module (classpath) with the boot layer, or assuming that module-info.class is the source file rather than the compiled output, leading candidates to incorrectly select A or C.

143
MCQmedium

You are a Java developer at a logistics company. Your team is maintaining a legacy Java 8 application that uses dozens of jars on the classpath. The company has decided to migrate to Java 17 and adopt the module system. As a first step, you are analyzing the application's dependencies using jdeps. You run 'jdeps -s -dotoutput /tmp/deps' on all jars. The output shows many dependencies labeled 'not found' for internal packages that belong to other jars in the application. The packages are correctly exported by the respective jars (which are on the classpath). You suspect that because the jars are on the classpath, jdeps cannot resolve inter-jar dependencies as modules. To get accurate dependency information, what should you do?

A.Use jlink to create a custom runtime image that includes all the jars.
B.Place all the jars on the module path and remove them from the classpath when running jdeps.
C.Run jdeps with the --module-path option pointing to the directory containing all jars, and keep the jars on the classpath.
D.Convert each jar into a named module by adding module-info.java to each jar and recompiling.
AnswerB

This makes them automatic modules, allowing jdeps to resolve inter-jar dependencies as module dependencies.

Why this answer

When jars are on the classpath, jdeps treats them as unnamed modules and cannot resolve inter-jar dependencies as module-level relationships, leading to 'not found' labels. Placing all jars on the module path (Option B) forces jdeps to treat each jar as a module (if it has a module-info.class) or as an automatic module (if it does not), enabling accurate dependency resolution. This is the correct approach because the module path is designed for module-aware analysis, while the classpath is a legacy flat namespace.

Exam trap

The trap here is that candidates think the --module-path option can be used while keeping jars on the classpath, but jdeps only performs module-aware analysis when all relevant jars are on the module path and none are on the classpath.

How to eliminate wrong answers

Option A is wrong because jlink creates a custom runtime image by linking modules, but it does not analyze dependencies; it is a deployment tool, not an analysis tool. Option C is wrong because jdeps ignores the --module-path option when jars remain on the classpath; the classpath takes precedence and jars are still treated as unnamed modules, so the 'not found' issue persists. Option D is wrong because converting jars to named modules by adding module-info.java is unnecessary for analysis; jdeps can treat jars as automatic modules on the module path without modifying them, and recompiling is a later migration step, not a prerequisite for accurate jdeps output.

144
MCQeasy

Given: for(int i=0; i<10; i++) { if(i%2==0) continue; System.out.print(i+" "); } What is the output?

A.1 3 5 7 9
B.No output
C.0 2 4 6 8
D.0 1 2 3 4 5 6 7 8 9
AnswerA

Correct: even numbers are skipped.

Why this answer

The loop iterates from 0 to 9, and the `continue` statement skips the rest of the loop body when the condition `i % 2 == 0` is true (i.e., for even numbers). Only odd numbers (1, 3, 5, 7, 9) are printed, each followed by a space.

Exam trap

The trap here is that candidates often confuse `continue` with `break`, or mistakenly think `continue` skips the current iteration entirely (including the increment), leading them to select the even numbers or no output at all.

How to eliminate wrong answers

Option B is wrong because the loop does produce output; the `continue` statement only skips even numbers, not all iterations. Option C is wrong because it lists even numbers (0, 2, 4, 6, 8), which are exactly the values skipped by the `continue` statement when `i % 2 == 0` is true. Option D is wrong because it includes all numbers from 0 to 9, but the `continue` statement prevents even numbers from being printed, so only odd numbers appear.

145
MCQeasy

Which code will successfully produce an Optional<Integer> that contains the maximum value from a list of integers?

A.B and D both produce Optional<Integer>.
B.list.stream().collect(Collectors.maxBy(Integer::compareTo))
C.list.stream().max()
D.list.stream().max(Integer::compareTo)
AnswerA

Both B and C compile and produce an Optional<Integer> with the maximum element.

Why this answer

Option A is correct because it states that options B and D both produce Optional<Integer>. Option B uses list.stream().collect(Collectors.maxBy(Integer::compareTo)), which returns an Optional<Integer> containing the maximum element. Option D uses list.stream().max(Integer::compareTo), which also returns an Optional<Integer> with the maximum element.

Option C, list.stream().max() without arguments, fails to compile because the Stream.max() method requires a Comparator. Therefore, A is the correct choice.

Exam trap

Oracle tests that Stream.max(Comparator) and Collectors.maxBy(Comparator) both return Optional<T>. Also, calling max() without a Comparator on a Stream<T> does not compile; this is distinct from IntStream.max().

How to eliminate wrong answers

Option B is correct because Collectors.maxBy(Integer::compareTo) returns an Optional<Integer> containing the maximum element. Option C is correct because list.stream().max() on a Stream<Integer> uses natural ordering (Integer implements Comparable) and returns Optional<Integer>. Option D is wrong because list.stream().max(Integer::compareTo) is syntactically invalid; max() expects a Comparator argument, but Integer::compareTo is a method reference that returns an int, not a Comparator—the correct form would be max(Integer::compareTo) if Integer::compareTo were a Comparator, but it is not; the proper comparator is Comparator.naturalOrder() or Comparator.comparingInt(Integer::intValue).

146
MCQhard

Given a try-with-resources statement where both the try block and the close method of the resource throw exceptions, which of the following is true about exception handling?

A.The exception from the close method is the primary exception.
B.Both exceptions are thrown simultaneously, causing a multi-catch.
C.The try block exception is the primary exception; the close exception is suppressed.
D.The close method exception is ignored if the try block succeeds.
AnswerC

Correct behavior of try-with-resources.

Why this answer

In a try-with-resources statement, if both the try block and the resource's close() method throw exceptions, the exception from the try block is the primary exception, and any exception thrown by close() is added as a suppressed exception. This is defined by Java's try-with-resources semantics (JLS §14.20.3.2), ensuring the primary exception is not masked by resource cleanup failures.

Exam trap

The trap here is that candidates often think both exceptions are thrown simultaneously or that the close exception is ignored, but Java's suppressed exception mechanism ensures the try block exception remains primary while preserving the close exception for debugging.

How to eliminate wrong answers

Option A is wrong because the exception from the close method is never the primary exception; the try block exception takes precedence, and the close exception is suppressed. Option B is wrong because Java does not throw both exceptions simultaneously; instead, the close exception is suppressed and attached to the primary exception via Throwable.addSuppressed(). Option D is wrong because if the try block succeeds, any exception thrown by close() is not ignored; it is thrown as the primary exception from the entire try-with-resources statement.

147
MCQeasy

Refer to the exhibit. Which algorithm was used to generate the certificate fingerprint shown?

A.SHA-1
B.MD5
C.SHA-384
D.SHA-256
AnswerB

The fingerprint shown is MD5 as indicated in the exhibit.

Why this answer

The certificate fingerprint shown is a 32-character hexadecimal string, which corresponds to a 128-bit hash. MD5 produces a 128-bit (16-byte) hash, displayed as 32 hex digits. This matches the fingerprint format exactly, confirming that MD5 was used.

Exam trap

The trap here is that candidates often confuse the output length of hash algorithms: MD5 (32 hex chars) is frequently mistaken for SHA-1 (40 hex chars) or SHA-256 (64 hex chars), leading them to pick a wrong answer based on familiarity rather than counting the hex digits.

How to eliminate wrong answers

Option A is wrong because SHA-1 produces a 160-bit (20-byte) hash, displayed as 40 hex digits, not 32. Option C is wrong because SHA-384 produces a 384-bit (48-byte) hash, displayed as 96 hex digits. Option D is wrong because SHA-256 produces a 256-bit (32-byte) hash, displayed as 64 hex digits, not 32.

148
MCQmedium

Refer to the exhibit. The exhibit shows a code snippet. What is the output when the variable day is set to Day.WEDNESDAY?

A.7
B.Compilation error
C.6
D.9
AnswerD

The default branch yields the length of "WEDNESDAY", which is 9.

Why this answer

(9) because the switch statement on Day.WEDNESDAY (ordinal 2) does not have break statements for cases WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY, causing fall-through. Execution adds values: WEDNESDAY (3), THURSDAY (4), FRIDAY (5), SATURDAY (6), totaling 18. Then the default case subtracts 9, resulting in 9.

Exam trap

The trap here is that candidates forget that switch cases fall through by default if break statements are missing, and they often overlook the effect of a default case that executes after fall-through, leading them to miscalculate the total.

How to eliminate wrong answers

Option A (7) is wrong because it assumes only one case executes (e.g., WEDNESDAY adds 3 and then a break stops, but the code lacks breaks, causing fall-through). Option B (Compilation error) is wrong because the code compiles fine; enums can be used in switch statements without error. Option C (6) is wrong because it might assume only the SATURDAY case executes (adds 6) or a miscalculation of fall-through without the default subtraction.

Page 1

Page 2 of 7

Page 3

All pages