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

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

Page 1 of 7

Page 2
1
MCQeasy

A developer needs to write text to a file with UTF-8 encoding. Which class should be used?

A.BufferedWriter
B.new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)
C.FileWriter
D.PrintWriter with default constructor
AnswerB

This allows explicit UTF-8 encoding for writing text.

Why this answer

Option B is correct because it explicitly constructs an OutputStreamWriter with a FileOutputStream and StandardCharsets.UTF_8, ensuring the text is written with UTF-8 encoding. This is the standard approach when you need precise control over the character encoding, as the OutputStreamWriter acts as a bridge from byte streams to character streams using the specified charset.

Exam trap

The trap here is that candidates often assume FileWriter or BufferedWriter automatically use UTF-8, but they actually rely on the platform's default charset, which may vary across operating systems, leading to encoding bugs in production.

How to eliminate wrong answers

Option A is wrong because BufferedWriter is a character stream that wraps another Writer but does not itself specify encoding; it relies on the underlying Writer's encoding, which by default is the platform's default encoding, not necessarily UTF-8. Option C is wrong because FileWriter uses the platform's default charset (e.g., UTF-8 on some systems, but not guaranteed) and does not allow specifying a charset, making it unreliable for cross-platform UTF-8 requirements. Option D is wrong because PrintWriter with the default constructor writes to System.out and does not write to a file; even if used with a file, it would use the platform's default encoding unless explicitly wrapped with an OutputStreamWriter specifying UTF-8.

2
Multi-Selectmedium

Which TWO statements are true regarding reading files with the NIO.2 API?

Select 2 answers
A.Files.readAllLines() is memory efficient for large files.
B.Files.newBufferedReader() provides buffered character input.
C.Files.lines() with try-with-resources allows streaming of lines.
D.Files.newInputStream() wraps a FileChannel for high performance.
E.Files.readAllBytes() is the best choice for large binary files.
AnswersB, C

newBufferedReader returns a BufferedReader for efficient reading.

Why this answer

Option B is correct because `Files.newBufferedReader()` returns a `BufferedReader` that wraps a `FileReader` (or underlying `FileChannel`), providing efficient buffered character input. This method is designed for reading text files line-by-line with reduced I/O operations, making it suitable for large or stream-oriented text processing.

Exam trap

Oracle often tests the distinction between memory-hungry convenience methods (`readAllLines`, `readAllBytes`) and streaming approaches (`lines`, `newBufferedReader`), trapping candidates who assume 'readAll' methods are efficient for large files.

3
MCQhard

A method catches multiple exceptions using a multi-catch clause. Which statement about the exceptions in a multi-catch clause is correct?

A.The exceptions must be disjoint; if one is a subclass of another, the code will not compile.
B.All exceptions in a multi-catch must be unchecked exceptions.
C.The multi-catch clause can have up to three exception types.
D.The exceptions can be in any order, and the first matching catch handles the exception.
AnswerA

Subclass relationship makes one unreachable, causing compile error.

Why this answer

Option A is correct because Java requires that exception types in a multi-catch clause be disjoint (i.e., not in a subclass/superclass relationship). If one exception is a subclass of another, the code will not compile because the catch block would be unreachable for the subclass exception, violating the rule that catch blocks must be ordered from most specific to most general. This ensures that the multi-catch clause is unambiguous and that each exception type is distinct.

Exam trap

The trap here is that candidates often confuse multi-catch with single-catch ordering rules, assuming that the order of exceptions in a multi-catch clause matters for handling, when in fact the compiler enforces disjointness and order is irrelevant within a single multi-catch block.

How to eliminate wrong answers

Option B is wrong because multi-catch clauses can include both checked and unchecked exceptions, as long as they are disjoint; there is no restriction that they must be unchecked. Option C is wrong because the Java Language Specification does not limit the number of exception types in a multi-catch clause to three; you can list any number of exception types separated by '|', as long as they are disjoint. Option D is wrong because the order of exceptions in a multi-catch clause does not matter for handling; the compiler checks that the types are disjoint, and if they are not, it fails compilation—there is no 'first matching catch' behavior within a single multi-catch block.

4
MCQhard

A financial services company runs a Java 17 application on a server with 8 GB RAM. The application reads daily transaction files in CSV format (each file is about 500 MB). It processes each line, validates it against a SQL database, and writes results to an output file. Recently, after processing about 60% of a file, the application crashes with an OutOfMemoryError: Java heap space. The heap size is set to 2 GB. The code uses Files.readAllLines() to load the entire file into a List<String>, then iterates. The team is evaluating solutions to avoid memory issues. Which approach is the best course of action?

A.Increase the JVM heap size to 4 GB.
B.Enable class data sharing to reduce memory footprint.
C.Split the file into 100 MB chunks and process each chunk sequentially.
D.Replace Files.readAllLines() with Files.lines() and process the stream line by line.
AnswerD

Streams lines lazily, fits in memory regardless of file size.

Why this answer

Option D is correct because Files.readAllLines() loads the entire 500 MB CSV file into memory as a List<String>, which causes the OutOfMemoryError when combined with other heap usage. Replacing it with Files.lines() returns a Stream<String> that reads lines lazily, processing each line one at a time without holding the entire file in memory. This directly solves the heap space issue without requiring additional hardware or manual file splitting.

Exam trap

The trap here is that candidates often choose to increase heap size (Option A) as a quick fix, missing the fundamental design flaw of loading the entire file into memory, which is a classic Java anti-pattern tested in the 1Z0-829 exam.

How to eliminate wrong answers

Option A is wrong because increasing the heap to 4 GB only postpones the problem and may not be feasible on an 8 GB server; the application could still crash with larger files or concurrent operations. Option B is wrong because class data sharing (CDS) reduces memory footprint of loaded classes, not heap usage for data buffers, so it does not address the root cause of loading a large file into memory. Option C is wrong because splitting the file into chunks still requires loading each chunk entirely into memory via readAllLines(), and the manual splitting adds complexity without fixing the fundamental issue of eager loading.

5
Multi-Selectmedium

Which THREE statements are true about Java NIO.2 and its interaction with blocking I/O? (Choose three.)

Select 3 answers
A.A Selector can be used to manage multiple non-blocking channels.
B.Files.walk() returns a Stream<Path> that lazily populates.
C.FileChannel operations are always non-blocking.
D.BufferedInputStream extends FilterInputStream.
E.Paths.get() is a factory method for obtaining a Path object.
AnswersA, B, E

A Selector can monitor multiple non-blocking channels.

Why this answer

Option A is correct because a Selector in Java NIO.2 is specifically designed to manage multiple non-blocking channels, enabling a single thread to monitor I/O readiness across many channels. This is a core feature of the NIO.2 multiplexed I/O model, where channels must be configured in non-blocking mode to be registered with a Selector.

Exam trap

The trap here is that candidates often confuse the blocking nature of FileChannel with NIO.2's non-blocking channels, or they mistakenly think BufferedInputStream is a correct answer because it is a valid I/O class, but it is not related to NIO.2 and does not fit the question's focus on NIO.2 and blocking I/O interaction.

6
MCQmedium

An application needs to maintain a set of unique customer IDs (type String) and frequently check if an ID is already present. The set is expected to contain up to 100,000 IDs. The current implementation uses a TreeSet, but performance tests show that the contains() operation is slower than desired. The developer considers switching to a HashSet. However, the business requires that when iterating the set, IDs must appear in sorted order. The developer proposes to convert the HashSet to a sorted list each time iteration is needed. Iteration occurs rarely (once per hour). What is the best approach?

A.Use ConcurrentSkipListSet
B.Use LinkedHashSet
C.Keep the TreeSet because it maintains sorted order
D.Use HashSet and sort when iteration is needed
AnswerD

Fast contains() and sorting once per hour is fine.

Why this answer

Option D is correct because the primary performance bottleneck is the contains() operation, which is O(log n) for TreeSet but O(1) average for HashSet. Since iteration with sorted order is required only once per hour, the cost of sorting the HashSet into a list (O(n log n)) is negligible compared to the frequent contains() checks. This trade-off optimizes for the dominant use case while still meeting the sorted iteration requirement.

Exam trap

The trap here is that candidates often assume sorted iteration must be maintained at all times, overlooking the fact that the requirement is only for rare iteration, making the conversion cost acceptable in exchange for faster contains().

How to eliminate wrong answers

Option A is wrong because ConcurrentSkipListSet is a thread-safe sorted set with O(log n) contains() performance, which does not improve over TreeSet and adds unnecessary concurrency overhead for a single-threaded scenario. Option B is wrong because LinkedHashSet maintains insertion order, not sorted order, so iterating it does not produce IDs in sorted order. Option C is wrong because keeping TreeSet retains the slower O(log n) contains() performance, which is the exact problem the developer is trying to solve.

7
MCQeasy

Which of the following is a checked exception in Java?

A.NullPointerException
B.ArrayIndexOutOfBoundsException
C.SQLException
D.IllegalArgumentException
AnswerC

Checked exception.

Why this answer

SQLException is a checked exception because it extends Exception directly (not RuntimeException). Checked exceptions must be either caught with a try-catch block or declared in the method signature using 'throws'. SQLException is thrown by JDBC API methods when database access errors occur, forcing the developer to handle potential SQL failures at compile time.

Exam trap

The trap here is that candidates often confuse all exception subclasses of Exception as checked, forgetting that RuntimeException and its subclasses are unchecked, and thus incorrectly select unchecked exceptions like NullPointerException or IllegalArgumentException.

How to eliminate wrong answers

Option A is wrong because NullPointerException extends RuntimeException and is an unchecked exception; it can occur at runtime without mandatory handling. Option B is wrong because ArrayIndexOutOfBoundsException extends RuntimeException and is unchecked; it is thrown by the JVM when accessing an invalid array index and does not require explicit handling. Option D is wrong because IllegalArgumentException extends RuntimeException and is unchecked; it is used to indicate that a method has received an illegal argument and does not require compile-time handling.

8
MCQhard

A team has a multi-release JAR that supports both Java 11 and Java 17. They want to ensure that when running on Java 17, the version-specific classes in META-INF/versions/17 are used. Which condition must be true?

A.The JAR must have a module-info.class in the root
B.The JAR must be placed on the module path
C.The JAR must be created using the --multi-release 17 option
D.The manifest must contain 'Multi-Release: true'
AnswerD

The manifest entry is required to activate multi-release behavior.

Why this answer

Option D is correct because the Java runtime checks for the `Multi-Release: true` entry in the JAR's manifest file to enable multi-release JAR functionality. Without this manifest attribute, the JVM ignores versioned directories under `META-INF/versions/` and uses only the root classes, even if the JAR was compiled with `--multi-release 17`.

Exam trap

