Courseiva

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

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

Page 6

Page 7 of 7

451
MCQmedium

A financial application processes millions of transactions daily. The original code uses a for loop to aggregate transactions into a Map<Long, TransactionSummary> where the key is account ID. To improve performance, a developer refactors it using parallel streams: transactions.parallelStream() .collect(Collectors.toMap( Transaction::getAccountId, Function.identity(), (t1, t2) -> t1.merge(t2), // merging logic HashMap::new )); After deployment, they observe that the resulting map is smaller than expected and some transaction summaries are missing. Profiling shows the merge function is called infrequently, suggesting that the map is losing entries. What is the most likely cause and the correct fix?

A.Remove parallelStream() and use sequential stream to avoid concurrency issues.
B.The merge function is not associative; change it to use a combiner that is associative.
C.Use forEach with a ConcurrentHashMap and putIfAbsent to manually merge.
D.Replace HashMap::new with ConcurrentHashMap::new in the collector.
AnswerD

In parallel streams, the default toMap collector uses HashMap which is not thread-safe. ConcurrentHashMap allows safe concurrent insertion and merging.

Why this answer

The issue is that `HashMap::new` is not thread-safe. When `parallelStream()` splits the stream into multiple threads, each thread creates its own `HashMap` for partial results. These partial maps are then merged using the collector's combiner, but `HashMap` does not guarantee thread safety during concurrent access or merging.

Using `ConcurrentHashMap::new` ensures that the map can be safely populated and combined across threads, preventing lost entries. The merge function itself is associative (merging two summaries into one), so the problem is purely the thread-unsafe map supplier.

Exam trap

Oracle often tests the misconception that the merge function must be associative when the real culprit is the thread-unsafe map supplier in parallel stream collectors.

How to eliminate wrong answers

Option A is wrong because removing parallelism is unnecessary; the core issue is the thread-unsafe map supplier, not parallelism itself. Option B is wrong because the merge function `(t1, t2) -> t1.merge(t2)` is associative (merging is order-independent) and not the cause of missing entries. Option C is wrong because using `forEach` with `ConcurrentHashMap` and `putIfAbsent` would work but is a manual, less idiomatic approach; the correct fix is to simply supply a thread-safe map to the collector, which is simpler and preserves the parallel stream's performance benefits.

452
MCQeasy

A developer runs `java --list-modules` and sees the above output on a standard JDK installation. What does this output represent?

A.The modules that are part of the java.base module.
B.The modules that are required by the current application.
C.The set of modules available in the current JDK.
D.The modules that are currently loaded by the JVM.
AnswerC

It lists all modules that can be resolved.

Why this answer

The `java --list-modules` command outputs the names of all observable modules that are part of the current JDK installation. This includes all platform modules (e.g., `java.base`, `java.sql`, `jdk.compiler`) that are available for use, regardless of whether they are currently required or loaded by an application. Option C correctly identifies this as the set of modules available in the current JDK.

Exam trap

The trap here is that candidates confuse 'available modules' with 'loaded modules' or 'required modules', because in everyday development, the modules used by an application are often a subset of those available, but `--list-modules` shows the full set of observable modules in the JDK, not the runtime state.

How to eliminate wrong answers

Option A is wrong because `java.base` is just one specific module, not the list of all modules; `--list-modules` shows all platform modules, not just those in `java.base`. Option B is wrong because the command does not depend on any application; it lists all modules in the JDK, not only those required by the current application. Option D is wrong because `--list-modules` shows available modules, not currently loaded modules; modules are loaded lazily by the JVM at runtime, and this command does not trigger loading.

453
MCQmedium

What is the output when this code is executed? ```java int x = 2; switch (x) { case 1: System.out.print("One "); case 2: System.out.print("Two "); case 3: System.out.print("Three "); break; default: System.out.print("Default"); } ```

A.Two Three
B.Two
C.Two Three Default
D.One Two Three
AnswerA

Correct, falls through to case 3 then breaks.

Why this answer

The switch statement matches the value 2, so it executes the case 'Two' block, which prints 'Two ' and then falls through to the next case because there is no break statement. The case 'Three' block prints 'Three ' and then breaks, exiting the switch. The default case is skipped because a matching case was found and the break in case 'Three' prevents further fall-through.

Thus, the output is 'Two Three '.

Exam trap

The trap here is that candidates often forget that missing break statements cause fall-through, leading them to think only the matched case executes, or they incorrectly assume the default case always runs at the end.

How to eliminate wrong answers

Option B is wrong because it assumes that after printing 'Two', the switch exits without falling through to case 'Three', but without a break statement, fall-through occurs. Option C is wrong because it includes 'Default' in the output, but the default case is only executed if no matching case is found; here, case 2 matches, so default is skipped. Option D is wrong because it suggests that case 'One' also executes, but the switch starts matching from the value 2, so case 'One' is never entered.

454
Multi-Selectmedium

Which THREE statements about the switch statement in Java are correct?

Select 3 answers
A.The default case can be placed anywhere within the switch block.
B.Case values can be runtime expressions.
C.A break statement is mandatory after each case block.
D.Case labels can be variables if they are final and assigned a constant expression.
E.The switch statement can be used with int, char, String, and enum types.
AnswersA, D, E

Correct. The default case can appear anywhere in the switch block.

Why this answer

The default case can be placed anywhere within the switch block according to the Java Language Specification. Option D is correct: case labels must be compile-time constant expressions; a final variable assigned a constant expression qualifies as a compile-time constant. Option E is correct: switch works with int, char, String, and enum types.

Option B is incorrect because case values must be compile-time constants, not arbitrary runtime expressions. Option C is incorrect because break is not mandatory; it is optional and used to prevent fall-through.

Exam trap

The trap here is that candidates often assume the default case must be last, or that break is always required, or that any final variable can be used as a case label, when in fact only compile-time constant expressions are allowed.

455
Drag & Dropmedium

Arrange the steps to read a file using NIO.2 Files.lines() in Java.

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

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

Why this order

Files.lines() returns a Stream that must be closed to release file handles. The stream is lazily populated.

456
MCQhard

A financial trading system uses a Java application to process market data. The core algorithm uses nested loops to compare price arrays. The developer uses a labeled continue statement to skip certain combinations. After a code review, the team suspects the algorithm has a bug that causes incorrect results. The developer writes a unit test and discovers that the labeled continue sometimes skips more iterations than intended. The code is: outer: for (int i = 0; i < prices1.length; i++) { for (int j = 0; j < prices2.length; j++) { if (prices1[i] < prices2[j]) continue outer; // process combination } } The developer intended that if any price in prices1 is less than a price in prices2, the entire row (i) should be skipped. However, the algorithm skips rows even when the condition is not met for all j. What is the most likely cause?

A.A break statement is missing after processing a combination.
B.The label outer is placed on the inner loop, not the outer loop.
C.The condition for continuing is not correctly evaluated.
D.The continue outer statement should be a break outer.
AnswerC

Correct. The condition checks for any j, but the intent was to skip only when the condition holds for all j. Thus the condition is not correctly evaluated.

Why this answer

The developer intended to skip the i-th row only if for every j, prices1[i] < prices2[j]. However, the condition currently uses an inequality that triggers on any j, causing rows to be skipped prematurely. The bug is that the condition is not correctly evaluating the intended logic; it should check that the condition holds for all j, not just one.

Therefore, the correct answer is C.

Exam trap

The trap is that candidates may think a labeled continue always affects a loop outside the current one, but in Java the label identifies which loop to continue. Placing the label on the inner loop means the continue targets that inner loop, not the outer loop. This leads to unexpected behavior where only a single inner iteration is skipped instead of the entire outer row.

How to eliminate wrong answers

Option A is wrong because a break statement after processing a combination would exit the inner loop entirely, not skip rows conditionally; the issue is about skipping too many iterations, not missing a break. Option C is wrong because the condition `prices1[i] < prices2[j]` is correctly evaluated; the bug is in the control flow, not the condition logic. Option D is wrong because `break outer` would exit the outer loop entirely, terminating all processing, which is not the intended behavior of skipping a row.

457
MCQhard

You are a software architect at a financial firm. Your team is developing a modular Java 17 application that comprises several modules: 'com.bank.core' (provides core banking services), 'com.bank.web' (REST API), and 'com.bank.persistence' (database access). The application uses the 'java.sql' module for JDBC and 'java.logging' for logging. The team uses Maven for dependency management. The application has an external dependency on the 'com.fasterxml.jackson.databind' library (Jackson) for JSON processing, which is provided as a non-modular jar. The Jackson jar is placed on the module path. The application modules are all named modules with module-info files. At runtime, the 'com.bank.web' module requires 'com.bank.core' and 'com.fasterxml.jackson.databind' (the automatic module). The 'com.bank.core' module requires 'java.sql' and 'java.logging'. When the application runs, it throws an 'IllegalAccessError' indicating that the module 'com.bank.core' tries to access a class from 'com.fasterxml.jackson.databind' but the module does not read it. Yet, 'com.bank.web' is the only module that explicitly requires Jackson. What is the most likely cause and the correct resolution?

A.Convert all application modules to unnamed modules by removing module-info files.
B.Add 'requires com.fasterxml.jackson.databind' to the module-info.java of 'com.bank.core' because it uses Jackson classes directly.
C.Place the Jackson jar on the classpath instead of the module path.
D.Use jlink to create a custom runtime image including all modules and the Jackson jar.
AnswerB

Direct use requires a requires directive; this resolves the readability chain.

Why this answer

The error indicates that 'com.bank.core' directly uses classes from 'com.fasterxml.jackson.databind', but its module-info.java does not include a 'requires com.fasterxml.jackson.databind' directive. In the Java module system, a module can only access types from another module if it explicitly reads that module. Since 'com.bank.core' needs Jackson classes at runtime, it must declare the dependency itself, even if another module ('com.bank.web') also requires it.

Exam trap

The trap here is that candidates assume transitive dependencies are automatically resolved by the module system, but in Java modules, each module must explicitly declare its own 'requires' for any module it directly uses, even if another module already requires it.

How to eliminate wrong answers

Option A is wrong because converting all modules to unnamed modules by removing module-info files would defeat the purpose of modularization, breaking encapsulation and potentially causing classpath conflicts; it does not fix the missing 'requires' directive. Option C is wrong because placing the Jackson jar on the classpath instead of the module path would make it an unnamed module, which would still not grant 'com.bank.core' read access to Jackson's packages unless the module reads the unnamed module (via 'requires java.base' or '--add-reads'), and it would also lose the benefits of reliable configuration. Option D is wrong because using jlink to create a custom runtime image does not resolve the missing module readability; jlink only includes modules that are explicitly required, and if 'com.bank.core' does not require Jackson, the error persists.

458
MCQmedium

Refer to the exhibit. Which concept does this error relate to?

A.ISO week date
B.Time zone offsets
C.Daylight Saving Time
D.Leap seconds
AnswerD

Correct: 60 seconds is a leap second, which is not valid in java.time parsing.

Why this answer

The error relates to leap seconds because the exhibit (not shown here) likely involves a date-time calculation or parsing failure caused by the extra second (23:59:60) that is occasionally inserted into UTC to keep atomic time in sync with astronomical time. Java's `java.time` API, such as `LocalTime.parse()`, does not handle the 60th second, throwing a `DateTimeException` when encountering a leap second value.

Exam trap

Oracle often tests the distinction between Daylight Saving Time (hour shifts) and leap seconds (second shifts), trapping candidates who confuse the two because both involve 'adjusting time' but at fundamentally different granularities.

How to eliminate wrong answers

Option A is wrong because ISO week date (e.g., '2023-W01-1') is a calendar system that defines weeks and days, not a source of parsing errors related to a 60th second. Option B is wrong because time zone offsets (e.g., +05:30) represent fixed differences from UTC and do not introduce an extra second in the minute. Option C is wrong because Daylight Saving Time involves shifting clocks forward or backward by one hour, not inserting or removing a single second.

459
MCQmedium

A team uses a TreeSet with a custom Comparable that returns 0 for objects that are not logically equal (e.g., based on one field but objects differ in another). What is the likely outcome when adding such objects?

A.The second object is not added because TreeSet considers it a duplicate
B.The second object replaces the first
C.A ClassCastException is thrown
D.Both objects are added and insertion order is preserved
AnswerA

TreeSet uses compareTo for equality; returning 0 means duplicate.

Why this answer

TreeSet uses the compareTo() method of the Comparable interface (or Comparator) to determine ordering and equality. When compareTo() returns 0 for two objects that are not logically equal (e.g., they share the same field used in comparison but differ in other fields), TreeSet treats them as duplicates and does not add the second object. This is because TreeSet relies on the comparison result, not the equals() method, for uniqueness.

Exam trap

The trap here is that candidates assume TreeSet uses equals() for duplicate detection, but it actually uses compareTo()/compare(), so objects that are not logically equal can be incorrectly treated as duplicates if the comparison method returns 0.

How to eliminate wrong answers

Option B is wrong because TreeSet never replaces an existing element; it simply refuses to add a duplicate when compareTo() returns 0. Option C is wrong because no ClassCastException occurs unless the objects are not mutually comparable (e.g., different types without a shared Comparable implementation), which is not the case here. Option D is wrong because TreeSet does not preserve insertion order; it maintains elements in sorted order according to the Comparable/Comparator, and duplicates are not added at all.

460
MCQmedium

When should LinkedList be preferred over ArrayList?

A.Frequent random access by index
B.Fast iteration over all elements
C.Minimal memory overhead
D.Frequent insertions and deletions at arbitrary positions
AnswerD

LinkedList has O(1) operations if position known via iterator.

Why this answer

LinkedList is preferred over ArrayList when frequent insertions and deletions occur at arbitrary positions because LinkedList uses a doubly-linked list structure, allowing O(1) time for insertions/deletions once the node is located, whereas ArrayList requires shifting elements (O(n)) due to its underlying array. This makes D correct for scenarios with heavy modification in the middle of the list.

Exam trap

The trap here is that candidates assume LinkedList is always faster for insertions/deletions anywhere, overlooking that random access by index is O(n) and that the overhead of finding the insertion point can make ArrayList more efficient in practice for many use cases.

How to eliminate wrong answers

Option A is wrong because LinkedList provides O(n) random access by index (traversing from head/tail), while ArrayList offers O(1) index-based access via its array backing. Option B is wrong because fast iteration over all elements is equally efficient for both (O(n)), but ArrayList has better cache locality and lower overhead per element, making it generally faster for iteration. Option C is wrong because LinkedList has higher memory overhead due to storing node objects with forward and backward pointers (typically 24+ bytes per element), whereas ArrayList stores elements in a compact contiguous array with minimal overhead.

461
MCQmedium

A developer adds .peek(System.out::println) to a stream pipeline to debug, but no output is printed. What is the most likely reason?

A.The stream is parallel
B.The pipeline lacks a terminal operation
C.The peek operation is placed after the terminal operation
D.The stream is empty
AnswerB

Correct. Without a terminal operation, the pipeline never executes, so peek never runs.

Why this answer

Stream pipelines are lazy; intermediate operations like peek() are only executed when a terminal operation (e.g., forEach, collect, reduce) is invoked. Without a terminal operation, the pipeline never starts processing data, so peek() produces no output.

Exam trap

The trap here is that candidates assume intermediate operations execute eagerly or that peek() works like a standalone print statement, overlooking the fundamental lazy-evaluation contract of streams.

How to eliminate wrong answers

Option A is wrong because parallelism does not prevent peek from printing; it would still print, though possibly interleaved. Option C is wrong because peek cannot be placed after a terminal operation; terminal operations end the pipeline, so any operation after them would cause a compilation error. Option D is wrong because an empty stream would still cause peek to execute (it would simply not print anything), but the question states no output is printed, implying the pipeline never ran.

462
Multi-Selecteasy

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

Select 2 answers
A.A break statement is optional.
B.A switch statement can be used as an expression in all cases.
C.The switch expression can be of type long.
D.The switch expression can be of type String.
E.The case values can be variables.
AnswersA, D

Without break, execution falls through to the next case.

Why this answer

In a Java switch statement, the break statement is optional. If omitted, execution falls through to the next case (fall-through behavior), which can be intentional or lead to bugs. This is a core feature of the switch construct, not a requirement.

Exam trap

The trap here is that candidates often assume break is mandatory in all switch constructs, or they mistakenly think long is a valid switch type because it is a numeric primitive, but Java explicitly excludes long from switch expressions.

463
Multi-Selecthard

Which TWO statements about Java interfaces are true? (Choose two.)

Select 2 answers
A.An interface can extend at most one other interface.
B.Fields in an interface can be declared as protected.
C.Interfaces can contain static methods with a body.
D.Interfaces can contain private methods.
E.Default methods are used to prevent method overriding.
AnswersC, D

Static methods in interfaces are allowed since Java 8.

Why this answer

Since Java 8, interfaces can contain static methods with a body. These static methods belong to the interface itself and are not inherited by implementing classes, allowing utility methods to be defined directly within the interface.

Exam trap

The trap here is that candidates often assume interfaces follow the same single-inheritance rule as classes, or that static methods in interfaces cannot have a body, or that default methods prevent overriding, leading them to select incorrect options A, B, or E.

464
MCQmedium

Which of the following correctly formats a LocalDateTime object into a string with pattern 'dd/MM/yyyy HH:mm:ss'?

A.DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").format(dateTime)
B.String.format("%1$td/%1$tm/%1$tY %1$tH:%1$tM:%1$tS", dateTime)
C.new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(dateTime)
D.dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
AnswerA

Correct: DateTimeFormatter.ofPattern creates a formatter for the custom pattern, and format works with LocalDateTime.

Why this answer

`DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")` creates a formatter with the specified pattern, and calling `.format(dateTime)` on that formatter converts a `LocalDateTime` object to a string in the exact requested format. This is the standard approach in Java 8+ using the `java.time` API, which is thread-safe and immutable.

Exam trap

The trap here is that candidates may confuse the legacy `SimpleDateFormat` (which works with `java.util.Date`) with the modern `DateTimeFormatter` (which works with `java.time.LocalDateTime`), or assume `String.format` can directly format `LocalDateTime` without realizing it requires a `Date` object.

How to eliminate wrong answers

Option B is wrong because `String.format` with `%t` conversion specifiers expects a `Date` or `Calendar` object, not a `LocalDateTime`; it will cause a runtime `IllegalFormatConversionException`. Option C is wrong because `SimpleDateFormat` works with `java.util.Date`, not `java.time.LocalDateTime`, and using it would require conversion and is not type-safe; it also represents the legacy API that is error-prone and non-thread-safe. Option D is wrong because `DateTimeFormatter.ISO_LOCAL_DATE_TIME` produces the ISO-8601 format like '2025-03-15T14:30:00', not the custom pattern 'dd/MM/yyyy HH:mm:ss'.

465
Multi-Selectmedium

Which two of the following are valid ways to exit a loop in Java?

Select 2 answers
A.label break
B.continue
C.break
D.System.exit(0)
E.throw new Exception()
AnswersA, C

A labeled break can exit a specific outer loop.

Why this answer

A labeled break statement allows you to exit an outer loop from within a nested loop by specifying the label of the outer loop. This is a valid control flow mechanism in Java, as defined in the Java Language Specification (JLS §14.15).

Exam trap

The trap here is that candidates often confuse 'continue' with 'break' or think that System.exit(0) or throwing an exception are valid loop exit mechanisms, when in fact only 'break' (and labeled break) are designed specifically for that purpose.

466
Multi-Selectmedium

Which THREE statements are true about the Java Platform editions? (Select three.)

Select 3 answers
A.Java ME provides a subset of Java SE APIs for embedded devices.
B.Java SE (Standard Edition) provides the core APIs for developing general-purpose Java applications.
C.Java ME (Micro Edition) is the same as Android SDK.
D.Java EE (now Jakarta EE) extends Java SE with APIs for distributed computing and web services.
E.Java SE includes a full application server for enterprise applications.
AnswersA, B, D

Java ME is designed for small devices with limited resources.

Why this answer

Java ME (Micro Edition) is designed for resource-constrained devices like sensors, mobile phones, and embedded systems. It provides a subset of the Java SE APIs, along with additional APIs tailored for small devices, such as the Connected Limited Device Configuration (CLDC) and the Mobile Information Device Profile (MIDP). This allows developers to write Java applications that run on devices with limited memory, processing power, and display capabilities.

Exam trap

The trap here is confusing Java ME with Android's SDK, as both target mobile/embedded devices, but Android uses a completely different runtime and API set, while Java ME is a standardized Java platform under the Java Community Process (JCP).

467
Matchingmedium

Match each Java 17 feature to its description.

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

Concepts
Matches

Restricts which classes can extend or implement a type

Allows patterns in case labels for type checks and destructuring

Transparent carriers for immutable data

Multi-line string literals with automatic formatting

Switch that can be used as an expression and returns a value

Why these pairings

These are key features introduced or enhanced in recent Java versions including 17.

468
Matchingmedium

Match each concurrency utility to its purpose.

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

Concepts
Matches

Allows one or more threads to wait until a count reaches zero

Allows a set of threads to wait for each other to reach a common barrier point

Controls access to a resource via a permit system

Allows two threads to exchange objects at a synchronization point

A reusable barrier that supports dynamic number of parties

Why these pairings

This question tests understanding of common concurrency utilities in java.util.concurrent such as CountDownLatch, CyclicBarrier, Semaphore, and Exchanger. A common mistake is confusing CountDownLatch (one-time use) with CyclicBarrier (reusable) and mixing up Semaphore's permit-based control with barrier synchronization.

469
MCQeasy

Refer to the exhibit. What is the result?

A.abc
B.NullPointerException
C.IllegalStateException
D.abcabc
AnswerC

Correct. A stream cannot be reused after a terminal operation.

Why this answer

The code attempts to call `findAny()` on a `Stream` that has already been consumed by a terminal operation (`forEach`). Once a terminal operation is executed on a stream, the stream is closed and cannot be reused. Any subsequent call to a terminal operation on the same stream reference throws `IllegalStateException`.

Option C is correct because the second terminal operation violates the single-use contract of streams.

Exam trap

Oracle Java 17 exams often test the misconception that a stream can be reused like a collection, leading candidates to expect multiple traversals or to overlook the single-use contract enforced by the Stream API.

How to eliminate wrong answers

Option A is wrong because the stream is consumed by the first `forEach`, so the second `forEach` never executes, and `abc` is printed only once, not as the final result. Option B is wrong because `NullPointerException` would only occur if the stream source or an element were null, but here the stream is valid and the elements are non-null strings. Option D is wrong because `abcabc` would require the stream to be traversed twice, which is impossible since a stream cannot be reused after a terminal operation.

470
MCQhard

A stream pipeline filters strings, sorts them, and returns the first match: .filter(s -> s.length() > 3).sorted().findFirst(). This is inefficient because sorted() processes all elements. Which alternative achieves the same result with better performance?

A..filter(s -> s.length() > 3).min(Comparator.naturalOrder())
B..filter(s -> s.length() > 3).sorted().limit(1).findFirst()
C..filter(s -> s.length() > 3).parallel().sorted().findFirst()
D..filter(s -> s.length() > 3).sorted().collect(Collectors.toList()).get(0)
AnswerA

min() uses a reduction that processes each element once, maintaining the minimum without sorting.

Why this answer

`min(Comparator.naturalOrder())` is a terminal operation that finds the smallest element according to natural ordering without sorting the entire stream. It uses a single pass reduction, which is O(n) in time complexity, whereas `sorted().findFirst()` must sort all elements (O(n log n)) before picking the first. This makes `min()` significantly more efficient for this use case.

Exam trap

The trap here is that candidates often assume `sorted().findFirst()` is optimized to stop early, but in Java streams, `sorted()` is a stateful intermediate operation that must process all elements before any downstream operation can begin, making it inherently inefficient for finding a single minimum or maximum.

How to eliminate wrong answers

Option B is wrong because `sorted().limit(1).findFirst()` still requires sorting all elements before limiting, so it does not improve performance over the original. Option C is wrong because `parallel().sorted().findFirst()` adds parallelism overhead and still sorts all elements, and `findFirst()` is a short-circuiting operation that may not benefit from parallelism due to ordering constraints. Option D is wrong because `sorted().collect(Collectors.toList()).get(0)` materializes the entire sorted list into memory before retrieving the first element, which is even less efficient than the original pipeline.

471
MCQeasy

What is the output of the following code? ```java int i = 5; while (i > 0) { System.out.print(i + " "); i--; } ```

A.5 4 3 2 1
B.The code does not compile because i is not declared final.
C.5 4 3 2
D.4 3 2 1
AnswerA

Correct countdown from 5 to 1.

Why this answer

The while loop runs as long as i > 0. Starting with i = 5, each iteration prints the current value of i followed by a space, then decrements i by 1. The loop stops when i becomes 0, so the output is '5 4 3 2 1 '.

Exam trap

The trap here is that candidates might think the loop stops before printing the last value (1) or that the decrement happens before printing, leading them to choose options C or D.

How to eliminate wrong answers

Option B is wrong because the code compiles and runs correctly; there is no requirement for i to be declared final in a while loop. Option C is wrong because it omits the final value 1, but the loop prints i before decrementing, so when i = 1, it prints 1, then i becomes 0 and the loop exits. Option D is wrong because it starts at 4 instead of 5, but the initial value of i is 5, and the first iteration prints 5.

472
MCQmedium

A company needs to read a large text file (over 2 GB) line by line in a Java application while minimizing memory footprint. Which approach is most efficient?

A.Use Files.readAllLines(path)
B.Use FileOutputStream with read() loop
C.Use Scanner with File and loop hasNextLine()
D.Use Files.lines(path) with try-with-resources
AnswerD

Lazy stream reading minimizes memory; auto-closes resource.

Why this answer

`Files.lines(path)` returns a `Stream<String>` that lazily reads lines from the file, processing them one at a time without loading the entire file into memory. Combined with try-with-resources, the underlying `BufferedReader` is automatically closed, ensuring efficient resource management even for files over 2 GB.

Exam trap

The trap here is that candidates often choose `Scanner` (Option C) because it is familiar from simple file reading, but they overlook its higher memory overhead and lack of automatic resource management compared to the stream-based `Files.lines()` with try-with-resources.

How to eliminate wrong answers

Option A is wrong because `Files.readAllLines(path)` reads the entire file into a `List<String>` in memory, which would cause an `OutOfMemoryError` for a file over 2 GB. Option B is wrong because `FileOutputStream` is designed for binary byte output, not reading text; using its `read()` method would require manual byte-to-character conversion and lacks line-by-line parsing, making it inefficient and error-prone for text files. Option C is wrong because `Scanner` with `hasNextLine()` internally buffers the file and can be slower for large files due to its regex-based tokenization overhead, and it does not leverage the optimized lazy streaming of `Files.lines()`.

473
MCQmedium

```java int count = 0; for (int i = 0; i < 5; ++i) { if (i == 3) break; count++; } System.out.println(count); ``` What is the output?

A.4
B.3
C.5
D.Compilation error
AnswerB

Correct: break at i=3 prevents further increment.

Why this answer

The code uses a loop that increments a variable count. It breaks when a certain condition (e.g., when a loop index equals 3) is met, after counting three iterations. Therefore, the output is 3.

Exam trap

The trap here is that candidates often miscount loop iterations by including the iteration where `break` occurs, forgetting that `break` exits before the loop body's remaining statements (including `count++`) execute.

How to eliminate wrong answers

Option A is wrong because it assumes the loop completes all five iterations (0 through 4) without considering the `break` statement, leading to a count of 4 instead of 3. Option C is wrong because it incorrectly counts the iteration where `i == 3` as executing the increment, but `break` exits before `count++` runs for that iteration, so the count is 3, not 5. Option D is wrong because there is no compilation error; the code is syntactically valid with proper loop syntax and a `break` statement inside an `if`.

474
MCQhard

A developer runs 'jdeps -s --module-path lib myapp.jar' and gets output: 'myapp.jar -> java.base, myapp.jar -> java.sql, myapp.jar -> notfound'. What does the 'notfound' entry indicate?

A.The application has a dependency on a package that is not provided by any module on the module path.
B.The dependency is resolved but its module name is not printed due to a summary flag.
C.The jar file is missing or corrupt.
D.There is a cyclic dependency among modules.
AnswerA

The 'notfound' indicates an unknown dependency that cannot be resolved to any module.

Why this answer

The 'notfound' entry in the jdeps -s output indicates that the application has a dependency on a package that is not provided by any module on the module path. The -s (summary) flag shows module-level dependencies, and when a required module cannot be located among the specified modules or the JDK's built-in modules, jdeps reports it as 'notfound'. This means the dependency cannot be resolved at analysis time, typically because the required module is missing from the module path.

Exam trap

The trap here is that candidates may confuse 'notfound' with a missing JAR file or a corrupt archive, but jdeps specifically reports unresolved module dependencies, not file system errors.

How to eliminate wrong answers

Option B is wrong because the -s (summary) flag does not suppress module names; it merely shortens the output to show only module-level dependencies without package details, so a resolved dependency would still show its module name. Option C is wrong because a missing or corrupt JAR file would cause jdeps to fail with an error message, not produce a 'notfound' entry in the dependency output. Option D is wrong because cyclic dependencies among modules are reported differently by jdeps (e.g., with a cycle warning), not as 'notfound'.

475
MCQmedium

A developer runs the above jdeps command on app.jar. Which statement about the dependencies is correct?

A.The app.jar has a direct dependency on the class com.thirdparty.util.
B.The modular dependency com.thirdparty.helper is not required because it is modular.
C.The dependencies on com.thirdparty.util and com.thirdparty.helper are on the module path.
D.The app.jar depends on java.base implicitly.
AnswerD

All Java applications implicitly depend on java.base.

Why this answer

Every Java module automatically has an implicit dependency on the `java.base` module, which is always resolved by the module system. The `jdeps` command analyzes dependencies, and even if no explicit `requires java.base` is declared, the module system adds it implicitly. This is a fundamental rule of the Java Platform Module System (JPMS) as defined in JSR 376.

Exam trap

Oracle often tests the implicit dependency on `java.base` to catch candidates who think all module dependencies must be explicitly declared in `module-info.java`.

How to eliminate wrong answers

Option A is wrong because `jdeps` output shows dependencies at the package level, not the class level; it would report a dependency on the package `com.thirdparty.util`, not on a specific class. Option B is wrong because whether a dependency is modular or not does not affect whether it is required; if `app.jar` uses types from `com.thirdparty.helper`, it must have a direct or transitive dependency on that module, regardless of its modular status. Option C is wrong because `jdeps` does not indicate whether dependencies are on the module path; it only reports the dependencies found, not their location (module path vs. class path).

476
MCQeasy

A developer needs to iterate over an ArrayList of integers and remove all elements that are less than 10. Which approach is best to avoid ConcurrentModificationException?

A.Use a for loop with index and list.remove(index) decrementing index.
B.Use an Iterator with iterator.remove().
C.Use a for-each loop with list.remove().
D.Use list.removeIf() with a lambda expression.
AnswerD

removeIf is the cleanest and safest way; it uses an internal iterator and avoids ConcurrentModificationException.

Why this answer

`list.removeIf()` is a built-in method introduced in Java 8 that safely removes elements from a collection based on a predicate, handling all iteration and modification internally without throwing ConcurrentModificationException. It uses an internal iterator that properly coordinates structural modifications, making it the most concise and reliable approach for this task.

Exam trap

The trap here is that candidates often choose the Iterator approach (Option B) because they know it avoids ConcurrentModificationException, but they overlook that `removeIf()` is the more modern, concise, and recommended method for such bulk removal operations in Java.

How to eliminate wrong answers

Option A is wrong because using a for loop with index and `list.remove(index)` while decrementing the index can still cause issues if not carefully managed (e.g., shifting elements), and it is error-prone and less efficient than the dedicated removal methods. Option B is wrong because while `Iterator.remove()` is safe and avoids ConcurrentModificationException, it is more verbose and not the 'best' approach compared to `removeIf()`, which is simpler and more expressive. Option C is wrong because using a for-each loop with `list.remove()` directly modifies the list during iteration, which throws ConcurrentModificationException as the for-each loop uses an internal iterator that detects concurrent modification.

477
Multi-Selectmedium

Which THREE conditions must be true for a method to override another method in a subclass? (Choose three.)

Select 3 answers
A.The method must be static in the superclass.
B.The access modifier must be the same or more restrictive.
C.The method name must be the same.
D.The parameter list must be the same.
E.The return type must be the same or a subtype (covariant return type).
AnswersC, D, E

Overriding requires same method name.

Why this answer

Method overriding requires the subclass method to have exactly the same name as the superclass method. This is a fundamental rule of polymorphism in Java, ensuring that the JVM can correctly resolve the overridden method at runtime based on the method signature.

Exam trap

Oracle often tests the misconception that overriding requires the same or more restrictive access, but the correct rule is the opposite: the overriding method must have the same or more accessible (less restrictive) access modifier.

478
MCQhard

A class implements Serializable but the developer wants to completely prevent deserialization of its instances. Which approach accomplishes this?

A.Override readResolve() to return a null.
B.Override readObject() to throw an InvalidClassException.
C.Override writeObject() to encrypt the object.
D.Override writeReplace() to throw an exception.
AnswerB

This causes deserialization to fail immediately.

Why this answer

Overriding readObject() to throw an InvalidClassException (or any exception) prevents the deserialization mechanism from completing. When an ObjectInputStream calls readObject() on a class that defines its own readObject() method, that custom method is invoked instead of the default deserialization. Throwing an exception inside readObject() aborts the deserialization process, effectively blocking the reconstruction of the instance.

Exam trap

The trap here is that candidates often confuse readResolve() with readObject(), thinking that returning null from readResolve() prevents deserialization, when in fact readResolve() runs after the object is already created, so it does not stop the deserialization process itself.

How to eliminate wrong answers

Option A is wrong because overriding readResolve() to return null does not prevent deserialization; readResolve() is called after the object is already deserialized, and returning null simply replaces the deserialized object with null, but the object has already been created in memory. Option C is wrong because overriding writeObject() to encrypt the object only affects serialization, not deserialization; the attacker can still call readObject() on the encrypted stream if they have the decryption key or bypass the encryption entirely. Option D is wrong because overriding writeReplace() to throw an exception only prevents serialization (writing), not deserialization; the developer wants to prevent deserialization, and writeReplace() is invoked during serialization, not during reading.

479
MCQhard

An architect is designing a microservice that reads large CSV files (up to 500 MB) from a shared filesystem and processes each row. The processing is CPU-bound and must not block the main thread. The service is deployed in a container with limited memory (512 MB heap). Which approach is most suitable?

A.Use Files.readAllLines() to read the entire file into memory, then process in parallel using streams.
B.Use a BufferedReader on a separate thread, reading lines into a bounded queue, and a thread pool to process rows from the queue.
C.Use a FileChannel with a memory-mapped byte buffer of the entire file.
D.Use a java.nio.file.FileSystem with a WatchService to detect changes to the file.
AnswerB

This approach reads line by line, using a bounded queue to decouple reading and processing.

Why this answer

It uses a bounded blocking queue to decouple I/O (reading lines from the CSV) from CPU-bound processing, preventing the main thread from being blocked while also avoiding memory exhaustion. The bounded queue acts as a back-pressure mechanism, ensuring that the limited 512 MB heap is not overwhelmed by the 500 MB file. Processing rows via a thread pool allows parallel CPU-bound work without blocking the reading thread.

Exam trap

The trap here is that candidates often assume memory-mapped files (FileChannel) are always efficient for large files, but they ignore the memory constraint and the need to keep the main thread responsive; Oracle tests whether you understand that bounded queues and separate threads are required for back-pressure and non-blocking processing in constrained environments.

How to eliminate wrong answers

Option A is wrong because Files.readAllLines() loads the entire file into memory as a List<String>, which would require at least 500 MB (plus overhead for String objects and UTF-16 encoding) and likely cause an OutOfMemoryError with a 512 MB heap. Option C is wrong because memory-mapping the entire file with a FileChannel would still map the full 500 MB into virtual memory, consuming significant heap or native memory and risking memory pressure; it also does not inherently offload CPU-bound processing to a separate thread. Option D is wrong because a WatchService is designed for monitoring file system changes (e.g., modifications, deletions) and has no role in reading or processing file contents; it would not help with reading or processing the CSV rows.

480
MCQeasy

Which statement about java.io and java.nio.file packages is true?

A.The java.nio.file package provides support for symbolic links and file attributes
B.Classes in java.nio.file are thread-safe by default
C.The java.io package includes the Path interface
D.The java.nio.file package is deprecated in favor of java.io
AnswerA

NIO.2 includes methods for creating symbolic links and reading file attributes.

Why this answer

The java.nio.file package (part of NIO.2) explicitly provides support for symbolic links via methods like Files.createSymbolicLink() and Files.isSymbolicLink(), and it offers comprehensive file attribute access through classes like BasicFileAttributes, DosFileAttributes, and PosixFileAttributes, which are not available in java.io.

Exam trap

The trap here is that candidates often confuse the legacy java.io.File class with the modern java.nio.file.Path interface, assuming Path is in java.io because both deal with files, or they mistakenly think java.nio.file is deprecated due to its 'nio' naming, when in fact it is the recommended API.

How to eliminate wrong answers

Option B is wrong because classes in java.nio.file are not thread-safe by default; while some operations may be atomic, the API does not guarantee thread safety for all methods, and concurrent access requires external synchronization. Option C is wrong because the Path interface is part of the java.nio.file package, not java.io; java.io contains File, which is a legacy class. Option D is wrong because java.nio.file is not deprecated; it is the modern replacement for java.io, offering improved performance and features, and java.io itself is not deprecated but is considered legacy for many use cases.

481
MCQeasy

A developer is designing a method that returns an immutable list of strings from an array. Which approach best follows current Java best practices?

A.Return new ArrayList<>(Arrays.asList(array))
B.Return Collections.unmodifiableList(Arrays.asList(array))
C.Return Arrays.asList(array)
D.Return List.of(array)
AnswerD

List.of returns an immutable list, introduced in Java 9, and rejects nulls, making it the best practice.

Why this answer

`List.of(array)` returns an immutable list that is null-hostile and structurally immutable, as specified by the Java Platform Module System (JPMS) and the `List` interface since Java 9. This approach aligns with current best practices by providing a concise, safe, and predictable immutable collection without the overhead of wrapping or defensive copying.

Exam trap

The trap here is that candidates often confuse `Arrays.asList()` (which returns a mutable, array-backed list) with an immutable list, or they think `Collections.unmodifiableList()` provides full immutability, but it only prevents modification through the returned reference while the underlying array remains mutable.

How to eliminate wrong answers

Option A is wrong because `new ArrayList<>(Arrays.asList(array))` creates a mutable, modifiable list, not an immutable one, and also incurs unnecessary copying overhead. Option B is wrong because `Collections.unmodifiableList(Arrays.asList(array))` returns a view that is unmodifiable but still backed by the original array, meaning changes to the array (if passed elsewhere) can affect the list, and it does not enforce null-hostility. Option C is wrong because `Arrays.asList(array)` returns a fixed-size list backed by the original array, which is mutable (via `set`), not immutable, and allows null elements.

482
MCQmedium

A developer needs to copy a large directory tree from one location to another, preserving file attributes. Which method should be used?

A.Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES)
B.Implement a FileVisitor using Files.walkFileTree and copy each file with COPY_ATTRIBUTES
C.Use Files.walk() and then Files.copy() for each entry
D.Use FileUtils.copyDirectory from Apache Commons IO
AnswerB

walkFileTree allows recursive traversal and attribute preservation.

Why this answer

`Files.walkFileTree` with a custom `FileVisitor` allows you to recursively traverse a directory tree and copy each file individually using `Files.copy` with `StandardCopyOption.COPY_ATTRIBUTES`. This is necessary because `Files.copy` on a directory does not copy the directory tree recursively; it only copies the top-level directory entry. The `FileVisitor` pattern ensures that subdirectories and files are visited and copied in depth-first order, preserving file attributes at each step.

Exam trap

The trap here is that candidates assume `Files.copy` with `COPY_ATTRIBUTES` works recursively on directories, but it only copies the directory entry, not its contents, requiring a tree-walking approach like `Files.walkFileTree` to achieve a full recursive copy with attribute preservation.

How to eliminate wrong answers

Option A is wrong because `Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES)` on a directory only copies the directory entry itself, not its contents; it does not recursively copy the tree. Option C is wrong because `Files.walk()` returns a `Stream<Path>` that does not inherently handle directory creation or attribute preservation during copy; using `Files.copy` on each entry without a `FileVisitor` would fail to create parent directories and could overwrite or skip files incorrectly. Option D is wrong because `FileUtils.copyDirectory` from Apache Commons IO is a third-party library method, not part of the standard Java I/O API, and the question asks for a method within the standard Java API.

483
MCQhard

A financial application processes a large log file containing millions of timestamp entries in two different formats: "2024-01-15T10:30:00Z" (ISO 8601) and "01/15/2024 10:30:00 AM" (US locale). The current implementation uses a single DateTimeFormatter with a pattern that throws an exception for the other format. The team wants to parse both formats efficiently without using try-catch for each line. Performance is critical, and the code must be thread-safe. Which approach should be used?

A.Use DateTimeFormatterBuilder.appendOptional to combine both formatters into one thread-safe formatter.
B.Use a single DateTimeFormatter and catch DateTimeParseException for the failing format, then retry with a second formatter.
C.Use DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'" or "MM/dd/yyyy hh:mm:ss a") with a union pattern.
D.Use a SimpleDateFormat with a try-catch block for each format inside a synchronized method.
AnswerA

Efficient and thread-safe, no exceptions for normal parsing.

Why this answer

`DateTimeFormatterBuilder.appendOptional` allows combining multiple formatters into a single thread-safe `DateTimeFormatter`. This approach parses each input against the optional formatters in order, succeeding on the first match without exceptions, which is ideal for performance-critical, thread-safe log processing.

Exam trap

Oracle often tests the misconception that `DateTimeFormatter.ofPattern` can accept multiple patterns in a single string, but the API only supports a single pattern per call, making union patterns invalid.

How to eliminate wrong answers

Option B is wrong because using try-catch for each line introduces exception-handling overhead, which is inefficient for millions of entries and violates the requirement to avoid try-catch per line. Option C is wrong because `DateTimeFormatter.ofPattern` does not support union patterns; the syntax shown is invalid and would cause a compile-time or runtime error. Option D is wrong because `SimpleDateFormat` is not thread-safe, and synchronizing the method would create a performance bottleneck, defeating the thread-safety and efficiency requirements.

484
MCQeasy

Which interface provides the ability to store key-value pairs and allows null keys?

A.ConcurrentHashMap
B.TreeMap
C.HashMap
D.Hashtable
AnswerC

Allows null keys.

Why this answer

HashMap is the correct answer because it implements the Map interface, allows null keys (only one null key is permitted), and does not synchronize its operations, making it suitable for unsynchronized key-value storage. In contrast, ConcurrentHashMap, TreeMap, and Hashtable all prohibit null keys for various reasons, such as thread-safety guarantees or sorting requirements.

Exam trap

The trap here is that candidates often confuse HashMap's allowance of null keys with Hashtable's historical prohibition, or assume that all Map implementations support null keys, when in fact only HashMap (and LinkedHashMap) permit null keys among the commonly used implementations.

How to eliminate wrong answers

Option A is wrong because ConcurrentHashMap does not allow null keys or null values, as its design for concurrent access requires non-null keys to avoid ambiguity in synchronization. Option B is wrong because TreeMap does not permit null keys (though it allows null values), as it relies on natural ordering or a Comparator that would throw a NullPointerException when comparing null. Option D is wrong because Hashtable is a legacy synchronized class that does not allow null keys or null values, throwing a NullPointerException if attempted.

485
Multi-Selecthard

Which THREE are recommended practices to prevent privilege escalation when using doPrivileged in a security-sensitive Java application?

Select 3 answers
A.Restrict the codebase URLs in policy files to only trusted code locations.
B.Use SubjectDomainCombiner to merge multiple protection domains.
C.Always use a SecurityManager to enforce the policy.
D.Sign JARs and verify signatures to ensure code integrity.
E.Use AccessController.checkPermission to explicitly check permissions before privileged operations.
AnswersA, D, E

Limiting which code can be granted privileges reduces attack surface.

Why this answer

Restricting codebase URLs in policy files to only trusted code locations limits the sources from which privileged code can be loaded. This prevents an attacker from injecting malicious code from an untrusted URL that could otherwise be granted elevated permissions via doPrivileged. By narrowing the codebase, you reduce the attack surface for privilege escalation attacks.

Exam trap

The trap here is that candidates often confuse the mechanism (SecurityManager) with a preventive practice, or think that SubjectDomainCombiner is a security control when it actually aggregates permissions and can inadvertently widen the privilege scope.

486
Multi-Selectmedium

Which TWO statements are true about securing a Java application?

Select 2 answers
A.A security policy file can grant specific permissions to code from a particular codebase.
B.Enabling the security manager is required for all Java applications.
C.The Java Cryptography Extension (JCE) is deprecated and should not be used.
D.Using code signing guarantees that the application is secure.
E.The SecurityManager class can be used to set a security policy for the application.
AnswersA, E

Policy files allow granular permission assignments.

Why this answer

A Java security policy file can use a codebase URL (e.g., `codeBase "file:/path/to/jar"`) to grant specific permissions, such as `java.io.FilePermission`, to code loaded from that location. This is a core feature of the Java security model, allowing fine-grained access control based on where the code originates.

Exam trap

The trap here is that candidates often confuse the optional nature of the SecurityManager (thinking it is mandatory) or assume code signing implies security, when in fact it only provides integrity and origin verification, not safety.

487
MCQmedium

Refer to the exhibit. Which of the following best describes the effective permissions granted to the application?

A.The application can connect to any network socket.
B.The application can read and write files under /data/ and connect to any socket.
C.The application can only read files under /data/ and connect to sockets.
D.The application can read and write any file under /data/.
AnswerB

Both permissions are granted by the policy.

Why this answer

The exhibit shows a Java security policy granting the application `java.net.SocketPermission` with `connect,resolve` actions and `java.io.FilePermission` with `read,write` actions on `/data/-`. This means the application can connect to any socket (since the target name is `*`) and read/write any file under `/data/`. Option B correctly captures both permissions.

Exam trap

Oracle often tests the distinction between file permission actions (read vs. write) and the wildcard syntax (`-` for recursive, `*` for all files in a directory), leading candidates to misread the granted actions or scope.

How to eliminate wrong answers

Option A is wrong because it omits the file permissions granted under `/data/`, which include both read and write access. Option C is wrong because it incorrectly restricts file access to read-only, while the policy explicitly grants `read,write`. Option D is wrong because it ignores the socket permission that allows connecting to any socket.

488
MCQhard

An application built with Java 17 uses a third-party library that internally uses `sun.misc.Unsafe`. The application runs without errors on Java 8 but throws an `IllegalAccessError` on Java 17. What is the most likely reason?

A.The --illegal-access flag is set to permit.
B.Strong encapsulation of JDK internals is enforced by default.
C.The module path does not include the library.
D.The library is not in a named module.
AnswerB

Java 17 strongly encapsulates internal APIs by default, causing IllegalAccessError.

Why this answer

In Java 17, strong encapsulation of JDK internals is enforced by default, meaning that code cannot access internal APIs like `sun.misc.Unsafe` via reflection or direct use unless explicitly opened. The `IllegalAccessError` occurs because the third-party library attempts to use `sun.misc.Unsafe`, which is a JDK internal API that is no longer accessible by default. This change was introduced as part of JEP 403 (Strongly Encapsulate JDK Internals) and finalized in Java 17, whereas Java 8 allowed such access.

Exam trap

The trap here is that candidates may think the error is due to the library not being modular (Option D) or a missing module path (Option C), but the real cause is the default strong encapsulation of JDK internals in Java 17, which is a direct consequence of JEP 403.

How to eliminate wrong answers

Option A is wrong because the `--illegal-access=permit` flag was a Java 9–16 transitional option that allowed access to internal APIs; in Java 17, this flag is no longer supported and defaults to `deny`, so setting it to `permit` would not change the behavior. Option C is wrong because the module path not including the library would cause a `ModuleNotFoundException` or `ClassNotFoundException`, not an `IllegalAccessError`; the error here is about access control, not missing modules. Option D is wrong because the library not being in a named module (i.e., being on the classpath) actually makes it more likely to be subject to strong encapsulation, but the error is not about module naming; the core issue is that `sun.misc.Unsafe` is an internal API that is encapsulated regardless of whether the library is named or unnamed.

489
MCQmedium

Given: Object obj = "Hello"; String result = switch(obj) { case String s -> "String of length " + s.length(); case Integer i -> "Integer"; default -> "Unknown"; }; What is result?

A."Unknown"
B.Compilation error
C."String of length 5"
D."Integer"
AnswerC

Correct: the String pattern matches and length is 5.

Why this answer

The switch expression uses pattern matching with type patterns. The runtime type of obj is String, so the first case matches, binding the value to s and executing the expression "String of length " + s.length(). Since s is "Hello", s.length() returns 5, so result is "String of length 5".

Option C is correct.

Exam trap

The trap here is that candidates may think the switch requires a constant expression or that pattern matching is not allowed, leading them to expect a compilation error, or they may forget that the String case matches the runtime type, not the compile-time type of the reference.

How to eliminate wrong answers

Option A is wrong because the switch does not fall through to the default; the String case matches exactly, so "Unknown" is never assigned. Option B is wrong because the code compiles successfully; Java 17+ supports pattern matching for switch with type patterns, and the switch expression is complete with a default branch. Option D is wrong because obj is not an Integer; it is a String, so the Integer case does not match.

490
MCQhard

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

A.The serialized object is corrupted.
B.The JVM versions are incompatible.
C.The file contains data that is not a serialized object.
D.The class definition has changed and the serialVersionUID is not explicitly defined.
AnswerD

Without an explicit UID, the JVM computes one from the class definition, which changes when the class is modified.

Why this answer

When a class definition changes (e.g., adding/removing fields) and the class does not explicitly declare a `serialVersionUID`, the JVM computes one automatically based on the class structure. After deserialization, if the computed UID differs from the UID stored in the serialized stream, an `InvalidClassException` is thrown. This is the most common cause of deserialization failures in practice.

Exam trap

Oracle often tests the misconception that any deserialization failure is due to file corruption or JVM version mismatch, when in fact the most common cause is an implicit `serialVersionUID` mismatch after a class definition change.

How to eliminate wrong answers

Option A is wrong because a corrupted serialized object typically causes a `StreamCorruptedException` or `EOFException`, not an `InvalidClassException`. Option B is wrong because incompatible JVM versions may cause class loading issues or `UnsupportedClassVersionError`, but the `InvalidClassException` is specifically about mismatched `serialVersionUID` values, not JVM version incompatibility. Option C is wrong because if the file contains data that is not a serialized object, the deserialization attempt would throw a `StreamCorruptedException` or `ClassNotFoundException`, not an `InvalidClassException`.

491
MCQmedium

A company has a service layer with a method performOperation() that originally declared throws BaseException (a checked exception). Several client methods call performOperation() and catch BaseException, wrapping it in a RuntimeException for propagation. After a system upgrade, the implementation of performOperation() now explicitly throws two new checked exceptions: SubException1 and SubException2, both of which extend BaseException. The client methods must continue to compile without modifying their catch signatures, and they must still handle the new exceptions appropriately. What is the best way to modify the client methods?

A.Use a multi-catch block to catch SubException1 and SubException2 and rethrow as RuntimeException.
B.Modify the client method signature to declare throws SubException1, SubException2.
C.Add separate catch blocks for SubException1 and SubException2 before the existing BaseException catch.
D.No change needed because the catch for BaseException catches all subclasses.
AnswerD

Polymorphism applies; no modification required.

Why this answer

In Java, a catch block for a superclass exception type (BaseException) will catch all subclasses (SubException1 and SubException2) due to polymorphism in exception handling. Since the client methods already catch BaseException and wrap it in a RuntimeException, no changes are needed to the catch signatures; the new exceptions are automatically handled. This satisfies the requirement that client methods continue to compile without modifying their catch signatures while still handling the new exceptions appropriately.

Exam trap

The trap here is that candidates often think they must explicitly catch new subclasses or use multi-catch, forgetting that a catch for the superclass already covers all subclasses due to polymorphism in exception handling.

How to eliminate wrong answers

Option A is wrong because adding a multi-catch block for SubException1 and SubException2 would require modifying the catch signatures, which violates the requirement that client methods must continue to compile without modifying their catch signatures. Option B is wrong because modifying the client method signature to declare throws SubException1, SubException2 would change the method contract and require all callers to handle these exceptions, which is unnecessary and violates the requirement to keep client methods unchanged. Option C is wrong because adding separate catch blocks for SubException1 and SubException2 before the existing BaseException catch would modify the catch structure, which is not allowed per the requirement; the existing BaseException catch already handles all subclasses, making additional catch blocks redundant and a violation of the 'no modification' constraint.

492
Multi-Selectmedium

Which two statements about multi-catch blocks are correct?

Select 2 answers
A.A multi-catch block cannot catch both checked and unchecked exceptions.
B.A multi-catch block can be used with a finally block.
C.The variable in a multi-catch block is not implicitly final.
D.A multi-catch block can only be used with try-with-resources.
E.The exception types in a multi-catch block must be disjoint.
AnswersB, E

A try statement can have multi-catch and finally.

Why this answer

A multi-catch block is a standard catch block that can handle multiple exception types, and it can be used with a finally block just like any other catch block. The finally block executes regardless of whether an exception is thrown or caught, and multi-catch does not alter this behavior. Option E is correct because the exception types in a multi-catch block must be disjoint, meaning they cannot be in a parent-child relationship; otherwise, the compiler would report an error due to unreachable code.

Exam trap

The trap here is that candidates often think multi-catch cannot be combined with finally or that the variable is not implicitly final, but the exam tests the exact rules: multi-catch works with finally, and the variable is implicitly final.

493
MCQmedium

To generate a cryptographically secure random number for a key generation algorithm, which class should be used?

A.ThreadLocalRandom
B.Math.random()
C.Random
D.SecureRandom
AnswerD

SecureRandom is specifically designed for cryptographic use.

Why this answer

D is correct because `SecureRandom` is specifically designed to produce cryptographically strong random numbers suitable for key generation, using algorithms like SHA1PRNG or NativePRNG that meet FIPS 140-2 standards. Unlike other random number generators, it ensures unpredictability and resistance to reverse engineering, which is critical for security-sensitive operations.

Exam trap

The trap here is that candidates often confuse general-purpose random number generators (like `Random` or `ThreadLocalRandom`) with cryptographically secure ones, assuming any 'random' class suffices for security, but the exam specifically tests the distinction that only `SecureRandom` meets the cryptographic strength required for key generation.

How to eliminate wrong answers

Option A is wrong because `ThreadLocalRandom` is optimized for concurrent access but uses a non-cryptographic PRNG (based on a linear congruential generator) and is not suitable for secure key generation. Option B is wrong because `Math.random()` internally uses `Random` and produces predictable sequences that can be reverse-engineered, making it insecure for cryptographic use. Option C is wrong because `Random` uses a 48-bit seed with a linear congruential formula, which is deterministic and predictable if the seed is known, failing to meet cryptographic randomness requirements.

494
MCQhard

A developer is designing a service that processes multiple files concurrently. To avoid resource leaks, which practice is essential?

A.Ensure each thread has its own copy of the file handle
B.Use try-with-resources for each AutoCloseable resource
C.Call close() on each stream in a separate try-catch block
D.Use FileLock to prevent concurrent access
AnswerB

try-with-resources guarantees closure of each resource in the correct order, even with exceptions.

Why this answer

Try-with-resources guarantees that each AutoCloseable resource is closed automatically at the end of the statement, even if an exception occurs. This is essential when processing multiple files concurrently, as it prevents resource leaks without requiring explicit close() calls in finally blocks.

Exam trap

The trap here is that candidates may think explicit close() calls in separate try-catch blocks are safer, but they overlook that try-with-resources handles suppression and automatic closure more reliably, especially in concurrent scenarios where resource leaks are harder to detect.

How to eliminate wrong answers

Option A is wrong because each thread having its own copy of the file handle does not prevent resource leaks; it merely avoids shared state issues, but the handles still need to be closed properly. Option C is wrong because calling close() on each stream in a separate try-catch block is error-prone and verbose; it does not guarantee closure if an exception occurs before reaching the close() call, and it can lead to suppressed exceptions being lost. Option D is wrong because FileLock is used for coordinating access to a file across processes, not for preventing resource leaks; it does not handle the automatic closing of file handles.

495
MCQmedium

A developer writes: list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); What is the result type and content?

A.Both B and C.
B.Map<T, Long> where T is element type.
C.Map<Object, Long> with number of occurrences of each element.
D.A ConcurrentMap.
AnswerA

This option is self-referential and meaningless; it does not provide a valid description of the result.

Why this answer

Option A, 'Both B and C,' is the correct answer because both statements accurately describe the result. Collectors.groupingBy with Function.identity() and Collectors.counting() produces a Map<T, Long> (where T is the element type) containing the frequency of each element, which can also be described as a Map<Object, Long> with occurrence counts. Options B and C individually are true but incomplete; the question expects selection of the combination.

Option D is incorrect because groupingBy without a map supplier returns a HashMap, not a ConcurrentMap.

Exam trap

The trap is that candidates may focus on individual correct statements and overlook that option A combines both B and C. Recognizing that the result is both a Map<T, Long> and a frequency map is key.

How to eliminate wrong answers

Option B is wrong because it is actually correct, but the question requires selecting both B and C, so B alone is incomplete. Option C is wrong because it is also correct, but again incomplete on its own. Option D is wrong because `Collectors.groupingBy` by default produces a `HashMap` (or a mutable `Map`), not a `ConcurrentMap`; to get a `ConcurrentMap`, you must use `groupingByConcurrent` or supply a `ConcurrentMap` factory via the overloaded `groupingBy` method.

496
MCQhard

Given the following switch statement: ```java int x = 2; switch (x) { default: System.out.print("default "); case 1: System.out.print("1 "); case 2: System.out.print("2 "); case 3: System.out.print("3 "); break; case 4: System.out.print("4 "); } ``` What is the output?

A.2
B.2 3 4
C.2 3
D.default 1 2 3
AnswerC

Prints 2, then falls through to 3 and breaks.

Why this answer

The switch statement starts execution at the matching case (case 2) and then falls through to subsequent cases until a break statement is encountered. Since case 2 has no break, it prints "2 ", then falls through to case 3, prints "3 ", and the break terminates the switch. The default case is not executed because a matching case was found before it.

Exam trap

The trap here is that candidates often forget fall-through behavior or assume the default case always executes, leading them to pick options that include default or skip the break's effect on subsequent cases.

How to eliminate wrong answers

Option A is wrong because it assumes only the matching case executes, ignoring fall-through behavior in switch statements without break. Option B is wrong because it incorrectly includes case 4, but the break in case 3 prevents fall-through to case 4. Option D is wrong because it assumes the default case executes first, but default only runs if no matching case is found; here case 2 matches, so default is skipped.

497
MCQeasy

A developer needs to read all lines from a text file named "data.txt" that uses UTF-8 encoding. Which code correctly reads the file using the NIO.2 API?

A.Files.lines(Path.of("data.txt"), StandardCharsets.UTF_8).collect(Collectors.toList())
B.Files.readString(Path.of("data.txt"), StandardCharsets.UTF_8)
C.Files.readAllBytes(Path.of("data.txt")).toString()
D.Files.readAllLines(Path.of("data.txt"), StandardCharsets.UTF_8)
AnswerD

Files.readAllLines directly returns a List<String> with the specified charset, which is the simplest correct approach.

Why this answer

`Files.readAllLines()` reads all lines from a file into a `List<String>`, and it accepts a `Path` and a `Charset` (here `StandardCharsets.UTF_8`) to handle encoding. This method is part of the NIO.2 API and directly fulfills the requirement to read all lines from a UTF-8 encoded file.

Exam trap

The trap here is that candidates often confuse `Files.readString()` (which returns a single string) with `Files.readAllLines()` (which returns a list of lines), or they mistakenly think `Files.readAllBytes().toString()` will convert bytes to text, when in fact it returns the object reference string.

How to eliminate wrong answers

Option A is wrong because `Files.lines()` returns a `Stream<String>` that must be collected (e.g., via `collect(Collectors.toList())`) to get a list, but the question asks for reading 'all lines' and the option as written is syntactically incomplete (missing semicolon) and not the most direct NIO.2 method for this task. Option B is wrong because `Files.readString()` reads the entire file content as a single `String`, not as a list of lines, so it does not meet the requirement to read 'all lines'. Option C is wrong because `Files.readAllBytes()` returns a `byte[]`, and calling `.toString()` on a byte array returns a meaningless representation like `[B@hashcode`, not the file content as lines.

498
MCQeasy

Consider the following code: ```java boolean a = true, b = false, c = false; if (a && b || c) { System.out.println("True"); } else { System.out.println("False"); } ``` What is the output?

A.The code does not compile because of invalid boolean expression.
B.False
C.The output cannot be determined without runtime values.
D.True
AnswerB

Correct. a&&b is false, then false||c is false.

Why this answer

The expression `a && b || c` evaluates as `(a && b) || c` due to operator precedence (`&&` has higher precedence than `||`). With `a=true`, `b=false`, `c=false`, `(true && false)` is `false`, then `false || false` is `false`, so the `else` branch prints "False". Option B is correct.

Exam trap

The trap here is that candidates often misinterpret the expression as `a && (b || c)` due to left-to-right reading, forgetting that `&&` has higher precedence than `||` in Java.

How to eliminate wrong answers

Option A is wrong because the boolean expression is syntactically valid; Java allows mixing `&&` and `||` in a single expression. Option C is wrong because all variables are initialized with literal values, so the output is deterministic at compile time. Option D is wrong because it assumes the expression evaluates to true, which would only happen if `c` were true or both `a` and `b` were true.

499
MCQeasy

Which of the following correctly creates a text block in Java?

A."line1\nline2"
B."""line1 line2"""
C.'line1\nline2'
D."""line1\nline2"""
AnswerB

Correct: Text block spans multiple lines and preserves indentation.

Why this answer

It uses the Java text block syntax, which starts and ends with three double-quote characters (""") and places the content on a new line after the opening delimiter. The text block preserves the line break and indentation, making it ideal for multi-line strings without escape sequences.

Exam trap

The trap here is that candidates may confuse the text block delimiter (""") with a regular string that uses escape sequences, leading them to choose option D, which incorrectly mixes explicit \n with the text block syntax.

How to eliminate wrong answers

Option A is wrong because it uses a regular string literal with an explicit escape sequence (\n) for a newline, not a text block. Option C is wrong because single quotes (') are used for character literals in Java, not strings, and the syntax is invalid for a multi-line string. Option D is wrong because it uses the text block delimiter (""") but includes an explicit \n escape sequence inside the block, which is unnecessary and defeats the purpose of a text block; text blocks automatically handle line breaks.

500
MCQmedium

Refer to the exhibit. Two Java classes are defined as shown. What is the output when the Sub class is executed?

A.HelloWorld
B.World
C.Hello
D.No output (compilation error)
AnswerB

Sub's main method is executed, printing 'World'.

Why this answer

The Sub class overrides the print() method from Super and does not call super.print(). Therefore, when Sub's print() is executed, it only prints "World" without printing "Hello". The output is simply "World".

Exam trap

Oracle often tests whether candidates understand that an overridden method in a subclass does not automatically execute the superclass version unless explicitly called with super.method(), leading many to mistakenly think the superclass method runs first by default.

How to eliminate wrong answers

Option A is wrong because "HelloWorld" would only appear if Sub's print() called super.print() before printing "World", but the exhibit (per the answer) shows Sub's print() does not call super.print(), so only "World" is output. Option C is wrong because "Hello" would be output only if Sub's print() called super.print() without printing anything else, but Sub's print() prints "World" after the super call (or instead of it). Option D is wrong because there is no compilation error; the code compiles successfully as Sub extends Super and overrides print() with a valid method signature.

501
MCQmedium

Refer to the exhibit. What is the output?

A.Count: 2
B.Count: 3
C.Count: 1
D.Count: 4
AnswerA

Correct. The filter removes all elements equal to 'A', leaving only non-'A' elements. The exhibit shows exactly two such elements, so the count is 2.

Why this answer

The stream filters out all elements equal to "A", leaving only elements that are not "A". Based on the list in the exhibit, there are exactly two such elements (e.g., "B" and "C"), so the count is 2.

Exam trap

The trap here is that candidates often forget to account for the filter predicate or misread the list contents, leading them to count all elements or assume a different number of non-'A' elements without carefully tracing the stream operations.

How to eliminate wrong answers

Option B (Count: 3) is wrong because it assumes the list has three non-'A' elements, but the correct count is 2, meaning the list either has only two non-'A' elements or includes a distinct() operation that reduces duplicates. Option C (Count: 1) is wrong because it underestimates the number of non-'A' elements; the filter does not remove all elements, only those equal to 'A'. Option D (Count: 4) is wrong because it ignores the filter entirely, counting all elements including 'A's, which is not what the stream does.

502
Multi-Selecteasy

Which THREE are methods of the Map.Entry interface? (Java 17)

Select 3 answers
A.getValue()
B.getHash()
C.getKey()
D.setValue(V value)
E.getValueOrDefault()
AnswersA, C, D

Returns the value.

Why this answer

The Map.Entry interface in Java defines the getValue() method, which returns the value associated with the entry's key. This method is part of the core contract for accessing key-value pairs within a Map.

Exam trap

The trap here is that candidates confuse methods of the Map interface (like getOrDefault) with methods of the Map.Entry interface, or assume a getHash() method exists due to familiarity with hash-based collections like HashMap.

503
Multi-Selectmedium

Which three of the following are valid case values in a traditional switch statement (non-pattern)?

Select 3 answers
A.42
B.true
C.3.14
D.Monday (assuming an enum constant)
E."hello"
AnswersA, D, E

Correct: int is allowed.

Why this answer

In a traditional switch statement (non-pattern), the case values must be compile-time constants of types that are compatible with the switch expression. Integer literals like 42 are valid case values, as they are constant expressions of type int, which is one of the allowed types (byte, short, char, int, their wrapper classes, String, and enum types).

Exam trap

The trap here is that candidates often assume any primitive type or literal can be used in a switch case, forgetting that only byte, short, char, int, String, and enum constants are allowed, and that boolean and floating-point types are explicitly excluded.

504
MCQeasy

A developer needs to iterate over a List<String> and remove elements that are null. Which approach guarantees correct behavior without throwing a ConcurrentModificationException?

A.Use a for-each loop and call list.remove() on the current element
B.Use a Stream's filter() method and collect the results
C.Use a traditional for loop with an index that decrements
D.Use an Iterator explicitly and call its remove() method
AnswerD

Iterator.remove() is the safe way to remove elements during iteration.

Why this answer

Iterator.remove() is the safe and recommended way to remove elements during iteration, avoiding ConcurrentModificationException. Option A is incorrect because using list.remove() inside a for-each loop modifies the list directly while iterating, causing ConcurrentModificationException. Option B is incorrect because Stream.filter() does not modify the original list; it creates a new list, which may not meet the requirement to remove elements from the original.

Option C is incorrect because although a decrementing for loop may work, it is error-prone and not the guaranteed approach; it is not the idiomatic Java solution.

505
MCQeasy

How many times does the following loop execute? int i=0; while(i<5) { System.out.println(i); i++; }

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

The loop runs for i=0 through i=4, which is 5 iterations.

Why this answer

The loop starts with i=0, checks the condition i<5 (true), prints i, then increments i. This repeats until i becomes 5, at which point i<5 is false and the loop terminates. Thus, the loop executes exactly 5 times (i=0,1,2,3,4).

Exam trap

The trap here is that candidates often miscount the iterations by starting at 1 instead of 0, or forget that the condition is checked before each execution, leading them to choose 4 or 6 instead of the correct 5.

How to eliminate wrong answers

Option A is wrong because the loop condition i<5 is true when i=0, so the loop body executes at least once, not zero times. Option B is wrong because the loop stops when i reaches 5, so it executes 5 times, not 6; a sixth iteration would require i<5 to be true when i=5, which it is not. Option D is wrong because the loop executes for i=0 through i=4 inclusive, which is 5 iterations, not 4; the increment happens after each print, so i=4 is the last value printed.

506
MCQhard

Refer to the exhibit. What is the result?

A.Prints 10
B.Runtime exception because Inner class is not static.
C.Compilation error because x is private.
D.Prints 0 because x is not initialized in Inner.
AnswerA

Inner class can access private members of the outer class.

Why this answer

The code accesses the private field `x` of the `Outer` class from within the `Inner` class, which is a member inner class. In Java, a non-static inner class has access to all members (including private fields) of its enclosing outer class. The `Inner` class's `printX()` method directly accesses `Outer.this.x`, which is initialized to 10 in the `Outer` constructor, so it prints 10.

Exam trap

The trap here is that candidates mistakenly think private members are inaccessible to inner classes, or that the inner class must be static to access outer class fields, but Java's member inner classes have full access to all members of the enclosing class, including private ones.

How to eliminate wrong answers

Option B is wrong because the `Inner` class does not need to be static to access the outer class's private field; a non-static inner class has implicit access to the outer class's private members. Option C is wrong because `x` being private does not cause a compilation error; private members are accessible within the same top-level class, and the inner class is part of the outer class. Option D is wrong because `x` is initialized to 10 in the `Outer` constructor before `printX()` is called, so it is not uninitialized.

507
MCQmedium

Which class from the java.nio.file package is most appropriate for efficiently transferring data between two channels on the same machine?

A.Files.copy(Path, Path)
B.RandomAccessFile.getChannel().write(ByteBuffer)
C.InputStream.transferTo(OutputStream)
D.FileChannel.transferTo(long, long, WritableByteChannel)
AnswerD

Zero-copy transfer between channels.

Why this answer

`FileChannel.transferTo()` (and its counterpart `transferFrom()`) uses the operating system's zero-copy mechanism (e.g., `sendfile()` on Linux or `TransmitFile()` on Windows) to move data directly between file system caches and the target channel without intermediate buffers or user-space copies. This makes it the most efficient approach for transferring data between two channels on the same machine, as it minimizes CPU overhead and memory bandwidth usage.

Exam trap

The trap here is that candidates often confuse high-level convenience methods like `Files.copy()` or `InputStream.transferTo()` with low-level channel operations, failing to recognize that the question specifically asks for 'most efficient' transfer between channels, which requires zero-copy via `FileChannel.transferTo()`.

How to eliminate wrong answers

Option A is wrong because `Files.copy(Path, Path)` is a high-level method that reads the source file into a buffer and writes it to the destination, involving multiple kernel-to-user-space copies, which is less efficient than zero-copy. Option B is wrong because `RandomAccessFile.getChannel().write(ByteBuffer)` requires manually managing a `ByteBuffer` and performing a read-then-write cycle, which adds overhead and does not leverage OS-level zero-copy optimization. Option C is wrong because `InputStream.transferTo(OutputStream)` operates at the stream level, reading bytes into an internal buffer and writing them out, which involves multiple data copies and is not channel-based, thus lacking the direct kernel-to-kernel transfer capability.

508
MCQmedium

Given: Object obj = null; String s = switch(obj) { case null -> "null"; case String str -> str; default -> "other"; }; What is the result?

A.Compilation error
B.NullPointerException
C."other"
D."null"
AnswerD

Correct: the null case matches and returns "null".

Why this answer

In Java 14+, switch expressions can handle null values directly using a 'case null' label. Since obj is null, the switch matches the 'case null' branch and returns the string "null". Option D is correct because the code compiles and executes without error, producing "null".

Exam trap

The trap here is that candidates may assume a switch expression throws NullPointerException on a null selector, but Java 14+ explicitly allows 'case null' to handle null values, making the code valid and producing the expected result.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; Java 14+ switch expressions allow 'case null' as a valid label. Option B is wrong because no NullPointerException is thrown; the 'case null' explicitly handles the null reference. Option C is wrong because the default branch is not reached; the switch matches the 'case null' branch first.

509
MCQmedium

A developer wants to ensure that a block of code always executes regardless of whether an exception occurs or not, and that any exception thrown in the block is not swallowed. Which construct should be used?

A.try-catch with empty catch block
B.try-catch-finally with catch that rethrows the exception
C.try-finally
D.try-with-resources without catch
AnswerC

Finally runs always; exception propagates uncaught.

Why this answer

The try-finally construct ensures that the finally block always executes after the try block, regardless of whether an exception occurs, and it does not catch or swallow any exception. This meets the requirement of guaranteed execution without suppressing the exception, as the exception propagates up the call stack.

Exam trap

The trap here is that candidates often think a catch block is required to handle exceptions, but the question specifically demands that the exception not be swallowed, making try-finally the correct choice because it executes cleanup code without interfering with exception propagation.

How to eliminate wrong answers

Option A is wrong because an empty catch block swallows the exception, preventing it from propagating, which violates the requirement that the exception not be swallowed. Option B is wrong because while a catch block that rethrows the exception preserves the exception, the finally block still executes, but the catch block itself is unnecessary for the requirement and adds complexity; the question asks for a construct that ensures execution without swallowing, and try-finally alone suffices. Option D is wrong because try-with-resources without a catch will close resources automatically but does not include a finally block; if an exception occurs, the resource closing mechanism may suppress exceptions (via suppressed exceptions), potentially swallowing the primary exception, and there is no guarantee of unconditional code execution after the try block.

510
MCQhard

Which change fixes the exception?

A.Change line 4 to: for (int i = 0; i < arr.length; i++)
B.Change line 4 to: for (int i = 1; i <= arr.length; i++)
C.Change line 4 to: for (int i = 0; i <= arr.length-1; i++)
D.Change line 5 to: System.out.println(arr[i-1]);
AnswerA

Corrects the off-by-one error.

Why this answer

It changes the loop to start at index 0 and continue while i < arr.length, which correctly iterates over all valid indices (0 to arr.length-1). The original code likely used i <= arr.length, causing an ArrayIndexOutOfBoundsException when accessing arr[i] at i = arr.length. By using i < arr.length, the loop stops before reaching the out-of-bounds index.

Exam trap

The trap here is that candidates often confuse the loop condition i <= arr.length with i < arr.length, not realizing that the former accesses an index one past the array's last element, causing an ArrayIndexOutOfBoundsException.

How to eliminate wrong answers

Option B is wrong because it uses i <= arr.length, which still causes an ArrayIndexOutOfBoundsException when i equals arr.length (since valid indices are 0 to arr.length-1). Option C is wrong because i <= arr.length-1 is functionally equivalent to i < arr.length, but the question asks which change 'fixes' the exception; while this would also work, it is not the listed correct answer and introduces unnecessary complexity. Option D is wrong because changing the print statement to arr[i-1] would cause an ArrayIndexOutOfBoundsException on the first iteration when i=0 (accessing arr[-1]), and does not fix the root cause of the loop bounds.

511
MCQhard

A developer needs to parse the string "2023-12-31T23:59:60Z" (a leap second) into a java.time.Instant. Which statement is true?

A.It returns an Instant representing 2023-12-31T23:59:59Z, ignoring the leap second.
B.It returns an Instant representing 2023-12-31T23:59:59Z with an added nanosecond.
C.It throws a DateTimeParseException because 60 seconds is invalid.
D.It returns null because the string is invalid.
AnswerB

The 60th second is treated as the last nanosecond of the minute.

Why this answer

Java.time.Instant.parse() handles leap seconds by converting them to the last valid second of the minute (23:59:59) and then adding a nanosecond to account for the extra second. This behavior is specified by the ISO-8601 standard and the Java Time API, which does not support a true 60th second but represents it as an Instant with a fractional second adjustment.

Exam trap

The trap here is that candidates assume '60' seconds is always invalid and will cause an exception, but the Java Time API specifically accommodates leap seconds by converting them to the nearest valid nanosecond-adjusted Instant.

How to eliminate wrong answers

Option A is wrong because it states the leap second is ignored entirely, but the API actually adds a nanosecond to represent the leap second, not discarding it. Option C is wrong because the parser does not throw a DateTimeParseException; it accepts the '60' seconds value as a valid leap second representation. Option D is wrong because the string is valid ISO-8601 format and does not cause a null return; Instant.parse() always returns a non-null Instant or throws an exception.

512
MCQmedium

What is the result of executing the code in the exhibit?

A.The code compiles and prints 'Caught in main: IOException' because the compiler uses improved rethrow analysis.
B.Prints: Caught in main: Exception
C.The code does not compile because methodA does not declare that it throws Exception.
D.Prints: Caught in main: IOException
AnswerC

The catch parameter is Exception, so rethrow is considered as throwing Exception, which is not declared.

Why this answer

The code does not compile because methodA explicitly throws an IOException, but the catch block in main catches Exception (a broader type). However, the compiler performs improved rethrow analysis only when the exception parameter is effectively final and the catch block is multi-catch or rethrows a checked exception that is declared in the method signature. Here, methodA does not declare that it throws Exception, and the catch block catches Exception, which is not a declared exception in methodA's throws clause, causing a compilation error.

Exam trap

The trap here is that candidates assume improved rethrow analysis allows catching a broader exception type (Exception) without the method declaring it, forgetting that the method's throws clause must still declare the caught exception or the catch block must match the thrown exception exactly.

How to eliminate wrong answers

Option A is wrong because improved rethrow analysis applies only when the caught exception parameter is effectively final and the method declares the specific exception types; here, methodA does not declare Exception, so the compiler cannot infer that IOException is the only exception thrown. Option B is wrong because the code does not compile, so it cannot print 'Caught in main: Exception'. Option D is wrong because the code does not compile, so it cannot print 'Caught in main: IOException'.

Page 6

Page 7 of 7

All pages