Sample questions
Oracle Certified Professional Java SE 17 Developer 1Z0-829 practice questions
A financial application uses Java SE 17 with a custom date format. The requirement is to parse strings like "2023-12-31T23:59:59.999Z" into an Instant. The existing code uses SimpleDateFormat with pattern "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" and then calls parse(). It works fine in single-threaded testing, but in production under load, intermittent parsing failures occur with DateTimeParseException or wrong values. The application is multi-threaded and reuses the same formatter instance. Which single change should be made to fix the issue while maintaining performance?
Trap 1: Wrap the parse call in a synchronized block
Thread-safe but causes contention, reducing performance.
Trap 2: Use a ThreadLocal<SimpleDateFormat> to give each thread its own…
Works but is more complex and less performant than using DateTimeFormatter.
Trap 3: Create a new SimpleDateFormat instance for each parse call
Avoids thread safety but creates many objects, hurting performance.
- A
Wrap the parse call in a synchronized block
Why wrong: Thread-safe but causes contention, reducing performance.
- B
Use a ThreadLocal<SimpleDateFormat> to give each thread its own instance
Why wrong: Works but is more complex and less performant than using DateTimeFormatter.
- C
Replace SimpleDateFormat with DateTimeFormatter.ISO_INSTANT and use Instant.from()
Thread-safe and correct for ISO 8601.
- D
Create a new SimpleDateFormat instance for each parse call
Why wrong: Avoids thread safety but creates many objects, hurting performance.
Which TWO statements about the switch statement in Java are correct?
Trap 1: Case values can be runtime expressions.
Case values must be compile-time constants.
Trap 2: A break statement is mandatory after each case block.
Break is optional; fall-through occurs without it.
Trap 3: Case labels can be variables if they are final and assigned a…
They must be compile-time constants, but final variables are allowed only if initialized with constant expressions.
- A
The default case can be placed anywhere within the switch block.
Default can be at any position.
- B
Case values can be runtime expressions.
Why wrong: Case values must be compile-time constants.
- C
A break statement is mandatory after each case block.
Why wrong: Break is optional; fall-through occurs without it.
- D
Case labels can be variables if they are final and assigned a constant expression.
Why wrong: They must be compile-time constants, but final variables are allowed only if initialized with constant expressions.
- E
The switch statement can be used with int, char, String, and enum types.
These are valid types for switch.
Which THREE statements are true about the java.util.Collection and java.util.stream.Stream APIs? (Choose three.)
Trap 1: The Collection.forEach() method is inherited from the Collection…
It is inherited from Iterable.
Trap 2: The Collection interface inherits the stream() method from the…
stream() is defined in Collection, not Iterable.
- A
The Collection.forEach() method is inherited from the Collection interface.
Why wrong: It is inherited from Iterable.
- B
The Stream.forEach() operation processes elements in the encounter order of the stream only for sequential streams.
Parallel streams may process elements out of order.
- C
The Collection interface inherits the stream() method from the Iterable interface.
Why wrong: stream() is defined in Collection, not Iterable.
- D
The Stream.toList() method returns an unmodifiable list.
Since Java 16.
- E
The Iterator interface provides a default method forEachRemaining(Consumer<? super E> action).
Introduced in Java 8.
Which TWO of the following are checked exceptions in Java?
Trap 1: ArithmeticException
ArithmeticException is an unchecked exception.
Trap 2: ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException is an unchecked exception.
Trap 3: NullPointerException
NullPointerException is an unchecked exception.
- A
SQLException
SQLException is a checked exception.
- B
ArithmeticException
Why wrong: ArithmeticException is an unchecked exception.
- C
ArrayIndexOutOfBoundsException
Why wrong: ArrayIndexOutOfBoundsException is an unchecked exception.
- D
NullPointerException
Why wrong: NullPointerException is an unchecked exception.
- E
IOException
IOException is a checked exception.
A developer is implementing a custom sort for a list of Employee objects. The Employee class has fields: String name, int age. The list must be sorted first by name (ascending, case-insensitive), then by age (descending). Which Comparator implementation correctly achieves this?
Trap 1: Comparator.comparing(Employee::getName,…
Sorts by name case-insensitive ascending, then age ascending - age should be descending.
Trap 2: Comparator.comparingInt(Employee::getAge).reversed().thenComparing(E…
Sorts by age descending first, then name - name should be primary key.
Trap 3: Comparator.comparing(Employee::getName).thenComparingInt(Employee::g…
Reverses entire comparator, so name descending, age descending - name should be ascending.
- A
Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER).thenComparingInt(Employee::getAge)
Why wrong: Sorts by name case-insensitive ascending, then age ascending - age should be descending.
- B
Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER).thenComparing(Comparator.comparingInt(Employee::getAge).reversed())
Correctly sorts by name case-insensitive ascending, then age descending.
- C
Comparator.comparingInt(Employee::getAge).reversed().thenComparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)
Why wrong: Sorts by age descending first, then name - name should be primary key.
- D
Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge).reversed()
Why wrong: Reverses entire comparator, so name descending, age descending - name should be ascending.
What is the result of executing the code in the exhibit?
Exhibit
Refer to the exhibit.
```
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
for (String s : list) {
if (s.equals("B")) {
list.remove(s);
}
}
System.out.println(list);
```Trap 1: The code compiles and runs without output.
Exception is thrown and printed.
Trap 2: [A, C]
Would be result if no exception, but exception is thrown.
Trap 3: [A, B]
Incorrect removal.
- A
The code compiles and runs without output.
Why wrong: Exception is thrown and printed.
- B
[A, C]
Why wrong: Would be result if no exception, but exception is thrown.
- C
ConcurrentModificationException is thrown.
Modification during enhanced for loop causes exception.
- D
[A, B]
Why wrong: Incorrect removal.
Which TWO statements are true about the Java Platform Module System (JPMS) introduced in Java 9?
Trap 1: The module path is searched after the class path when resolving…
The module path and class path are separate; the class path is used for unnamed module and the module path for named modules.
Trap 2: An automatic module is one that has a module-info.class file at its…
An automatic module is created from a JAR placed on the module path without a module-info.class.
Trap 3: A named module can access the unnamed module without any explicit…
Named modules are not allowed to read the unnamed module unless the --add-reads flag is used.
- A
The module path is searched after the class path when resolving types.
Why wrong: The module path and class path are separate; the class path is used for unnamed module and the module path for named modules.
- B
The module declaration is stored in a file named module-info.java.
The module declaration is placed in module-info.java, which is compiled to module-info.class.
- C
A module must explicitly export a package to make it accessible to other modules.
By default, a package is not exported; it must be declared with the exports directive.
- D
An automatic module is one that has a module-info.class file at its root.
Why wrong: An automatic module is created from a JAR placed on the module path without a module-info.class.
- E
A named module can access the unnamed module without any explicit declaration.
Why wrong: Named modules are not allowed to read the unnamed module unless the --add-reads flag is used.
A developer wants to find the longest word in a list of strings. Which stream operation should be used?
Trap 1: stream().sorted(Comparator.comparingInt(String::length).reversed()).…
Works but not as direct as max.
Trap 2: stream().min(Comparator.comparingInt(String::length))
Returns shortest.
Trap 3: stream().sorted(Comparator.comparingInt(String::length)).findFirst()
Returns shortest.
- A
stream().sorted(Comparator.comparingInt(String::length).reversed()).findFirst()
Why wrong: Works but not as direct as max.
- B
stream().min(Comparator.comparingInt(String::length))
Why wrong: Returns shortest.
- C
stream().sorted(Comparator.comparingInt(String::length)).findFirst()
Why wrong: Returns shortest.
- D
stream().max(Comparator.comparingInt(String::length))
Correct.
A Java 17 application is deployed on a server. The application uses modules but one required module is missing from the module path. Which exception will be thrown at startup?
Trap 1: ExceptionInInitializerError
This occurs during static initialization.
Trap 2: NoClassDefFoundError
This occurs when a class is missing at runtime, not a module.
Trap 3: ClassNotFoundException
This is for class loading, not module resolution.
- A
ExceptionInInitializerError
Why wrong: This occurs during static initialization.
- B
NoClassDefFoundError
Why wrong: This occurs when a class is missing at runtime, not a module.
- C
ClassNotFoundException
Why wrong: This is for class loading, not module resolution.
- D
ModuleNotFoundException
Thrown when a required module cannot be resolved.
A developer runs 'java --list-modules' and sees the output above. Which command can be used to create a custom runtime image containing only the 'java.base' module?
Trap 1: jar --create --file myimage --module java.base
jar does not create runtime images.
Trap 2: jimage --add-modules java.base --output myimage
jimage is for managing runtime images, not creating them.
Trap 3: jlink --modules java.base --output myimage
--modules is not a valid flag.
- A
jar --create --file myimage --module java.base
Why wrong: jar does not create runtime images.
- B
jimage --add-modules java.base --output myimage
Why wrong: jimage is for managing runtime images, not creating them.
- C
jlink --modules java.base --output myimage
Why wrong: --modules is not a valid flag.
- D
jlink --add-modules java.base --output myimage
Correct syntax for jlink.
A development team wants to ensure that a Java 17 application runs with a specific set of modules. They want to minimize the footprint by including only necessary modules. Which tool should they use?
Trap 1: javac
javac compiles Java source code.
Trap 2: jmod
jmod creates JMOD files for packaging, not runtime images.
Trap 3: jar
jar packages classes, it does not create a runtime.
- A
javac
Why wrong: javac compiles Java source code.
- B
jlink
jlink assembles a custom runtime image with specified modules.
- C
jmod
Why wrong: jmod creates JMOD files for packaging, not runtime images.
- D
jar
Why wrong: jar packages classes, it does not create a runtime.
Which THREE are valid ways to package a Java 17 application for distribution? (Choose three.)
Trap 1: ZIP file containing compiled classes
ZIP is not a standard Java packaging format.
Trap 2: Shell script that compiles and runs the application
That is not a packaging format.
- A
JMOD file
JMOD is a packaging format for modules.
- B
ZIP file containing compiled classes
Why wrong: ZIP is not a standard Java packaging format.
- C
Native installer (e.g., MSI, DMG)
jpackage can create native installers.
- D
Shell script that compiles and runs the application
Why wrong: That is not a packaging format.
- E
JAR file with a manifest
Standard JAR packaging is valid.
A developer receives the above error when running a modular Java application. What is the most likely cause?
Exhibit
Refer to the exhibit. ``` Error: Unable to initialize main class com.example.Main Caused by: java.lang.module.ResolutionException: Module com.example.app not found ```
Trap 1: The module-info.java has a syntax error.
A syntax error would be caught at compile time.
Trap 2: The JRE version is too old.
If the JRE were too old, it would not support modules at all.
Trap 3: The main class is misspelled.
That would cause a different error (ClassNotFoundException).
- A
The module-info.java has a syntax error.
Why wrong: A syntax error would be caught at compile time.
- B
The module 'com.example.app' is not on the module path.
The error indicates the module was not found.
- C
The JRE version is too old.
Why wrong: If the JRE were too old, it would not support modules at all.
- D
The main class is misspelled.
Why wrong: That would cause a different error (ClassNotFoundException).
A developer is tasked with reading a large binary file (1 GB) from a network share using the least amount of memory possible. Which approach should be used?
Trap 1: Read the entire file into a byte array using Files.readAllBytes()
This loads the entire file into memory, which is not memory-efficient for large files.
Trap 2: Use a FileReader wrapped in a BufferedReader to read lines
FileReader is for character data, not binary files, and still holds data in memory.
Trap 3: Use a RandomAccessFile to read the file in segments
RandomAccessFile is not memory-efficient and is more complex; BufferedInputStream is simpler and adequate.
- A
Use a FileInputStream wrapped in a BufferedInputStream with a 8 KB buffer
This reads the file in chunks with a small buffer, minimizing memory footprint.
- B
Read the entire file into a byte array using Files.readAllBytes()
Why wrong: This loads the entire file into memory, which is not memory-efficient for large files.
- C
Use a FileReader wrapped in a BufferedReader to read lines
Why wrong: FileReader is for character data, not binary files, and still holds data in memory.
- D
Use a RandomAccessFile to read the file in segments
Why wrong: RandomAccessFile is not memory-efficient and is more complex; BufferedInputStream is simpler and adequate.
A Java application writes sensitive user data to a file. To ensure that data is not left in the file system after the application crashes, which practice should be followed?
Trap 1: Call flush() after every write operation
Flush only ensures data is sent to the OS, but doesn't guarantee atomicity or cleanup on crash.
Trap 2: Delete the file manually in a finally block
If the JVM crashes abruptly, the finally block may not execute, leaving the file.
Trap 3: Use a FileLock to prevent concurrent access
FileLock prevents concurrent access but does not prevent data residue after a crash.
- A
Call flush() after every write operation
Why wrong: Flush only ensures data is sent to the OS, but doesn't guarantee atomicity or cleanup on crash.
- B
Delete the file manually in a finally block
Why wrong: If the JVM crashes abruptly, the finally block may not execute, leaving the file.
- C
Use a FileLock to prevent concurrent access
Why wrong: FileLock prevents concurrent access but does not prevent data residue after a crash.
- D
Write to a temporary file, then use Files.move() with ATOMIC_MOVE to replace the target file
Atomic move ensures the target file is either fully written or not replaced, preventing partial writes.
Which THREE are benefits of using the NIO.2 API over the java.io API?
Trap 1: Better performance for all I/O operations compared to java.io.
Performance gains vary; not all operations are faster.
Trap 2: Automatic file compression when writing.
Compression is not built-in; it requires additional libraries.
- A
Better performance for all I/O operations compared to java.io.
Why wrong: Performance gains vary; not all operations are faster.
- B
Simplified recursive file operations using FileVisitor.
walkFileTree and SimpleFileVisitor simplify recursive traversal.
- C
Access to file attributes like creation time, owner, and permissions.
NIO.2 provides attribute views for various file systems.
- D
Automatic file compression when writing.
Why wrong: Compression is not built-in; it requires additional libraries.
- E
Support for symbolic links and other file system features.
NIO.2 provides methods for creating and reading symbolic links.
A developer needs to copy a large directory tree from one location to another, preserving file attributes. Which method should be used?
Trap 1: Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES)
Files.copy does not copy directories recursively.
Trap 2: Use Files.walk() and then Files.copy() for each entry
Files.walk returns a stream; using Files.copy on directories fails.
Trap 3: Use FileUtils.copyDirectory from Apache Commons IO
This is not part of standard Java SE; the question expects standard API.
- A
Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES)
Why wrong: Files.copy does not copy directories recursively.
- B
Implement a FileVisitor using Files.walkFileTree and copy each file with COPY_ATTRIBUTES
walkFileTree allows recursive traversal and attribute preservation.
- C
Use Files.walk() and then Files.copy() for each entry
Why wrong: Files.walk returns a stream; using Files.copy on directories fails.
- D
Use FileUtils.copyDirectory from Apache Commons IO
Why wrong: This is not part of standard Java SE; the question expects standard API.
Which TWO statements about java.io and java.nio.file packages are true?
Trap 1: java.io.Console can be used to read from and write to the standard…
Console is for interacting with the system console, not general streams.
Trap 2: java.io.FileInputStream supports the mark and reset methods.
FileInputStream does not support mark/reset; BufferedInputStream does.
Trap 3: java.nio.file.Path is a class that represents a file path.
Path is an interface, not a class.
- A
java.io.Console can be used to read from and write to the standard streams of the JVM.
Why wrong: Console is for interacting with the system console, not general streams.
- B
java.nio.file.Files class provides methods for operating on symbolic links.
Files has methods like isSymbolicLink, createSymbolicLink, etc.
- C
java.io.RandomAccessFile can be used for both reading and writing to a file.
RandomAccessFile supports read and write operations.
- D
java.io.FileInputStream supports the mark and reset methods.
Why wrong: FileInputStream does not support mark/reset; BufferedInputStream does.
- E
java.nio.file.Path is a class that represents a file path.
Why wrong: Path is an interface, not a class.
What is the output of the program?
Exhibit
Refer to the exhibit.
$ cat list.txt
A
B
C
D
$ cat ListDemo.java
import java.util.*;
import java.util.stream.*;
public class ListDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("A", "B", "C", "D"));
list.removeIf(s -> s.compareTo("C") > 0);
System.out.println(list);
}
}
$ javac ListDemo.java && java ListDemoTrap 1: [A, B, C, D]
No removal.
Trap 2: [A, B, D]
C is not removed.
Trap 3: [B, C, D]
A is not removed.
- A
[A, B, C, D]
Why wrong: No removal.
- B
[A, B, D]
Why wrong: C is not removed.
- C
[A, B, C]
Correct: D removed.
- D
[B, C, D]
Why wrong: A is not removed.
A developer is designing a method that processes a stream of Employee objects. The method needs to group employees by department and then, within each department, sort by salary in descending order, and collect the top 3 highest-paid employees per department into a list. Which approach correctly accomplishes this using streams?
Trap 1: stream.collect(Collectors.toMap(Employee::getDepartment, e -> {…
toMap is intended for one-to-one mapping; merging lists is complex and error-prone, and does not guarantee correct per-department top 3.
Trap 2: stream.sorted(Comparator.comparing(Employee::getSalary).reversed()).…
Sorting globally before grouping loses per-department top 3; the top 3 overall may all be from one department.
Trap 3: stream.collect(Collectors.groupingBy(Employee::getDepartment,…
This collects all employees into a Map then flattens, but flatMap is unnecessary and order may not be maintained properly.
- A
stream.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.collectingAndThen(Collectors.toList(), list -> list.stream().sorted(Comparator.comparing(Employee::getSalary).reversed()).limit(3).collect(Collectors.toList()))))
This groups by department, then for each group sorts descending and limits to 3, exactly as required.
- B
stream.collect(Collectors.toMap(Employee::getDepartment, e -> { List<Employee> l = new ArrayList<>(); l.add(e); return l; }, (l1, l2) -> { l1.addAll(l2); l1.sort(Comparator.comparing(Employee::getSalary).reversed()); return l1.subList(0, Math.min(3, l1.size())); }))
Why wrong: toMap is intended for one-to-one mapping; merging lists is complex and error-prone, and does not guarantee correct per-department top 3.
- C
stream.sorted(Comparator.comparing(Employee::getSalary).reversed()).collect(Collectors.groupingBy(Employee::getDepartment, Collectors.toList())).values().stream().map(l -> l.subList(0, Math.min(3, l.size()))).collect(Collectors.toList())
Why wrong: Sorting globally before grouping loses per-department top 3; the top 3 overall may all be from one department.
- D
stream.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.toList())).entrySet().stream().flatMap(e -> e.getValue().stream().sorted(Comparator.comparing(Employee::getSalary).reversed()).limit(3)).collect(Collectors.toList())
Why wrong: This collects all employees into a Map then flattens, but flatMap is unnecessary and order may not be maintained properly.
Which TWO are correct about parallel streams in Java? (Choose TWO.)
Trap 1: Parallel streams always improve performance over sequential streams.
Performance depends on data size and operation complexity.
Trap 2: Any lambda expression is safe to use in a parallel stream.
Lambdas must be stateless and non-interfering.
Trap 3: Using parallel streams guarantees the order of elements in the…
Order is not guaranteed unless using forEachOrdered.
- A
Parallel streams always improve performance over sequential streams.
Why wrong: Performance depends on data size and operation complexity.
- B
Any lambda expression is safe to use in a parallel stream.
Why wrong: Lambdas must be stateless and non-interfering.
- C
Using parallel streams guarantees the order of elements in the result.
Why wrong: Order is not guaranteed unless using forEachOrdered.
- D
Parallel streams use the common ForkJoinPool by default.
Default pool is ForkJoinPool.commonPool().
- E
To get correct results, operations should be stateless and non-interfering.
Statelessness ensures correct parallel execution.
Which of the following correctly formats a NumberFormat instance to display a currency value for the US locale with exactly two decimal places, rounding half-up?
Trap 1: NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);…
setRoundingMode is not available on NumberFormat.
Trap 2: NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);…
Only sets minimum, not maximum; extra digits could appear.
Trap 3: NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);…
Only sets maximum, not minimum; fewer digits could appear.
- A
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setRoundingMode(RoundingMode.HALF_UP);
Why wrong: setRoundingMode is not available on NumberFormat.
- B
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setMinimumFractionDigits(2);
Why wrong: Only sets minimum, not maximum; extra digits could appear.
- C
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setMaximumFractionDigits(2);
Why wrong: Only sets maximum, not minimum; fewer digits could appear.
- D
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
Default behavior includes two decimal places and rounding half-up.
Question Discussion
Share a tip, memory trick, or ask about the reasoning behind this question. Do not post real exam questions, leaked content, braindumps, or copyrighted exam material. Comments are moderated and may be removed without notice.
Sign in to join the discussion.