Oracle often tests the misconception that the `--multi-release` compiler or jar tool option alone enables version selection at runtime, when in fact the manifest entry `Multi-Release: true` is the sole runtime trigger.

How to eliminate wrong answers

Option A is wrong because a `module-info.class` in the root is required for modular JARs but is not a condition for multi-release JAR behavior; the runtime resolves version-specific classes based on the manifest, not module descriptors. Option B is wrong because multi-release JARs work correctly on both the class path and module path; placing the JAR on the module path is not a prerequisite for version-specific class loading. Option C is wrong because the `--multi-release 17` flag is used at JAR creation time to embed versioned classes, but the runtime behavior depends solely on the manifest entry `Multi-Release: true`; without it, the JVM will not activate version selection.

9
MCQeasy

Given: for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { if(i==1 && j==1) break; } } What is the value of i after the outer loop completes?

A.1
B.2
C.4
D.3
AnswerD

Correct: the outer loop completes all three iterations, ending with i=3.

Why this answer

The outer loop variable `i` increments from 0 to 2. When `i` is 1 and `j` is 1, the `break` statement exits only the inner `for` loop, not the outer loop. The outer loop continues to its next iteration, incrementing `i` to 2, then to 3.

When `i` becomes 3, the outer loop condition `i < 3` fails, so the loop terminates. Thus, after the outer loop completes, `i` is 3.

Exam trap

The trap here is that candidates often mistakenly think `break` exits all nested loops or that the loop variable retains the value at the time of the break, leading them to choose 1 or 2 instead of recognizing the outer loop continues to completion.

How to eliminate wrong answers

Option A is wrong because `i` is never 1 after the outer loop finishes; the loop increments `i` to 2 and then 3 before exiting. Option B is wrong because `i` becomes 2 during the loop but continues to increment to 3 when the condition fails. Option C is wrong because `i` never reaches 4; the loop condition `i < 3` stops at 3.

10
MCQhard

Given the following assertion: assert age >= 0 : "Age must be non-negative"; When is it appropriate to use assertions?

A.To verify internal invariants of a private method.
B.To handle recoverable conditions like file not found.
C.To check parameters of a public API method.
D.To validate user input from an external system.
AnswerA

Assertions are perfect for internal consistency checks.

Why this answer

Option C is correct. Assertions are typically used for internal invariants during development and testing, not for argument validation in public methods. Options A, B, D are incorrect because assertions should not be used for input validation (checked exceptions) or for conditions that are checked externally.

11
MCQmedium

A developer wants to create a stream that repeatedly generates random integers. Which method should be used?

A.IntStream.range(0, 100)
B.Stream.of(new Random().nextInt())
C.IntStream.generate(() -> new Random().nextInt())
D.Stream.iterate(0, i -> new Random().nextInt())
AnswerC

This creates an infinite stream of random ints; it's the idiomatic choice for primitive streams.

Why this answer

Option C is correct because `IntStream.generate()` accepts a `Supplier<Integer>` and produces an infinite sequential unordered stream, making it ideal for repeatedly generating random integers. The lambda `() -> new Random().nextInt()` supplies a new random integer each time the stream is evaluated, fulfilling the requirement exactly.

Exam trap

The trap here is that candidates confuse `Stream.generate()` with `Stream.iterate()` or `Stream.of()`, mistakenly thinking that a single random call or a finite range can produce an infinite stream of random values, when only `generate()` with a `Supplier` correctly models repeated independent generation.

How to eliminate wrong answers

Option A is wrong because `IntStream.range(0, 100)` generates a finite stream of integers from 0 to 99, not random values. Option B is wrong because `Stream.of(new Random().nextInt())` creates a single-element stream containing one random integer, not a stream that repeatedly generates random integers. Option D is wrong because `Stream.iterate(0, i -> new Random().nextInt())` produces an infinite stream but the first element is always 0, and the seed value is never used in the generation logic, which is not a clean or intended approach for random generation; additionally, `Stream.iterate` is typically used for sequential transformations, not for independent random suppliers.

12
MCQmedium

A developer is designing a method that processes a stream of Employee objects. The method needs to group employees by department and then, within each department, sort by salary in descending order, and collect the top 3 highest-paid employees per department into a list. Which approach correctly accomplishes this using streams?

A.stream.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.collectingAndThen(Collectors.toList(), list -> list.stream().sorted(Comparator.comparing(Employee::getSalary).reversed()).limit(3).collect(Collectors.toList()))))
B.stream.collect(Collectors.toMap(Employee::getDepartment, e -> { List<Employee> l = new ArrayList<>(); l.add(e); return l; }, (l1, l2) -> { l1.addAll(l2); l1.sort(Comparator.comparing(Employee::getSalary).reversed()); return l1.subList(0, Math.min(3, l1.size())); }))
C.stream.sorted(Comparator.comparing(Employee::getSalary).reversed()).collect(Collectors.groupingBy(Employee::getDepartment, Collectors.toList())).values().stream().map(l -> l.subList(0, Math.min(3, l.size()))).collect(Collectors.toList())
D.stream.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.toList())).entrySet().stream().flatMap(e -> e.getValue().stream().sorted(Comparator.comparing(Employee::getSalary).reversed()).limit(3)).collect(Collectors.toList())
AnswerA

This groups by department, then for each group sorts descending and limits to 3, exactly as required.

Why this answer

Option A is correct because it uses `Collectors.groupingBy` to partition employees by department, then applies `Collectors.collectingAndThen` to post-process each department's list. Inside, it sorts the list by salary in descending order, limits to the top 3, and collects them into a new list. This ensures each department's result is independently sorted and truncated.

Exam trap

The trap here is that candidates often sort globally before grouping (Option C) or flatten the result (Option D), failing to realize that per-group sorting and limiting must occur inside the downstream collector to maintain group isolation.

How to eliminate wrong answers

Option B is wrong because `Collectors.toMap` with a merge function is not designed for grouping; it incorrectly mutates the same list across multiple employees, leading to shared state and potential data corruption. Option C is wrong because it sorts the entire stream globally before grouping, which destroys per-department ordering, and then uses `subList` on unsorted lists, which may not contain the top 3 per department. Option D is wrong because it flattens the grouped entries into a single stream after sorting and limiting, producing a flat list of top employees across all departments rather than a list of lists per department.

13
MCQmedium

Given nested loops with labels, which statement correctly breaks out of the outer loop?

A.break outer;
B.continue outer;
C.return;
D.break inner;
AnswerA

This labeled break exits the loop labeled 'outer'.

Why this answer

Option A is correct because the labeled break statement 'break outer;' terminates the outer loop when executed inside the inner loop. In Java, a label (e.g., 'outer:') placed before a loop allows a break or continue to target that specific loop, overriding the default behavior of breaking only the innermost loop.

Exam trap

The trap here is that candidates often forget that a plain 'break' only exits the innermost loop, and they may incorrectly assume 'continue outer;' or 'return;' achieve the same effect as a labeled break, leading them to choose a wrong option.

How to eliminate wrong answers

Option B is wrong because 'continue outer;' does not break out of the outer loop; it skips the current iteration of the outer loop and proceeds to the next iteration, which is not the same as terminating the outer loop entirely. Option C is wrong because 'return;' exits the current method entirely, which is too broad and would not simply break out of the outer loop while allowing code after the loop to execute. Option D is wrong because 'break inner;' (assuming 'inner' is a label on the inner loop) would only break the inner loop, not the outer loop, leaving the outer loop to continue its next iteration.

14
MCQmedium

A developer is working on a high-performance trading application that processes market data. The system needs to maintain a sorted list of order IDs (Long values) that are frequently inserted and removed. The current implementation uses a TreeSet<Long> to store the order IDs. The application is experiencing performance degradation under high load, and profiling shows that the TreeSet operations are the bottleneck. The developer considers replacing the TreeSet with a data structure that offers O(log n) insertion and removal but also supports O(log n) indexed access (e.g., get by index) for batch processing. Which of the following should the developer choose to improve performance while maintaining the sorted order and adding indexed access?

A.No standard Java Collections class fulfills all requirements; consider a custom implementation.
B.Replace with TreeMap<Long, Boolean> and use the key set for iteration and indexed access via keySet().toArray().
C.Replace with PriorityQueue<Long> and use poll() for removal and toArray() for indexed access.
D.Replace with ArrayList<Long> and use Collections.sort() after each insertion.
AnswerA

No built-in collection provides O(log n) insertion, removal, and indexed access simultaneously.

Why this answer

Option A is correct because no standard Java Collections class provides O(log n) insertion, removal, and O(log n) indexed access while maintaining sorted order. TreeSet offers O(log n) insertion/removal but lacks indexed access; ArrayList provides O(1) indexed access but requires O(n log n) sorting after each insertion; PriorityQueue offers O(log n) insertion/removal but only O(1) peek access, not indexed access. A custom data structure like an order statistic tree (e.g., a balanced binary search tree with subtree sizes) is needed to meet all requirements.

Exam trap

The trap here is that candidates assume TreeSet or TreeMap can provide indexed access via toArray() or keySet(), overlooking that those operations are O(n) and defeat the purpose of O(log n) performance requirements.

How to eliminate wrong answers

Option B is wrong because TreeMap<Long, Boolean> does not provide O(log n) indexed access; keySet().toArray() requires O(n) time to copy all keys into an array, and the key set itself does not support get(index). Option C is wrong because PriorityQueue<Long> does not maintain a sorted list for indexed access; it only guarantees the head (minimum) element via O(1) peek, and toArray() returns elements in arbitrary order (heap order, not sorted). Option D is wrong because ArrayList<Long> with Collections.sort() after each insertion yields O(n log n) per insertion, which is worse than the O(log n) required, and does not maintain sorted order incrementally.

15
MCQhard

What is the output of the program?

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

Correct sequence as per execution.

Why this answer

The program uses nested for loops where the outer loop runs from 0 to 2 and the inner loop runs from the outer loop's current value to that value plus 2. For each iteration, the inner loop variable is printed. This produces the sequence: outer=0 prints 0,1,2; outer=1 prints 1,2,3; outer=2 prints 2,3,4.

However, after the inner loop completes for outer=2, the program prints a space (not shown) and then the loop ends, so the output is '0 1 2 1 2 3 2 3 4' — but note the last value 4 is printed, making option B correct.

Exam trap

The trap here is that candidates miscount the number of iterations or misjudge the inner loop's termination condition, often thinking the inner loop runs from 0 to i+2 instead of from i to i+2, leading to sequences like 0 1 2 0 1 2 0 1 2 or adding extra values.

How to eliminate wrong answers

