Java SE 17 Developer (OCP) Practice Questions
Prepare for 1Z0-829 with more than an answer.
- Exam fee
- $245 USD
- Level
- Professional
- Valid for
- Lifetime (no expiration)
Domains covered on the exam 11
- Handling date, time, text, numeric and boolean values10%
- Controlling Program Flow8%
- Utilizing Java Object-Oriented Approach30%
- Handling Exceptions7%
- Working with Arrays and Collections10%
- Working with Streams and Lambda expressions12%
- Packaging and deploying Java code and use the Java Platform Module System8%
- Managing concurrent code execution8%
- Using Java I/O API7%
- Accessing databases using JDBC5%
- Implementing Localization5%
- 1
A developer has a
List >and wants to get aListcontaining all non-empty string values. Which of the following stream pipelines correctly and most efficiently accomplishes this?Show answer details
Correct answer: B
This is the most idiomatic and efficient solution. Since Java 9,
Optional.stream()returns a stream of one element if the optional is present, or an empty stream if it is empty. TheflatMapoperation effectively unnests these streams, filtering out the empty ones and extracting the values from the present ones into a singleStream, which is then collected into a list. - 2
Case Study:
A logistics company is modernizing its package tracking system. The system needs to represent different types of packages, each with specific attributes. The requirements are as follows:
- There are three and only three types of packages:
Standard,Express, andFragile. - No other package types should be permissible in the system to ensure strict domain modeling.
- A
Standardpackage has a weight. - An
Expresspackage has a weight and a priority level (an integer). - A
Fragilepackage has a weight and special handling instructions (a String). - All package types should be immutable data carriers.
A senior developer proposes using a combination of sealed interfaces and records to model this domain. The goal is to create a type-safe hierarchy that can be effectively processed, for example, in a
switchexpression for calculating shipping costs.Which code implementation best satisfies all the given requirements?
Show answer details
Correct answer: B
This solution perfectly meets all requirements. The
sealed interface Packagewith apermitsclause ensures that onlyStandard,Express, andFragilecan implement it, satisfying requirement #1 and #2. Usingrecordfor each package type makes them immutable data carriers with appropriate fields, satisfying requirements #3, #4, #5, and #6. This structure is ideal for modern, type-safe domain modeling and works perfectly with pattern matching inswitchexpressions. - There are three and only three types of packages:
- 3
A developer is writing a JDBC utility to fetch user data. They need to ensure that the
ConnectionandPreparedStatementare always closed, even if an exception occurs during result set processing. Which code structure provides the most robust and modern approach to achieve this?Show answer details
Correct answer: C
The
try-with-resourcesstatement is the modern, preferred way to manage resources that implement theAutoCloseableinterface, such asConnection,Statement, andResultSet. By declaring the resources in the parentheses aftertry, the developer guarantees thatclose()will be called on them automatically at the end of the block, in the correct reverse order of declaration, regardless of whether an exception is thrown. This approach is more concise and less error-prone than manualfinallyblocks. - 4
True or False: In the Java Platform Module System (JPMS), if module
Arequires moduleB(requires B;), and moduleBexports packagep1(exports p1;), then moduleAcan access public types in packagep1by default.Show answer details
Correct answer: A
This statement is true. This describes the fundamental principle of readability in JPMS. The
requiresdirective in module A makes module B readable to A. Theexportsdirective in module B makes the public types within packagep1accessible to any module that requires B. Therefore, module A can access the public types inp1. - 5
A developer is working with a
java.util.concurrent.ExecutorServiceto run asynchronous tasks. After submitting all tasks, the developer wants to shut down the service gracefully, allowing currently executing tasks to finish but rejecting any new tasks. Which method should be called on theExecutorServiceinstance?Show answer details
Correct answer: A
The
shutdown()method initiates an orderly shutdown of theExecutorService. It stops accepting new tasks, but previously submitted tasks will be allowed to complete. This is the standard method for a graceful shutdown. - 6
Consider the following record definition and its usage. What will be the output of this program?
Show answer details
Correct answer: C
The code defines a record
Pointwith a compact constructor for validation. Records automatically generate accessor methods (e.g.,x(),y()), and anequals()method that compares the state of the record components. Sincep1andp2are created with the samexandyvalues,p1.equals(p2)will returntrue. The first print statement correctly accesses the components. - 7
A developer is serializing an object of class
Employee. TheEmployeeclass contains a field for a password, which should not be saved to disk for security reasons. The class also needs to maintain a version UID for compatibility. Which two modifications are necessary to achieve this? (Select TWO)Show answer details
Correct answer: A, C
For an object to be serializable, its class must implement the
java.io.Serializablemarker interface. This is the primary requirement to enable the serialization mechanism for a class.The
transientkeyword is used to mark a field that should be excluded from the serialization process. When an object is serialized, the values of its transient fields are ignored. - 8
Case Study:
A logistics company is modernizing its package tracking system. The system needs to represent different types of packages, each with specific attributes. The requirements are as follows:
- There are three and only three types of packages:
Standard,Express, andFragile. - No other package types should be permissible in the system to ensure strict domain modeling.
- A
Standardpackage has a weight. - An
Expresspackage has a weight and a priority level (an integer). - A
Fragilepackage has a weight and special handling instructions (a String). - All package types should be immutable data carriers.
A senior developer proposes using a combination of sealed interfaces and records to model this domain. The goal is to create a type-safe hierarchy that can be effectively processed, for example, in a
switchexpression for calculating shipping costs.Which code implementation best satisfies all the given requirements?
Show answer details
Correct answer: B
This solution perfectly meets all requirements. The
sealed interface Packagewith apermitsclause ensures that onlyStandard,Express, andFragilecan implement it, satisfying requirement #1 and #2. Usingrecordfor each package type makes them immutable data carriers with appropriate fields, satisfying requirements #3, #4, #5, and #6. This structure is ideal for modern, type-safe domain modeling and works perfectly with pattern matching inswitchexpressions. - There are three and only three types of packages:
- 9
Case Study
A software architect is designing a system for a payment gateway. The system must handle different types of payment methods. The core requirement is to have a common
PaymentMethodtype, but restrict implementations to a known, fixed set:CreditCard,PayPal, andBankTransfer. No other developers, now or in the future, should be able to create new, unknown implementations ofPaymentMethodoutside of the core payment module. This strict control is necessary for security and compliance audits.The architect wants to model this domain using the most effective and modern object-oriented features available in Java 17 to enforce this restriction at the compiler level.
Which design provides the strongest compile-time safety and best expresses the architect's intent?
Show answer details
Correct answer: D
This is the ideal solution. The
sealedkeyword is designed precisely for this scenario. It allows a class or interface to declare which other types are permitted to extend or implement it. This enforces the restriction at compile time, perfectly matching the architect's requirement for a closed set of implementations. - 10
A developer is building a system that processes different geometric shapes. The following
sealedinterface is defined:sealed interface Shape permits Circle, Rectangle {} final class Circle implements Shape { /* ... */ } final class Rectangle implements Shape { /* ... */ }Later, another developer in a different package tries to define a new shape:
// in another package public final class Triangle implements Shape { /* ... */ }What is the result of this attempt?
Show answer details
Correct answer: C
The purpose of a
sealedinterface or class is to restrict which other types can implement or extend it. BecauseShapeis sealed and onlypermits CircleandRectangle, any attempt to implement it with another class likeTrianglewill result in a compilation error. This is a key feature of sealed types for creating closed hierarchies.
