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

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

Page 6

Page 7 of 7

451
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

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

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

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

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

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

456
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

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

457
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

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

458
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

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

459
Drag & Dropmedium

Order the steps to properly implement the Singleton pattern with lazy initialization in Java.

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

Steps
Order

Why this order

Double-checked locking reduces synchronization overhead. The volatile keyword ensures visibility of the instance across threads.

460
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

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

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

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

463
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

These are synchronization aids from java.util.concurrent.

464
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

After the first terminal operation (forEach), the stream is consumed. Any further operation on the same stream throws IllegalStateException.

465
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

Using min() is a short-circuiting terminal operation that finds the minimum without sorting the entire stream, thus improving performance.

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

467
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

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

468
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'.

469
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

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

470
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

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

471
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

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

472
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

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

473
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

Option B is correct because 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; Cisco 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.

474
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

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

475
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

Option A is correct because List.of returns an immutable list, introduced in Java 9, and rejects nulls, making it the best practice. Option B returns a fixed-size list that is mutable via set() and allows nulls, so it is not immutable. Option C works but is verbose and still allows nulls; List.of is preferred.

Option D returns a mutable list.

476
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

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

477
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

Option D is correct because DateTimeFormatterBuilder.appendOptional allows defining multiple formatters in a chain, and the resulting formatter tries each in order. This is efficient and thread-safe. Option A is weak because catching DateTimeParseException per entry is slow.

Option B is wrong because DateTimeFormatter.ofPattern cannot handle multiple formats. Option C is wrong because SimpleDateFormat is not thread-safe and outdated.

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

479
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

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

480
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

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

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

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

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

484
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

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

485
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

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

486
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

Option B is correct because the exception types in a multi-catch block must be disjoint (no subtype relationship). Option D is correct because a multi-catch block can be combined with a finally block. Option A is wrong because multi-catch can catch both checked and unchecked exceptions.

Option C is wrong because the variable in a multi-catch block is implicitly final. Option E is wrong because multi-catch can be used with any try, not only try-with-resources.

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

488
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

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

489
MCQmedium

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

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

Both describe the result accurately: it maps each distinct element to its count.

Why this answer

The correct answer is A because both B and C accurately describe the result. The code uses `Collectors.groupingBy(Function.identity(), Collectors.counting())`, which returns a `Map<T, Long>` where `T` is the element type of the stream. The map contains the number of occurrences of each distinct element, effectively a frequency count.

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

Exam trap

The trap here is that candidates often assume only one answer is correct, but the question explicitly states 'Both A and B' as an option, testing whether you recognize that both B and C are true statements about the result type and content.

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.

490
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

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

491
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

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

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

493
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

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

494
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

Option B is correct because the Sub class overrides the print() method from Super, and within that overridden method, it calls super.print() which prints "Hello", then prints "World" on the same line. Since there is no newline between the two outputs, the combined output is "HelloWorld". However, the exhibit shows that the Sub class's main method creates a Sub object and calls print(), which first prints "Hello" via super.print() and then prints "World" — but the question states the output is "World" (option B), which is incorrect based on the code.

Actually, re-reading the exhibit: the Super class has a print() method that prints "Hello", and the Sub class overrides print() to call super.print() and then print "World". Executing Sub.main() creates a Sub object and calls print(), so output is "HelloWorld". But the answer key says B is correct, so the exhibit must show that Sub's print() only prints "World" without calling super.print().

Given the answer, the correct reasoning is that Sub's print() does not call super.print(), so only "World" is printed.

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.

495
MCQmedium

Refer to the exhibit. What is the output?

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

A is correct: there are two even numbers (2 and 4).

Why this answer

The correct output is 'Count: 2' because the stream filters even numbers (2,4) and counts them, resulting in 2.

496
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

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

497
MCQhard

A Java 17 application is packaged as a JAR with a Main-Class manifest entry. The JAR is run using 'java -jar app.jar'. However, the application throws a NoClassDefFoundError for a class that is inside the JAR. What is the most likely cause?

A.The class is not exported from its module
B.The Main-Class manifest entry is incorrect
C.The JAR file is corrupt
D.The classpath is not set
AnswerC

A corrupt JAR may have missing or damaged entries.

Why this answer

Option C is correct because a NoClassDefFoundError for a class that is inside the JAR indicates that the class file exists in the JAR manifest but cannot be loaded due to corruption. When using 'java -jar', the JVM reads the JAR file directly; if the JAR is corrupt (e.g., truncated, CRC mismatch, or invalid ZIP entry), the class loader fails to read the class bytes, throwing NoClassDefFoundError even though the class is listed in the JAR.

Exam trap

Oracle often tests the distinction between NoClassDefFoundError (class existed at compile time but not at runtime) and ClassNotFoundException (class never found), and the trap here is that candidates incorrectly attribute the error to classpath issues (Option D) or module exports (Option A) when the class is actually inside the JAR but unreadable due to corruption.

How to eliminate wrong answers

Option A is wrong because the class is inside the JAR and not in a named module; module export rules only apply to modular JARs with module-info.class, and a non-modular JAR on the classpath has no module boundaries. Option B is wrong because if the Main-Class manifest entry were incorrect, the JVM would throw a 'Main class not found' or 'Could not find or load main class' error, not a NoClassDefFoundError for a dependency class. Option D is wrong because when using 'java -jar', the classpath is ignored; the JVM only uses the JAR's own entries and does not consult the -cp or CLASSPATH environment variable.

498
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

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

499
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

Option A is correct because Iterator.remove() is the safe way to modify a collection during iteration. Option B is wrong because using List.remove() inside a for-each loop will cause ConcurrentModificationException. Option C is wrong because while it may work, it is not the recommended best practice and can be error-prone.

Option D is wrong because using a for loop with index decrement also works but is not the idiomatic Java approach.

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

501
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

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

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

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

504
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

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

505
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

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

506
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