Option A is wrong because it includes an extra '4' at the end (0 1 2 1 2 3 2 3 4) which is actually correct, but the option is listed as '0 1 2 1 2 3 2 3 4' and is marked as correct in the answer key, so A is not wrong; the correct answer is B. Option C is wrong because it adds a '5' at the end, which would require the outer loop to iterate to 3 or the inner loop to go beyond outer+2, neither of which occurs. Option D is wrong because it repeats '3' an extra time (0 1 2 1 2 3 2 3 3 4), which would happen if the inner loop condition were incorrectly set to <= outer+2 or if there were an off-by-one error in the loop bounds.

16
MCQhard

Given: List<String> words = Arrays.asList("apple", "banana", "cherry"); Map<Integer, List<String>> map = words.stream().collect(Collectors.groupingBy(String::length)); System.out.println(map); What is the output?

A.[apple, banana, cherry]
B.{5=[5], 6=[6, 6]}
C.{5=[apple], 6=[banana, cherry]}
D.{apple=[5], banana=[6], cherry=[6]}
AnswerC

Correct grouping.

Why this answer

The `groupingBy` collector groups stream elements by a classifier function, here `String::length`. Each distinct length becomes a key in the map, and the values are lists of strings with that length. "apple" (length 5) maps to key 5, "banana" and "cherry" (both length 6) map to key 6, producing `{5=[apple], 6=[banana, cherry]}`.

Exam trap

The trap here is confusing `groupingBy` with `toMap` or assuming the map keys are the string values themselves, leading candidates to reverse the key-value roles or misrepresent the grouped lists.

How to eliminate wrong answers

Option A is wrong because it shows a flat list, not a map, and ignores the grouping operation. Option B is wrong because it incorrectly uses the length values as list elements instead of the original strings, and duplicates the length 6 value. Option D is wrong because it reverses the key-value relationship, making the strings the keys and their lengths the values, which is not what `groupingBy` does.

17
MCQhard

An application must read a configuration file that is updated frequently by another process. The developer wants to avoid stale data and minimize I/O operations. Which approach is best?

A.Use java.nio.file.WatchService to monitor the file for modifications and reload when notified
B.Read the file from disk every time it is accessed using Files.newInputStream()
C.Periodically check the file's lastModified timestamp using File.lastModified() and reload if changed
D.Read the file once at startup and cache the content in memory
AnswerA

WatchService provides asynchronous notifications, reducing unnecessary reads and ensuring freshness.

Why this answer

Option A is correct because java.nio.file.WatchService provides an event-driven mechanism to monitor file system changes, such as modifications to a configuration file. This approach avoids stale data by reloading the file only when a change is detected, and it minimizes I/O operations by eliminating the need for polling or repeated reads. The WatchService uses the underlying OS file system events (e.g., inotify on Linux, ReadDirectoryChanges on Windows) for efficient notification.

Exam trap

The trap here is that candidates often choose option C (polling with lastModified) because it seems simple and avoids continuous reads, but they overlook that polling still wastes resources and may miss updates, whereas WatchService is the true event-driven solution that minimizes I/O and avoids stale data.

How to eliminate wrong answers

Option B is wrong because reading the file from disk every time it is accessed using Files.newInputStream() results in excessive I/O operations, which is inefficient and contradicts the requirement to minimize I/O. Option C is wrong because periodically checking the file's lastModified timestamp using File.lastModified() and reloading if changed still involves polling, which wastes CPU cycles and I/O if the file hasn't changed, and it may miss rapid updates if the polling interval is too long. Option D is wrong because reading the file once at startup and caching the content in memory leads to stale data, as it does not account for updates made by another process.

18
Multi-Selecteasy

Which TWO are true about the try-with-resources statement?

Select 2 answers
A.Resources declared outside the try block can be used if they are effectively final.
B.All resources must be of the same type.
C.Resources declared in try-with-resources are implicitly final.
D.Multiple resources must be separated by commas.
E.The resource must implement the Closeable interface.
AnswersA, C

Effectively final variables can be used as resources.

Why this answer

Option A is correct because the try-with-resources statement allows resources declared outside the try block to be used, provided they are effectively final (i.e., their reference does not change after initialization). This was introduced in Java 9, which enhanced try-with-resources to support effectively final variables in addition to those declared directly within the try parentheses.

Exam trap

Oracle often tests the distinction between Closeable and AutoCloseable, and the requirement that resources must be declared inside the try parentheses (pre-Java 9) or be effectively final (Java 9+), leading candidates to incorrectly think resources must always be declared inside the try block or that Closeable is the only valid interface.

19
MCQeasy

Which of the following collections maintains elements in the order they were inserted?

A.LinkedHashSet
B.None of the above
C.PriorityQueue
D.HashSet
E.TreeSet
AnswerA

Correct: LinkedHashSet maintains insertion order.

Why this answer

LinkedHashSet maintains a doubly-linked list running through all of its entries, which defines the iteration ordering as the order in which elements were inserted into the set. This is specified in the Java documentation for LinkedHashSet, making it the only collection among the options that guarantees insertion order.

Exam trap

The trap here is that candidates often confuse 'ordered' (sorted) with 'ordered by insertion' and incorrectly choose TreeSet or PriorityQueue, forgetting that LinkedHashSet is the only standard Set implementation that preserves insertion order without sorting.

How to eliminate wrong answers

Option B is wrong because 'None of the above' is incorrect since LinkedHashSet does maintain insertion order. Option C is wrong because PriorityQueue orders elements according to their natural ordering or a provided Comparator, not by insertion order. Option D is wrong because HashSet uses hash-based storage and does not guarantee any specific order of elements.

Option E is wrong because TreeSet stores elements in sorted order (either natural ordering or by a Comparator), not in insertion order.

20
Multi-Selecthard

Which THREE statements are true about the java.util.Collection and java.util.stream.Stream APIs? (Choose three.)

Select 3 answers
A.The Collection.forEach() method is inherited from the Collection interface.
B.The Stream.forEach() operation processes elements in the encounter order of the stream only for sequential streams.
C.The Collection interface inherits the stream() method from the Iterable interface.
D.The Stream.toList() method returns an unmodifiable list.
E.The Iterator interface provides a default method forEachRemaining(Consumer<? super E> action).
AnswersB, D, E

Parallel streams may process elements out of order.

Why this answer

Option B is correct because the Stream.forEach() operation respects the encounter order of the stream only for sequential streams. For parallel streams, the order is not guaranteed unless the stream is explicitly forced to be sequential or uses forEachOrdered(). This behavior is defined in the Stream API specification.

Exam trap

The trap here is that candidates often assume forEach() always preserves order regardless of stream type, but the Stream API explicitly states that forEach() does not guarantee encounter order for parallel streams, unlike forEachOrdered().

21
MCQhard

Given the exhibit, what is the output? (Assume America/New_York observes daylight saving time, with spring forward on March 12, 2023 at 2:00 AM to 3:00 AM.)

A.null is printed.
B.2023-03-12T03:30:00-04:00[America/New_York]
C.A DateTimeException is thrown.
D.2023-03-12T02:30:00-05:00[America/New_York]
AnswerC

The time 02:30 does not exist due to DST gap.

Why this answer

Option C is correct because attempting to create a ZonedDateTime for 2023-03-12 at 02:30 in the America/New_York timezone results in a DateTimeException. This is due to the daylight saving time 'spring forward' transition at 2:00 AM, when clocks jump directly to 3:00 AM, making the time 02:30 non-existent in that timezone. The java.time API strictly validates local date-time values against the timezone's offset transitions and throws an exception for invalid local times.

Exam trap

The trap here is that candidates may assume the API will automatically adjust the time to the next valid moment (e.g., 03:30) or use the pre-transition offset, but the exam tests that ZonedDateTime.of() throws an exception for non-existent local times during DST gaps.

How to eliminate wrong answers

Option A is wrong because the code does not produce a null value; it throws an exception instead. Option B is wrong because it incorrectly assumes the time 02:30 is valid and would be adjusted to 03:30 with offset -04:00, but the API does not automatically shift to a valid time—it throws an exception. Option D is wrong because it assumes the time 02:30 exists with the pre-transition offset -05:00, but that time is skipped entirely during the spring-forward transition, so no such ZonedDateTime can be created.

22
MCQhard

A company runs a financial application that processes a stream of millions of transaction records daily. Each record is a 'Transaction' object with fields: id, amount, currency, timestamp. The system currently uses a parallel stream to group transactions by currency and compute the sum of amounts per currency, using the following code: Map<String, Double> result = transactions.parallelStream() .collect(Collectors.groupingBy(Transaction::getCurrency, Collectors.summingDouble(Transaction::getAmount))); Recently, performance has degraded significantly. Analysis shows that the stream source is a LinkedList, and the operation involves a large number of distinct currencies (over 1000). The JVM is running on a machine with 4 cores. Which is the best course of action to improve performance?

A.Change the stream source to an ArrayList and use sequential stream.
B.Use a custom thread pool with ForkJoinPool to control parallelism.
C.Increase the parallelism level to 8.
D.Replace groupingBy with a custom concurrent collector using ConcurrentHashMap.
AnswerD

C is correct: a concurrent collector (like groupingByConcurrent) improves parallel performance.

Why this answer

Option C is correct: using groupingByConcurrent is designed for parallel streams and uses ConcurrentHashMap, reducing merge overhead. Option A (sequential stream) would lose parallelism and likely be slower. Option B (increasing parallelism) would add overhead without addressing the source or collector issue.

Option D (custom thread pool) does not fix the core problems of poor splitting and non-concurrent collector.

23
MCQeasy

Given ArrayList<Integer> numbers = new ArrayList<>(List.of(1,2,3,4)); Which statement will insert element 10 at index 2?

A.numbers.add(10,2);
B.numbers.add(2,10);
C.numbers.set(2,10);
D.numbers.insert(2,10);
AnswerB

Inserts 10 at index 2, shifting subsequent elements to the right.

Why this answer

Option B is correct because the `ArrayList.add(int index, E element)` method inserts the specified element at the given index, shifting existing elements to the right. Here, `numbers.add(2,10)` inserts 10 at index 2, resulting in the list [1,2,10,3,4].

Exam trap

The trap here is that candidates often confuse the `add(index, element)` method with `set(index, element)`, mistakenly thinking both insert, or they reverse the argument order, expecting `add(element, index)` as in some other languages.

How to eliminate wrong answers

Option A is wrong because `add(10,2)` attempts to insert element 10 at index 2, but the arguments are reversed — the first argument must be the index, and the second the element, so this would cause a compile-time error or an `IndexOutOfBoundsException` if the index were valid. Option C is wrong because `set(2,10)` replaces the element at index 2 with 10, not inserts a new element, so the list size remains 4 and the original element at index 2 is lost. Option D is wrong because `ArrayList` has no `insert` method; this would cause a compile-time error.

24
Multi-Selecteasy

Which three of the following are valid methods in the String class in Java 17? (Choose three.)

Select 3 answers
A.substring(int, int, Locale)
B.translateEscapes()
C.toLowerCase(Locale)
D.transform(Function<String, String>)
E.indent(String)
AnswersB, C, D

Correct: translateEscapes was added in Java 14.

Why this answer

Option B is correct because `translateEscapes()` is a valid instance method introduced in Java 14 (and present in Java 17) that translates escape sequences (e.g., `\n` to newline) in a string. Option C is correct because `toLowerCase(Locale)` is a standard overloaded method in the String class that converts all characters to lowercase using the specified locale. Option D is correct because `transform(Function<String, String>)` is a valid method added in Java 12 that applies the given function to the string and returns the result.

Exam trap

The trap here is that candidates may confuse the `substring` method with other locale-sensitive methods like `toLowerCase(Locale)` or incorrectly assume that `indent` accepts a `String` parameter because of its name, when in fact it takes an `int`.

25
MCQhard

A stream pipeline uses sorted() with a Comparator that calls a thread-unsafe method on each element. The pipeline is parallel. What is the likely outcome?

A.The pipeline may produce incorrect ordering or throw a ConcurrentModificationException.
B.The pipeline will throw an exception because the comparator is stateful.
C.The pipeline will sort correctly because sorted() is a sequential operation.
D.The pipeline will run sequentially because the stream source is not ordered.
AnswerA

Correct: A non-thread-safe comparator can cause data corruption or exceptions due to concurrent access.

Why this answer

The sorted operation in parallel streams uses multiple threads and requires the comparator to be stateless and thread-safe. A thread-unsafe comparator can cause unpredictable results or exceptions.

26
MCQhard

Consider try-with-resources where resource1 is opened first, then resource2. During closing, both throw exceptions. Which exception is propagated to the caller?

A.The exception from resource1 (closed last) with resource2's exception as suppressed.
B.The exception from resource2 (closed first) with resource1's exception as suppressed.
C.Only the exception from the resource declared first is propagated.
D.Both exceptions are wrapped in a new exception.
AnswerB

Resources closed in reverse order; first exception encountered becomes primary.

Why this answer

In try-with-resources, resources are closed in the reverse order of their declaration. Resource2 (declared second) is closed first, and resource1 (declared first) is closed last. If both throw exceptions during closing, the exception from the first resource closed (resource2) is propagated to the caller, and the exception from the second resource closed (resource1) is added as a suppressed exception.

This matches option B.

Exam trap

The trap here is that candidates often mistakenly think the exception from the first declared resource is propagated, when in fact the exception from the resource closed first (the last declared) is propagated, and the other is suppressed.

How to eliminate wrong answers

Option A is wrong because it incorrectly states that the exception from resource1 (closed last) is propagated; in reality, the exception from the resource closed first (resource2) is propagated. Option C is wrong because it claims only the exception from the resource declared first is propagated, but the exception from the resource closed first (the last declared) is propagated, and the other exception is suppressed. Option D is wrong because both exceptions are not wrapped into a new exception; instead, one exception is propagated and the other is added as a suppressed exception via the Throwable.addSuppressed() mechanism.

27
MCQhard

You are developing a high-frequency trading application that processes a stream of market data ticks. Each tick is an immutable object containing timestamp, price, and volume. The ticks arrive in real time and must be stored in a collection for later analysis. The collection is accessed by multiple threads: one producer thread adds ticks, and multiple consumer threads periodically iterate to compute moving averages. The system must minimize latency for the producer and ensure that consumers see a consistent snapshot of data without interfering with ongoing writes. You initially used a synchronized ArrayList, but profiler results show high contention and poor throughput. You consider the following approaches. Which one best addresses the requirements?

A.Replace ArrayList with CopyOnWriteArrayList, which provides thread-safety without explicit synchronization and allows concurrent iteration while modifications occur.
B.Use a ConcurrentLinkedDeque for writes and have consumers obtain a consistent snapshot by calling toArray() on the deque. The toArray() operation is O(n) but provides a point-in-time view without blocking the producer.
C.Use a ConcurrentLinkedDeque and have consumers acquire a read lock when iterating, while the producer uses a write lock. This provides fine-grained locking and reduces contention.
D.Maintain two synchronized ArrayLists. The producer writes to one list while consumers read from the other. Periodically, swap references using an AtomicReference. This allows lock-free reads after the swap.
AnswerB

ConcurrentLinkedDeque offers lock-free, low-latency writes for the producer. Calling toArray() creates a snapshot that is consistent as of the moment of the call, allowing consumers to iterate without interference. The O(n) cost of toArray() is acceptable if consumers iterate infrequently relative to the number of writes.

Why this answer

Option B is correct because ConcurrentLinkedDeque allows lock-free, non-blocking writes (ideal for low-latency producers) and calling toArray() provides a consistent, immutable snapshot of the deque at that instant without blocking concurrent modifications. This satisfies the requirement for multiple consumers to see a consistent view while the producer continues writing with minimal latency.

Exam trap

The trap here is that candidates often assume CopyOnWriteArrayList is the best choice for concurrent reads and writes, but they overlook its write-cost penalty, which is disastrous for high-frequency producers; the correct solution uses a non-blocking collection with a snapshot mechanism.

How to eliminate wrong answers

Option A is wrong because CopyOnWriteArrayList creates a new copy of the underlying array on every write operation, which incurs O(n) copy cost and high memory overhead, making it unsuitable for a high-frequency producer that must minimize latency. Option C is wrong because ConcurrentLinkedDeque does not support read/write locks; it is designed for non-blocking, lock-free concurrency, and adding explicit locks would reintroduce contention and defeat its purpose. Option D is wrong because maintaining two synchronized ArrayLists with periodic swapping introduces complexity, potential staleness, and still requires synchronization on writes, which does not eliminate the contention problem shown in the profiler.

28
MCQhard

What is the result of executing the following code snippet? BigDecimal d1 = new BigDecimal("1.00"); BigDecimal d2 = new BigDecimal("1.0"); System.out.println(d1.equals(d2));

A.false
B.compile error
C.true
D.1
AnswerA

Correct: d1.equals(d2) returns false due to scale mismatch.

Why this answer

The `equals` method of `BigDecimal` compares both the numeric value and the scale (number of digits after the decimal point). Since `new BigDecimal("1.00")` has a scale of 2 and `new BigDecimal("1.0")` has a scale of 1, they are not considered equal by `equals`, even though they represent the same mathematical value. Therefore, the output is `false`.

Exam trap

The trap here is that candidates often assume `equals` behaves like `compareTo` or like primitive `==` for numeric values, forgetting that `BigDecimal.equals` enforces scale equality, so `1.00` and `1.0` are not equal.

How to eliminate wrong answers

Option B is wrong because the code compiles without error; `BigDecimal` is a standard Java class and `equals` is a valid method. Option C is wrong because `equals` does not compare only the numeric value; it also considers scale, so `1.00` and `1.0` are not equal. Option D is wrong because `System.out.println` prints a boolean (`true` or `false`), not an integer; `equals` returns a `boolean`, not `1`.

29
Multi-Selecthard

Which TWO are correct about parallel streams in Java? (Choose TWO.)

Select 2 answers
A.Parallel streams always improve performance over sequential streams.
B.Any lambda expression is safe to use in a parallel stream.
C.Using parallel streams guarantees the order of elements in the result.
D.Parallel streams use the common ForkJoinPool by default.
E.To get correct results, operations should be stateless and non-interfering.
AnswersD, E

Default pool is ForkJoinPool.commonPool().

Why this answer

Option D is correct because parallel streams in Java, by default, use the common ForkJoinPool (ForkJoinPool.commonPool()), which is a shared thread pool designed for parallel task execution. This pool is lazily initialized and has a default parallelism level equal to the number of available processors minus one, as per the ForkJoinPool implementation.

Exam trap

The trap here is that candidates often assume parallel streams are always faster (Option A) or that any lambda is safe (Option B), overlooking the critical requirements of statelessness and non-interference for correctness in parallel execution.

30
MCQeasy

Which statement about the Stream API is true?

A.Parallel streams always improve performance.
B.Streams are always finite.
C.Intermediate operations are executed eagerly.
D.A stream can be consumed only once.
AnswerD

Correct.

Why this answer

Option D is correct because a Stream in Java represents a sequence of elements that can be traversed only once. Once a terminal operation (like collect() or forEach()) is invoked on a stream, the stream is consumed and cannot be reused; attempting to do so throws an IllegalStateException. This one-time consumption is a fundamental design principle of the Stream API, ensuring that operations are applied to a single, immutable pipeline.

Exam trap

Oracle often tests the misconception that streams are reusable like collections, but the trap here is that candidates forget a stream is a one-shot object that cannot be traversed more than once, leading them to incorrectly assume they can call multiple terminal operations on the same stream.

How to eliminate wrong answers

Option A is wrong because parallel streams do not always improve performance; overhead from thread management, splitting, and merging can degrade performance, especially on small datasets or operations with high contention. Option B is wrong because streams can be infinite, as demonstrated by Stream.iterate() or Stream.generate(), which produce unbounded sequences that must be limited by short-circuiting operations like limit(). Option C is wrong because intermediate operations (e.g., filter(), map()) are lazy and are not executed until a terminal operation is invoked; they build a pipeline of operations that are applied only when needed.

31
MCQmedium

Which of the following correctly uses DateTimeFormatter to parse the date "2023-01-15" into a LocalDate?

A.LocalDate.parse("2023-01-15", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
B.LocalDate.parse("2023-01-15", DateTimeFormatter.ofPattern("yyyy-mm-dd"))
C.MonthDay.parse("2023-01-15")
D.LocalDate.parse("2023-01-15", DateTimeFormatter.ISO_LOCAL_DATE)
AnswerA

Correct pattern and method.

Why this answer

Option A is correct because `LocalDate.parse()` uses the `DateTimeFormatter` with the pattern `"yyyy-MM-dd"` which matches the ISO 8601 date format of the input string "2023-01-15". The uppercase `MM` correctly represents the month, and the pattern exactly matches the input, allowing successful parsing into a `LocalDate`.

Exam trap

The trap here is that candidates often confuse lowercase `mm` (minute) with uppercase `MM` (month) in date/time patterns, leading them to choose option B, or they forget that `MonthDay.parse()` requires a specific format without a year, causing them to select option C.

How to eliminate wrong answers

Option B is wrong because it uses `"yyyy-mm-dd"` where lowercase `mm` represents minutes, not months; this will cause a `DateTimeParseException` because the input contains month values (01) that cannot be parsed as minutes. Option C is wrong because `MonthDay.parse()` expects a string in the format `"--MM-dd"` (e.g., "--01-15"), not a full date with year, so it will throw a `DateTimeParseException`. Option D is wrong because `DateTimeFormatter.ISO_LOCAL_DATE` is actually the default formatter used by `LocalDate.parse()`, so while it would work, the question asks for a correct use of `DateTimeFormatter` to parse the date, and option D is also correct; however, the question expects only one correct answer, and option A is explicitly correct, but in this context option D is also technically correct, making the question ambiguous—but per the given answer key, A is marked correct, and D is considered wrong because the question likely expects an explicit `ofPattern` call.

32
MCQeasy

Which of the following is a best practice when designing custom exception classes?

A.Define a custom exception with a single constructor that takes an int error code.
B.Extend an existing exception class and provide constructors that call the superclass constructor.
C.Extend the Throwable class directly to create a new exception type.
D.Use a generic Exception class with a string message to indicate the type of error.
AnswerB

This matches common patterns and allows proper exception handling.

Why this answer

Option B is correct because the Java best practice for custom exceptions is to extend an existing exception class (e.g., Exception or RuntimeException) and provide constructors that call the superclass constructor. This ensures the custom exception inherits the standard exception mechanism, including proper chaining, stack trace handling, and compatibility with try-catch blocks, without reinventing the wheel.

Exam trap

Oracle often tests the misconception that extending Throwable directly is acceptable for custom exceptions, but the trap is that Throwable should only be subclassed by Error and Exception, and custom exceptions must extend Exception or RuntimeException to work correctly with Java's checked/unchecked exception rules and the compiler's exception specification enforcement.

How to eliminate wrong answers

Option A is wrong because defining a custom exception with a single constructor that takes an int error code is not a best practice; it limits flexibility and breaks the standard exception API, which expects message and cause constructors. Option C is wrong because extending Throwable directly is not recommended; Throwable is the root class, and direct subclasses are reserved for serious system errors (e.g., Error), not application-level exceptions, and it bypasses the checked/unchecked exception distinction. Option D is wrong because using a generic Exception class with a string message to indicate the type of error defeats the purpose of custom exceptions, which should provide distinct types for specific error conditions to enable precise catch-and-handle logic.

33
Multi-Selectmedium

Which TWO statements are true about creating an unmodifiable List?

Select 2 answers
A.Collections.unmodifiableList() returns a view that is unmodifiable, but the backing list can still be changed.
B.List.of() returns an immutable list that does not support any modification.
C.List.copyOf() creates a list that, if the source list is changed, the copy also changes.
D.new ArrayList<>(Arrays.asList(...)) creates an unmodifiable list.
E.Arrays.asList() returns an unmodifiable list.
AnswersA, B

View is unmodifiable, backing list change reflected.

Why this answer

B and D are correct. B: Collections.unmodifiableList returns a view that throws UnsupportedOperationException on mutating operations; it does not prevent changes to backing list. D: List.of creates an immutable list; the backing is not modifiable.

A is wrong because Arrays.asList returns a fixed-size but modifiable list (set allowed). C is wrong because new ArrayList is mutable. E is wrong because List.copyOf creates an immutable copy, but changing original does not affect the copy? Actually copyOf is independent, so modifications to original do not affect the copy; however the statement says 'does not guarantee immutability' which is false because the copy is immutable.

So E is false.

34
MCQhard

Given: List<String> words = List.of("apple", "banana", "cherry"); var result = words.stream().filter(s -> s.length() > 5).collect(Collectors.toUnmodifiableList()); What happens if another thread tries to add to result?

A.Compilation error because var cannot be used with streams.
B.UnsupportedOperationException at runtime.
C.The thread successfully adds the element.
D.NullPointerException.
AnswerB

The returned list is unmodifiable; calling add() throws UnsupportedOperationException.

Why this answer

B is correct because `Collectors.toUnmodifiableList()` returns an unmodifiable list, and any attempt to modify it (e.g., via `add()`) throws an `UnsupportedOperationException`. The stream pipeline itself is safe and compiles fine; the issue is the mutability of the resulting collection.

Exam trap

The trap here is that candidates may confuse `Collectors.toUnmodifiableList()` with `Collectors.toList()`, which returns a mutable list, and incorrectly assume the list can be modified by another thread.

How to eliminate wrong answers

Option A is wrong because `var` can be used with streams; it infers the type `List<String>` from the right-hand side, and the code compiles without error. Option C is wrong because the list returned by `Collectors.toUnmodifiableList()` is immutable, so no thread can successfully add an element; any modification attempt throws an exception. Option D is wrong because no `NullPointerException` occurs; the list is non-null and the exception is specifically `UnsupportedOperationException`.

35
MCQmedium

Which of the following correctly sorts an array of integers (int[] arr) in descending order?

A.Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new); Arrays.sort(boxed, Collections.reverseOrder()); arr = Arrays.stream(boxed).mapToInt(i->i).toArray();
B.Arrays.sort(arr, Collections.reverseOrder());
C.None of the above, because primitive arrays cannot be sorted in descending order.
D.Arrays.sort(arr, (a,b) -> b - a);
E.Arrays.parallelSort(arr, (a,b) -> b - a);
AnswerA

Correct: this boxes the array, sorts descending, and unboxes back to int[].

Why this answer

Option A is correct because it demonstrates the proper technique for sorting a primitive int array in descending order. The `Arrays.sort()` method does not accept a `Comparator` for primitive arrays, so the array must first be boxed into an `Integer[]` using `Arrays.stream(arr).boxed().toArray(Integer[]::new)`. After sorting with `Collections.reverseOrder()`, the result is unboxed back to `int[]` via `mapToInt(i->i).toArray()`.

This approach correctly leverages the `Comparator` interface, which only works with object types.

Exam trap

The trap here is that candidates often assume `Arrays.sort()` with a `Comparator` works on primitive arrays, but the Java API explicitly separates primitive and object array sorting, and the `Comparator` overload is only available for object arrays.

How to eliminate wrong answers

Option B is wrong because `Arrays.sort()` for a primitive `int[]` does not accept a `Comparator`; the overload `sort(T[], Comparator)` only works with object arrays. Option C is wrong because primitive arrays can be sorted in descending order using the boxing technique shown in option A, so the claim is false. Option D is wrong because `Arrays.sort(int[], Comparator)` does not exist; the lambda `(a,b) -> b - a` would require a `Comparator<Integer>`, which cannot be applied to a primitive array.

Option E is wrong for the same reason as D — `Arrays.parallelSort(int[], Comparator)` is not a valid overload for primitive arrays.

36
MCQhard

A financial trading application uses Java 17 and processes millions of transactions per second. It uses a custom checked exception `TradeException extends Exception` for business rule violations. Recently, the transaction processing service began throwing a `RuntimeException` that wraps a `TradeException`, but the error logs only show the wrapper's message and stack trace, missing the original `TradeException` details. The logging framework prints the exception and its cause chain. The development team needs to ensure that the original `TradeException` message and stack trace are always logged. What is the most appropriate course of action?

A.Catch the RuntimeException in the main processing loop and print the cause's message using getCause().getMessage().
B.Modify the exception wrapping code to pass the original TradeException as a cause to the RuntimeException constructor.
C.Modify the TradeException class to extend RuntimeException.
D.Override the getMessage() method in TradeException to return the original message.
AnswerB

Using the cause constructor preserves the original exception in the cause chain.

Why this answer

Option C is correct because the issue is that the wrapping code does not pass the original exception as a cause. By using the `RuntimeException(Throwable cause)` constructor or `RuntimeException(String message, Throwable cause)`, the original exception is preserved in the cause chain, and the logging framework will include it. Option A is a workaround but not a proper fix and could be error-prone.

Option B changes the exception type but does not address the missing cause, and may break checked exception contracts. Option D is irrelevant because the wrapper's `getMessage()` is the one being logged, not the original.

37
MCQeasy

A developer is implementing a cache that stores recent user sessions. The cache should maintain the most recently accessed session at the end, and when the cache reaches its maximum size (1000), it should remove the least recently accessed session (i.e., the oldest). The developer chooses a LinkedList to store sessions, adding new sessions at the end and removing from the front. However, performance is poor because searching for an existing session to update its position requires O(n) linear scan. Which collection should replace the LinkedList to improve performance while maintaining the removal order?

A.TreeSet
B.HashSet
C.LinkedHashSet
D.ArrayList
AnswerC

O(1) add, remove, contains; maintains insertion order; can reinsert to move to end.

Why this answer

LinkedHashSet (C) maintains insertion order (which can be used to represent access order if reinserted on access) and provides O(1) average-time complexity for add, remove, and contains operations. By removing and re-adding a session upon access, it moves to the end, and the oldest (first inserted) can be removed from the front when the size exceeds 1000, solving the O(n) scan problem of LinkedList.

Exam trap

The trap here is that candidates often choose HashSet for speed but forget that order is required, or choose TreeSet thinking sorted order helps, but neither maintains insertion/access order for LRU eviction.

How to eliminate wrong answers

Option A is wrong because TreeSet orders elements by their natural ordering or a comparator, not by insertion or access order, and does not allow duplicates; it would not maintain the required removal order (oldest first) and has O(log n) operations. Option B is wrong because HashSet does not maintain any order; it cannot guarantee that the least recently accessed session (oldest) is at the front for removal. Option D is wrong because ArrayList provides O(n) removal from the front (due to shifting elements) and O(n) search for an existing session, offering no performance improvement over LinkedList.

38
Multi-Selecthard

Which TWO are true about the PriorityQueue class?

Select 2 answers
A.It allows null elements.
B.It orders elements based on insertion order.
C.It is not thread-safe.
D.It can be used with a custom Comparator.
E.It provides O(1) time for contains().
AnswersC, D

Correct, not synchronized.

Why this answer

Option C is correct because PriorityQueue is not thread-safe; it does not synchronize access, so concurrent modifications without external synchronization can lead to inconsistent behavior. Option D is correct because PriorityQueue can accept a custom Comparator at construction time to define the ordering of elements, overriding the natural order.

Exam trap

The trap here is that candidates often confuse PriorityQueue with a FIFO queue (like LinkedList) and assume insertion order, or mistakenly think it allows nulls or provides O(1) contains() due to its heap structure.

39
MCQhard

A Java 17 application uses a HashMap<Integer, List<String>> to group error messages by error code. The map may contain up to 5000 error codes, and each list may contain up to 1000 messages. The application frequently retrieves the list for a given error code and iterates over it. The lists are rarely modified after initial population. The current performance is acceptable, but the team wants to reduce memory footprint. The developer suggests replacing the inner List<String> with an array (String[]), but then iteration would require conversion. Another developer suggests using a TreeMap instead of HashMap to save memory because TreeMap uses less memory per entry? Actually TreeMap has more overhead. Actually HashMap typically has lower overhead than TreeMap. The correct approach: Since lists are rarely modified, consider using List.of to create immutable lists that can be shared? Or use ArrayList with initial capacity to reduce resizing. But the stem says 'reduce memory footprint'. Option C: Use ArrayList with initial capacity to reduce internal array resizing overhead. Option A: Use TreeMap - wrong because TreeMap uses more memory per entry due to tree nodes. Option B: Use array of arrays - not type-safe. Option D: Use LinkedList - higher memory overhead per element. So best is to use ArrayList with proper sizing to minimize wasted space.

A.Replace ArrayList<String> with LinkedList<String>
B.Replace HashMap with TreeMap
C.Replace List<String> with String[]
D.Use ArrayList<String> with initial capacity set to expected list size
AnswerD

Minimizes internal array resizing and waste.

Why this answer

Option D is correct because using an ArrayList with an initial capacity set to the expected list size eliminates the overhead of repeated internal array resizing (which wastes memory by leaving unused capacity). Since the lists are rarely modified after initial population, this approach minimizes wasted space without sacrificing iteration performance, unlike the other options.

Exam trap

The trap here is that candidates assume switching to a different collection type (like TreeMap or LinkedList) will save memory, when in fact the most effective memory optimization is to eliminate wasted internal capacity by using ArrayList with a proper initial capacity.

How to eliminate wrong answers

Option A is wrong because LinkedList has higher per-element memory overhead (due to node objects storing prev/next pointers) and poor iteration performance, increasing memory footprint. Option B is wrong because TreeMap uses more memory per entry than HashMap (tree nodes store color, parent, left, right pointers) and offers no memory benefit. Option C is wrong because replacing List<String> with String[] would require manual conversion for iteration, losing type safety and flexibility, and does not inherently reduce memory if the array is oversized; the real memory waste comes from unused capacity, not the collection type.

40
MCQeasy

Which of the following correctly uses a switch expression with multiple constants per case? ```java int day = 2; String result = switch (day) { case 1, 2, 3 -> "Weekday"; case 6, 7 -> "Weekend"; default -> "Invalid"; }; ``` What is the value of result?

A.The code does not compile because multiple constants are not allowed.
B.Weekday
C.Invalid
D.Weekend
AnswerB

Correct match.

Why this answer

The switch expression correctly uses multiple constants per case with the arrow syntax. Since day is 2, it matches case 1, 2, 3, so the expression evaluates to "Weekday". The switch expression is exhaustive (covers all possible int values via the default branch), so it compiles and runs without error.

Exam trap

Oracle often tests whether candidates know that multiple constants per case are allowed in modern Java (since Java 14), and the trap here is that some candidates mistakenly believe this syntax is invalid or that the default branch would be selected for a value that matches an explicit case.

How to eliminate wrong answers

Option A is wrong because Java 14+ allows multiple constants per case in switch expressions and statements, separated by commas. Option C is wrong because day=2 matches case 1,2,3, not the default branch. Option D is wrong because day=2 does not match case 6,7, which would yield "Weekend".

41
Multi-Selectmedium

Which TWO practices improve the security of Java serialization?

Select 2 answers
A.Disable serialization by throwing NotSerializableException from writeObject().
B.Mark sensitive fields as transient to exclude them from serialization.
C.Set a random serialVersionUID to prevent malicious serialization.
D.Implement readObject() to validate and sanitize fields.
E.Use Externalizable for full control over serialization format.
AnswersB, D

transient prevents sensitive data from being serialized.

Why this answer

Option B is correct because marking sensitive fields as transient prevents them from being serialized, ensuring that confidential data (e.g., passwords, cryptographic keys) is not exposed through the serialized stream. Option D is correct because implementing readObject() allows you to validate and sanitize deserialized fields, protecting against deserialization attacks where crafted data could corrupt the object state or trigger malicious behavior.

Exam trap

The trap here is that candidates often confuse serialVersionUID as a security mechanism when it is actually a versioning control for class compatibility, not a defense against malicious serialization.

42
MCQhard

Given a list of strings, which of the following will produce a Map<String, Long> counting the occurrences of each string?

A..collect(Collectors.toMap(Function.identity(), String::length))
B..collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
C..collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e->1)))
D..collect(Collectors.toMap(Function.identity(), v->1))
AnswerB

Correct. groupingBy with counting as downstream collector produces a long count per key.

Why this answer

Collectors.groupingBy with Collectors.counting() correctly counts occurrences and returns Map<String, Long>.

43
Multi-Selectmedium

Which THREE of the following are valid ways to create a new ArrayList<Integer>? (Select three.)

Select 3 answers
A.new ArrayList<>(Arrays.asList(1,2,3))
B.new ArrayList<>(10, 20, 30)
C.new ArrayList<>(List.of(1,2,3))
D.(ArrayList<Integer>) Arrays.asList(1,2,3)
E.new ArrayList<Integer>() with initial capacity 10
AnswersA, C, E

Creates an ArrayList from the List returned by Arrays.asList.

Why this answer

Option A is correct because `Arrays.asList(1,2,3)` returns a fixed-size `List<Integer>`, and passing it to the `ArrayList` constructor creates a new, mutable `ArrayList<Integer>` containing the same elements. This is a standard way to initialize an `ArrayList` with known values.

Exam trap

The trap here is that candidates confuse `Arrays.asList` with `ArrayList` and attempt to cast the returned list directly, not realizing it is a different class that cannot be cast to `ArrayList`.

44
Matchingmedium

Match each Java module directive to its description.

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

Concepts
Matches

Makes a package accessible to other modules

Specifies a dependency on another module

Allows reflective access to a package at runtime

Declares a service implementation

Specifies a service interface consumed by the module

Why these pairings

These directives are used in module-info.java for the Java Module System.

45
MCQmedium

A developer is implementing a method that processes a collection of objects. The objects are instances of various classes that implement a common interface. The developer wants to use a switch expression to perform different actions based on the runtime type of each object. Which approach is correct?

A.Use a series of if-else statements with instanceof.
B.Use a switch expression with pattern matching and a default case.
C.Use a traditional switch statement with instanceof checks and casting.
D.Use a switch expression with pattern matching without a default case if all possible types are covered.
AnswerD

Switch expressions must be exhaustive; if all subtypes are covered, no default is needed.

Why this answer

Option D is correct because Java 17+ switch expressions with pattern matching allow exhaustive type coverage without a default case when all possible subtypes of the sealed interface or hierarchy are explicitly listed. This ensures compile-time safety and eliminates the need for a default branch, aligning with the principle of exhaustive pattern matching.

Exam trap

The trap here is that candidates often assume a default case is always required in switch expressions, but the exam tests the knowledge that pattern matching with sealed types or exhaustive coverage can omit the default case, and that including one may actually mask missing cases and defeat compile-time safety.

How to eliminate wrong answers

Option A is wrong because using a series of if-else statements with instanceof is verbose, error-prone, and does not leverage the concise, type-safe pattern matching introduced in modern Java. Option B is wrong because it mandates a default case even when all possible types are covered, which is unnecessary and can hide missing cases if the hierarchy changes. Option C is wrong because a traditional switch statement with instanceof checks and casting requires manual casting and lacks the compile-time exhaustiveness check that pattern matching provides.

46
Multi-Selectmedium

Which TWO of the following statements about the Collections framework are true?

Select 2 answers
A.Collections.checkedList performs type checking at compile time.
B.Collections.unmodifiableList returns an unmodifiable view of the list.
C.List.of returns a mutable list.
D.Collections.synchronizedList returns a thread-safe list.
E.Arrays.asList returns a mutable list of variable size.
AnswersB, D

Correct: it wraps the list to prevent modifications.

Why this answer

Option B is correct because `Collections.unmodifiableList()` returns a view of the specified list that cannot be modified. Any attempt to modify the returned list (e.g., add, remove, set) will throw an `UnsupportedOperationException`. This is a standard method in the Java Collections Framework to provide read-only access to a list.

Exam trap

The trap here is that candidates often confuse `Collections.unmodifiableList()` with `List.of()` or assume that `Arrays.asList()` returns a fully mutable list of variable size, when in fact it returns a fixed-size list backed by the array.

47
MCQmedium

A developer wants to find the longest word in a list of strings. Which stream operation should be used?

A.stream().sorted(Comparator.comparingInt(String::length).reversed()).findFirst()
B.stream().min(Comparator.comparingInt(String::length))
C.stream().sorted(Comparator.comparingInt(String::length)).findFirst()
D.stream().max(Comparator.comparingInt(String::length))
AnswerD

Correct.

Why this answer

Option D is correct because the `max()` terminal operation, when combined with a `Comparator` that compares strings by their length, returns the longest word in the stream. The `max()` operation uses the provided comparator to determine the 'largest' element according to the ordering, which in this case is the string with the greatest length.

Exam trap

The trap here is that candidates often confuse `min()` and `max()` or incorrectly assume that sorting and taking the first element is the intended approach, overlooking the direct and efficient `max()` operation.

How to eliminate wrong answers

Option A is wrong because it sorts the stream in descending order of length and then calls `findFirst()`, which is unnecessarily complex and less efficient than `max()`; it also requires the stream to be fully sorted before retrieval. Option B is wrong because `min()` returns the smallest element according to the comparator, which would give the shortest word, not the longest. Option C is wrong because it sorts in ascending order of length and then calls `findFirst()`, which returns the shortest word, not the longest.

48
MCQeasy

What is the result of the following code? List<String> list = List.of("A", "B"); list.add("C"); System.out.println(list);

A.[A, B, C]
B.[A, B]
C.An exception is thrown at runtime
D.Compilation error
AnswerC

UnsupportedOperationException thrown.

Why this answer

The `List.of()` factory method returns an immutable list. Calling `add()` on an immutable list throws an `UnsupportedOperationException` at runtime, so the code does not compile or run successfully. Option C is correct because the exception is thrown when the `add` method is invoked.

Exam trap

The trap here is that candidates often assume `List.of()` returns a regular mutable `ArrayList` or that the code will simply ignore the `add` call, but the exam tests the specific runtime exception behavior of immutable collections created by factory methods.

How to eliminate wrong answers

Option A is wrong because it assumes the list is mutable and that 'C' can be added, but `List.of()` creates an immutable list that cannot be modified. Option B is wrong because it suggests the list remains unchanged and the program prints '[A, B]', but the `add` call throws an exception before the `println` executes. Option D is wrong because there is no compilation error; the code compiles fine since `add()` is a valid method on the `List` interface, but it fails at runtime.

49
Multi-Selectmedium

Which two statements about the break statement are true?

Select 2 answers
A.break can be used inside an if statement.
B.break without a label terminates the innermost loop or switch.
C.break can only be used inside a loop.
D.break with a label terminates the outermost matching loop or switch.
E.break can be used inside a switch statement.
AnswersB, E

Correct: it exits the immediate enclosing loop or switch.

Why this answer

Option B is correct because the break statement, when used without a label, immediately terminates the innermost enclosing loop (for, while, do-while) or switch statement. This is defined by the Java Language Specification (JLS §14.15), which states that an unlabeled break statement transfers control out of the immediately enclosing statement.

Exam trap

Oracle often tests the misconception that break can only be used in loops, when in fact it is also valid in switch statements, and that labeled break can only target loops, when it can target any labeled statement.

50
MCQmedium

A company deploys a Java 17 application on a server with a custom runtime image created by jlink. The application uses the Java logging API (java.util.logging). The server administrator notices that the image size is approximately 45 MB. They need to reduce it further. Which jlink option would help exclude unnecessary locale data?

A.--include-locales en_US
B.--compress=2
C.--strip-debug
D.--no-header-files
AnswerA

Using --include-locales with a limited set includes only those locales, excluding others and reducing the image size.

Why this answer

Option A is correct because the `--include-locales` option in jlink allows you to specify which locale data to include in the custom runtime image. By default, jlink includes all locale data, which can significantly increase image size. Using `--include-locales en_US` restricts the image to only US English locale data, reducing unnecessary bloat for applications that do not require multiple locales.

Exam trap

The trap here is that candidates may confuse size-reduction options like compression or stripping debug with the specific need to exclude locale data, leading them to choose `--compress=2` or `--strip-debug` instead of the correct `--include-locales` option.

How to eliminate wrong answers

Option B is wrong because `--compress=2` applies ZIP compression to the image's resources, which reduces size but does not specifically exclude locale data; it compresses all resources, including locale data that may still be present. Option C is wrong because `--strip-debug` removes debug information from the image, which reduces size but has no effect on locale data inclusion. Option D is wrong because `--no-header-files` excludes header files (used for native development) from the image, which does not impact locale data.

51
Matchingmedium

Match each exception class to its category (checked/unchecked).

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

Concepts
Matches

Checked exception

Unchecked exception

Checked exception

Unchecked exception

Checked exception

Why these pairings

Checked exceptions must be handled or declared; unchecked extend RuntimeException.

52
MCQhard

Given the following switch expression with colon syntax, what is the result when code equals 2? int val = switch(code) { case 1: yield 10; case 2: yield 20; default: yield 30; };

A.20
B.10
C.30
D.Compilation error
AnswerA

20 is the yield for case 2.

Why this answer

When code equals 2, the switch expression matches case 2: and executes the yield 20; statement, which returns 20 as the value assigned to val. The colon syntax with yield is valid in Java 14+ switch expressions, and each case must yield a value.

Exam trap

The trap here is that candidates may think colon syntax requires break instead of yield, or that yield is only for arrow syntax, but Java allows yield in both colon and arrow forms for switch expressions.

How to eliminate wrong answers

Option B is wrong because case 1: would only be selected when code equals 1, not 2. Option C is wrong because the default label is only reached if no case matches, but here case 2 matches exactly. Option D is wrong because the switch expression with colon syntax and yield statements is valid Java syntax; it compiles successfully.

53
MCQeasy

A Java application running on a server reads configuration from a file 'config.properties' located in the same directory as the JAR. The application uses java.util.Properties.load(InputStream) to read the file. Recently, the file was modified by an unauthorized user, and the application started throwing runtime exceptions due to corrupted property values. The security team requires that the file be protected from unauthorized modifications while still being readable by the application. Which action should be taken to ensure the integrity of the configuration file?

A.Encrypt the file using AES and decrypt it in the application.
B.Set the file permissions to read-only for the application user.
C.Store the file in a ZIP archive with a checksum.
D.Digitally sign the file and verify the signature before loading properties.
AnswerD

Digital signatures provide integrity and authenticity; any modification invalidates the signature.

Why this answer

Option D is correct because digital signing provides both integrity and authenticity. By signing the file with a private key and verifying the signature with a public key before calling Properties.load(InputStream), the application can detect any unauthorized modification. This directly addresses the security requirement without relying on encryption (which protects confidentiality, not integrity) or file permissions (which can be bypassed by a privileged attacker).

Exam trap

The trap here is that candidates confuse encryption (confidentiality) with integrity, or assume file permissions are sufficient, but the exam tests understanding that only digital signing provides non-repudiation and tamper detection against unauthorized modifications.

How to eliminate wrong answers

Option A is wrong because encryption (e.g., AES) protects confidentiality, not integrity; a corrupted or tampered file would still decrypt (possibly to garbage) and cause runtime exceptions. Option B is wrong because file permissions can be overridden by a root user or an attacker with sufficient privileges, and they do not prevent the file from being modified by a different user or process. Option C is wrong because a ZIP archive with a checksum does not provide cryptographic integrity; a checksum can be recomputed after tampering, and ZIP does not inherently include a digital signature mechanism.

54
MCQmedium

A developer is implementing a custom sort for a list of Employee objects. The Employee class has fields: String name, int age. The list must be sorted first by name (ascending, case-insensitive), then by age (descending). Which Comparator implementation correctly achieves this?

A.Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER).thenComparingInt(Employee::getAge)
B.Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER).thenComparing(Comparator.comparingInt(Employee::getAge).reversed())
C.Comparator.comparingInt(Employee::getAge).reversed().thenComparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)
D.Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge).reversed()
AnswerB

Correctly sorts by name case-insensitive ascending, then age descending.

Why this answer

Option B is correct because it first sorts by name using a case-insensitive comparator, then chains a reversed comparator for age, ensuring descending order for age while preserving the primary sort by name. The `thenComparing` method correctly applies the reversed age comparator as a secondary sort, which is essential for multi-field sorting where one field requires descending order.

Exam trap

The trap here is that candidates often forget to reverse only the secondary comparator (age) and instead apply `reversed()` to the entire chain, which inverts all sort orders, or they mistakenly use `thenComparingInt` without reversal, leading to ascending age order.

How to eliminate wrong answers

Option A is wrong because `thenComparingInt(Employee::getAge)` sorts age in ascending order, not descending as required. Option C is wrong because it sorts by age first (descending) and then by name, which reverses the required primary and secondary sort order. Option D is wrong because `reversed()` is applied to the entire comparator chain, reversing both the name sort (to descending) and the age sort (to ascending), which does not meet the requirement of ascending name and descending age.

55
Multi-Selecthard

Which THREE statements about the jpackage tool are true?

Select 3 answers
A.jpackage requires an existing JRE to create a runtime image.
B.jpackage uses the Java Packager library.
C.jpackage can create native installers for Windows, macOS, and Linux.
D.jpackage can bundle a JVM with the application.
E.jpackage can use a pre-built runtime image created by jlink.
AnswersC, D, E

jpackage supports all major operating systems.

Why this answer

Option C is correct because the jpackage tool is designed to create native installers for Windows (e.g., .exe/.msi), macOS (e.g., .dmg), and Linux (e.g., .deb/.rpm). This is a core feature of jpackage, which replaces the older Java Packager and allows developers to distribute self-contained applications with platform-specific packaging formats.

Exam trap

The trap here is that candidates often confuse jpackage with the deprecated Java Packager (javapackager) or assume it requires an external JRE, when in fact jpackage is a self-contained tool that can generate runtime images and native installers without external dependencies.

56
Multi-Selecteasy

Which THREE statements about exception handling are true? (Choose three.)

Select 3 answers
A.The variable in a catch clause is effectively final only when using multi-catch syntax.
B.A finally block is mandatory in a try-with-resources statement.
C.Multi-catch syntax uses the pipe symbol (|) between exception types.
D.Checked exceptions must be handled or declared in the throws clause.
E.A finally block will not execute if the JVM exits before the finally block.
AnswersC, D, E

Correct syntax.

Why this answer

Option C is correct because Java's multi-catch syntax allows a single catch block to handle multiple exception types by separating them with the pipe symbol (|). This reduces code duplication when different exceptions require the same handling logic.

Exam trap

The trap here is that candidates often confuse the 'effectively final' concept with multi-catch syntax, incorrectly thinking that only multi-catch variables are effectively final, when in fact all catch clause variables are implicitly final in Java.

57
MCQmedium

Consider the following do-while loop: ```java int x = 10; do { x--; } while (x < 10); System.out.println(x); ``` What is printed?

A.3
B.The loop does not compile because x is not declared final.
C.2
D.1
AnswerA

Correct, final value is 3.

Why this answer

The loop executes body first: x becomes 2, condition (2<3) true, execute again: x becomes 3, condition (3<3) false, exit. Print x which is 3.

58
MCQeasy

A Java application is developed using Java SE 17. It uses only standard Java APIs and no external libraries. The application runs without errors in the development environment. When deploying to a production server, which minimal Java environment is sufficient?

A.Java compiler (javac)
B.Java Virtual Machine (JVM) only
C.Java Development Kit (JDK)
D.Java Runtime Environment (JRE)
AnswerD

JRE provides JVM and all necessary libraries to run Java applications.

Why this answer

The correct answer is D because a Java application compiled into bytecode (`.class` files) requires only the Java Runtime Environment (JRE) to execute. The JRE includes the Java Virtual Machine (JVM), core libraries, and supporting files, but not development tools like the compiler. Since the application is already compiled and uses only standard APIs, no additional tools are needed at runtime.

Exam trap

The trap here is that candidates confuse the JVM with the JRE, thinking a standalone JVM can run Java applications, but the JVM requires the runtime libraries packaged in the JRE to resolve standard classes like `java.lang.String`.

How to eliminate wrong answers

Option A is wrong because the Java compiler (javac) is a development tool used to compile source code into bytecode; it is not needed to run an already-compiled application. Option B is wrong because a JVM alone is insufficient — the JRE includes the JVM plus essential runtime libraries (e.g., java.lang, java.util) that the application depends on; a standalone JVM without these libraries cannot execute standard Java code. Option C is wrong because the Java Development Kit (JDK) includes the JRE plus development tools (compiler, debugger, etc.), which are unnecessary for running a pre-compiled application and add overhead.

59
MCQmedium

A company has a legacy application consisting of multiple JAR files that run on Java 11. They plan to migrate to Java 17 and modularize the application using JPMS. However, some third-party libraries do not provide module-info.class files. What is the best approach to ensure the application can be modularized while maintaining compatibility with these libraries?

A.Create a module-info.java for the application that requires all third-party libraries as automatic modules.
B.Place all third-party JARs on the classpath and the application JARs on the module path.
C.Place all JARs on the module path and use the --add-reads and --add-exports flags to resolve dependencies.
D.Use the jlink tool to create a custom runtime image that includes all needed modules.
AnswerA

Automatic modules allow backward compatibility; the application can declare requires on the library names derived from JAR names.

Why this answer

Option B is correct because creating a module-info.java that requires the third-party libraries as automatic modules (by placing them on the module path) allows the application to be modular while using libraries without module-info. Option A is wrong because mixing classpath and module path can lead to class-loading inconsistencies and is not recommended. Option C is wrong because using --add-reads and --add-exports for all libraries is verbose and error-prone.

Option D is wrong because jlink creates a runtime image but does not solve the modularization of dependencies.

60
MCQhard

Which of the following lambda expressions is syntactically invalid?

A.() -> {return 42;}
B.(a, b) -> a + b
C.(a, b) -> return a + b;
D.(int a, int b) -> a + b
E.(a) -> a * 2
AnswerC

Invalid. 'return' keyword requires a block body (curly braces).

Why this answer

Option C is syntactically invalid because in a lambda expression, the `return` keyword is only allowed inside a block body (with braces). When using an expression body (no braces), the `return` keyword must be omitted, and the expression itself is implicitly returned. Option C incorrectly uses `return` without braces, which is a syntax error.

Exam trap

The trap here is that candidates often confuse the syntax of expression lambdas with block lambdas, mistakenly thinking `return` can be used without braces, or they forget that a single expression without `return` is implicitly returned.

How to eliminate wrong answers

Option A is valid because it uses a block body with braces and a `return` statement, which is syntactically correct. Option B is valid because it uses an expression body (no braces) that implicitly returns the result of `a + b`. Option D is valid because it uses explicit parameter types (`int a, int b`) with an expression body, which is allowed.

Option E is valid because it uses a single parameter with an expression body, and parentheses around a single parameter are optional but allowed.

61
Multi-Selecthard

Which TWO are valid uses of the 'jmod' tool in Java 17?

Select 2 answers
A.Creating a custom runtime image.
B.Listing the contents of a JMOD file.
C.Creating a JMOD file from a modular jar and native libraries.
D.Executing a JMOD file as an application.
E.Identifying module dependencies of a jar.
AnswersB, C

jmod list command lists contents of a JMOD file.

Why this answer

The 'jmod' tool is primarily used for creating and inspecting JMOD files, which are a packaging format for Java modules that can include native libraries, configuration files, and other resources beyond what a modular JAR can hold. Option B is correct because 'jmod list' lists the contents of a JMOD file, showing its entries such as classes, native code, and legal notices. Option C is correct because 'jmod create' can create a JMOD file from a modular JAR and additional native libraries using the --libs option.

Exam trap

The trap here is confusing the roles of 'jmod' (packaging) with 'jlink' (runtime image creation) and 'jdeps' (dependency analysis), leading candidates to incorrectly assign runtime image creation or dependency analysis to 'jmod'.

62
Multi-Selectmedium

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

Select 2 answers
A.Duration supports units like months and years.
B.Duration can be negative.
C.Duration is immutable and thread-safe.
D.Duration.between(LocalDate.now(), LocalDate.now()) returns a Duration.
E.Duration uses a days-based representation.
AnswersB, C

Correct: Duration can represent a negative amount of time.

Why this answer

Option B is correct because the java.time.Duration class can represent negative durations, such as when the end instant is before the start instant in a Duration.between() call. Option C is correct because all classes in the java.time package, including Duration, are immutable and thread-safe by design, ensuring safe concurrent access without synchronization.

Exam trap

The trap here is that candidates often confuse Duration with Period, assuming Duration supports months/years, or incorrectly think Duration.between() works with any date-time type like LocalDate, when it actually requires time-based temporals such as LocalTime, LocalDateTime, or Instant.

63
MCQhard

Which code correctly reads a line of text from the console using System.console()?

A.Scanner sc = new Scanner(System.in); String line = sc.nextLine();
B.Console cons = System.console(); String line = cons.readLine();
C.DataInputStream dis = new DataInputStream(System.in); String line = dis.readLine();
D.BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine();
AnswerB

Correct: Console.readLine() reads a line of input from the console.

Why this answer

Option B is correct because `System.console()` returns a `Console` object that provides a direct, secure method for reading text from the console without buffering issues. The `readLine()` method reads a line of text as a `String`, which is the intended approach when using the console API.

Exam trap

The trap here is that candidates often choose option D because `BufferedReader` is a common pattern for reading input, but they overlook that the question explicitly requires `System.console()`, not just any reader of `System.in`.

How to eliminate wrong answers

Option A is wrong because `Scanner` with `System.in` works for reading input but is not the specific API for `System.console()`, and it lacks the secure input features of `Console`. Option C is wrong because `DataInputStream.readLine()` is deprecated and does not properly handle line endings across platforms; it reads bytes, not characters, and is not intended for console input. Option D is wrong because `BufferedReader` with `InputStreamReader` is a valid way to read from `System.in`, but it is not the direct `System.console()` method; the question explicitly asks for code using `System.console()`, so this option does not meet that requirement.

64
MCQhard

A company runs a Java 17 microservice that reads stock market data from a WebSocket and processes it. The application is packaged as an executable JAR using Maven Shade Plugin. Recently, after a dependency update, the application started throwing 'javax.net.ssl.SSLHandshakeException: PKIX path building failed' when connecting to the WebSocket. The security team insists that no certificates should be imported into the default truststore. The application already includes a custom truststore file 'certs.jks' in the resources folder. The developer had been loading it programmatically but the new dependency uses a different SSL context. The application must trust the WebSocket server without modifying JVM defaults. Which action should be taken?

A.Set the system property 'javax.net.ssl.trustStore' to the path of 'certs.jks' and 'javax.net.ssl.trustStorePassword' to its password.
B.Add the certificate to the default truststore using keytool and restart the application.
C.Use the jlink tool to create a custom runtime image that includes the certificate.
D.Create a custom TrustManager that bypasses all certificate validation.
AnswerA

This tells the JVM to use the custom truststore globally.

Why this answer

Option A is correct because setting the system properties 'javax.net.ssl.trustStore' and 'javax.net.ssl.trustStorePassword' overrides the default JVM truststore globally for all SSL contexts within the application. This allows the custom 'certs.jks' file to be used without modifying the JVM's default truststore, satisfying the security team's requirement. The new dependency causing the issue likely uses the default SSL context, which will now pick up the custom truststore via these system properties.

Exam trap

The trap here is that candidates may think the system properties only affect the default SSLContext, but in practice, many libraries rely on the default SSLContext, making this a global and effective solution without modifying JVM defaults.

How to eliminate wrong answers

Option B is wrong because it directly violates the security team's explicit requirement that no certificates should be imported into the default truststore. Option C is wrong because jlink creates a custom runtime image by linking modules, but it does not provide a mechanism to inject or include a custom truststore file into the SSL context; it is used for module reduction, not for truststore configuration. Option D is wrong because creating a custom TrustManager that bypasses all certificate validation would disable SSL certificate verification entirely, creating a severe security vulnerability and violating the principle of trusting only the specific WebSocket server.

65
MCQeasy

Which of the following is a terminal operation of the Stream API?

A.map()
B.forEach()
C.filter()
D.peek()
AnswerB

Correct. forEach() is a terminal operation.

Why this answer

Option B (forEach()) is correct because it is a terminal operation in the Stream API. Terminal operations produce a result or side effect and close the stream, meaning no further operations can be performed on the same stream. forEach() consumes each element of the stream and returns void, making it a terminal operation.

Exam trap

The trap here is that candidates often confuse peek() with forEach() because both can perform actions on elements, but peek() is intermediate and does not trigger stream processing, while forEach() is terminal and does.

How to eliminate wrong answers

Option A is wrong because map() is an intermediate operation that returns a new stream after applying a function to each element; it does not close the stream. Option C is wrong because filter() is an intermediate operation that returns a new stream containing only elements that match a predicate; it does not terminate the stream. Option D is wrong because peek() is an intermediate operation designed for debugging purposes, allowing you to view elements without terminating the stream.

66
MCQhard

Refer to the exhibit. The resulting image directory includes a 'bin' directory with java launcher. When running the application, a NoClassDefFoundError occurs for a class from module com.example.lib. What is the most likely cause?

A.The --compress=2 option altered the class.
B.The application uses reflection to access the class.
C.The com.example.lib module was not added via --add-modules.
D.The --strip-debug option removed the class file.
AnswerC

Only modules explicitly added (and their transitive dependencies) are included.

Why this answer

When using jlink to create a custom runtime image, only the modules explicitly specified (or their transitive dependencies) are included. If the application depends on com.example.lib but it was not added via --add-modules, the module's classes will be missing from the image, causing a NoClassDefFoundError at runtime. This is the most direct cause among the options.

Exam trap

Oracle often tests the distinction between missing classes due to module omission (NoClassDefFoundError) versus missing classes due to reflection (ClassNotFoundException), and candidates may confuse --strip-debug with removing class files.

How to eliminate wrong answers

Option A is wrong because --compress=2 applies ZIP compression to resources in the image, not to class files, and does not alter class bytecode or cause classes to be missing. Option B is wrong because reflection does not cause NoClassDefFoundError; it may cause ClassNotFoundException if the class is absent, but the error here is specifically about a class that was expected to be present but is not, which is a module resolution issue. Option D is wrong because --strip-debug removes debugging information (like line numbers and local variable names) from class files, not the class files themselves, so the class remains available for loading.

67
MCQhard

Given a record `Point(int x, int y)`, which statement is true about the automatically generated constructor?

A.You can define a compact constructor that modifies the parameters before assignment.
B.You can define a no-arg constructor by default.
C.The generated constructor is package-private.
D.The generated constructor throws `NullPointerException` for any null component.
AnswerA

A compact constructor can perform validation or modification.

Why this answer

In Java records, you can define a compact constructor that omits the parameter list and allows you to modify the implicit parameters before they are assigned to the components. This is the only customization allowed for the canonical constructor; the compact constructor implicitly assigns the (possibly modified) parameters to the components at the end of its body.

Exam trap

The trap here is that candidates may think the compact constructor replaces the canonical constructor entirely, not realizing it still performs the implicit assignments, or they may confuse the compact constructor with a no-arg constructor or assume records have default constructors like regular classes.

How to eliminate wrong answers

Option B is wrong because records cannot have a no-arg constructor unless all components have default values, and even then you must explicitly define it; the automatically generated constructor always has the same signature as the record components. Option C is wrong because the automatically generated canonical constructor has the same access modifier as the record itself, which is public if the record is public, not package-private. Option D is wrong because the automatically generated constructor does not throw NullPointerException for null components; it simply assigns the value, and a NullPointerException would only occur later if you try to dereference a null component.

68
Drag & Dropmedium

Arrange the steps to override equals() and hashCode() correctly in Java.

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

Steps
Order

Why this order

equals() and hashCode() must be consistent: if two objects are equal, they must have the same hash code. Use Objects.hash() for hashCode().

69
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

Option D is correct because `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.

70
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

Option C is correct because 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.

71
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

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.

Page 1 of 7

Page 2

All pages