1Z0-829 Sample Questions & Answers
Explores object-oriented design with classes and records, by far the largest share, plus primitives, text and date-time values, program flow, exceptions, concurrency, I/O, JDBC, the module system, arrays, collections, streams and lambda expressions.
Launch the full 1Z0-829 simulator →Free 1Z0-829 Sample Questions with Answers
Real questions from the Java SE 17 Developer (OCP) practice test — answers and explanations included. Showing 10 of 20 free samples.
- Question 1Advanced
Utilizing Java Object-Oriented Approach · Java Inheritance
A developer is designing a system to model hierarchical configurations. A
ConfigNodecan contain otherConfigNodeobjects. The design must ensure that only specific, predefined types of nodes (FileNode,DirectoryNode,PropertyNode) can extendConfigNode. Additionally,DirectoryNodeitself must be extensible, but only byRootDirectoryNode. Which class and interface structure best achieves these requirements?Show answer & explanation
Correct answer: B
This solution correctly uses
sealedclasses to enforce the inheritance constraints.ConfigNodeissealedand explicitlypermitsonlyFileNode,DirectoryNode, andPropertyNode.FileNodeandPropertyNodearefinal, preventing further extension as required.DirectoryNodeis declarednon-sealed, which breaks the sealing and allows any class, includingRootDirectoryNode, to extend it. This perfectly matches all design requirements. - Question 2Intermediate
Utilizing Java Object-Oriented Approach · Java Inheritance
A developer is modeling a system for handling financial transactions using a sealed interface. The goal is to ensure that all possible transaction types are handled in a
switchexpression without requiring adefaultcase. Given the following sealed hierarchy, what is the problem with theprocessTransactionmethod?sealed interface Transaction permits Deposit, Withdrawal, FxTrade {} final record Deposit(double amount) implements Transaction {} final record Withdrawal(double amount) implements Transaction {} // FxTrade is a non-sealed class to allow for future extension non-sealed class FxTrade implements Transaction {} class SpotTrade extends FxTrade {} public class TransactionProcessor { public static String processTransaction(Transaction tx) { return switch (tx) { case Deposit d -> "Processing Deposit"; case Withdrawal w -> "Processing Withdrawal"; case FxTrade f -> "Processing FX Trade"; }; } }Show answer & explanation
Correct answer: B
This is the correct answer. Because
FxTradeis declared asnon-sealed, other classes (likeSpotTradeor any other class in any package) can extend it. Therefore, the compiler cannot guarantee that all possible subtypes ofTransactionare covered by thecaselabels. To fix this, theswitchexpression must include adefaultcase to handle any unknown subtypes ofFxTrade. - Question 3Advanced
Utilizing Java Object-Oriented Approach · Java Inheritance
Case Study
A development team at a logistics company is modeling various types of shipping containers. The requirements are as follows:
- There are three primary types of containers:
Standard,Refrigerated, andOpenTop. - All container types must have a
capacityand acontainerId. Refrigeratedcontainers must also have atemperaturesetting.- The system must be able to handle these specific container types exhaustively in
switchexpressions for processing logic. - In the future, a subcontractor may need to introduce a new
HeavyDutycontainer type that extends theStandardcontainer's functionality. This new type should NOT break the exhaustiveness of existingswitchstatements.
Which class hierarchy design best fulfills all these requirements using modern Java features?
classDiagram direction LR class ShipmentProcessor { +process(Container c) } class Container { > +double capacity +String containerId } class Standard { +double capacity +String containerId } class Refrigerated { +double capacity +String containerId +double temperature } class OpenTop { +double capacity +String containerId } class HeavyDuty { +double maxLoad } Container <|.. Standard Container <|.. Refrigerated Container <|.. OpenTop Standard <|-- HeavyDuty ShipmentProcessor ..> Container : processesShow answer & explanation
Correct answer: C
This design correctly meets all requirements.
sealed interface Containerensures thatswitchexpressions can be exhaustive for the three primary types. UsingrecordsforRefrigeratedandOpenTopis ideal for these immutable data carriers. Crucially, makingStandardanon-sealed classexplicitly allows it to be extended by other classes, such asHeavyDuty, fulfilling the extensibility requirement. BecauseHeavyDutyis not a direct permitted subtype ofContainer, existingswitchstatements overContainerremain exhaustive and do not need to be updated, preventing code breakage. - There are three primary types of containers:
- Question 4Intermediate
Utilizing Java Object-Oriented Approach · Java Inheritance
A developer is implementing a
sealedinterface to model different types of application events. Aswitchexpression is used to process these events. What is the result of compiling and running the following code?sealed interface AppEvent permits LoginEvent, LogoutEvent, ErrorEvent { String getUserId(); } final record LoginEvent(String userId, String ipAddress) implements AppEvent {} final record LogoutEvent(String userId, String reason) implements AppEvent {} final record ErrorEvent(String userId, String errorMsg) implements AppEvent {} public class EventProcessor { public String process(AppEvent event) { return switch (event) { case LoginEvent le -> "Login from " + le.ipAddress(); case LogoutEvent le -> "Logout because " + le.reason(); // Missing case for ErrorEvent }; } }graph TD A[AppEvent] --> B(LoginEvent) A --> C(LogoutEvent) A --> D(ErrorEvent) style A fill:#f9f,stroke:#333,stroke-width:2pxShow answer & explanation
Correct answer: B
One of the key benefits of combining
sealedtypes withswitchexpressions is compile-time exhaustiveness checking. BecauseAppEventis a sealed interface, the compiler knows all possible direct subtypes (LoginEvent,LogoutEvent,ErrorEvent). Theswitchexpression must cover all these permitted subtypes or include adefaultcase. Since thecaseforErrorEventis missing and there is nodefaultbranch, the compiler will report an error, preventing potential runtime errors from unhandled types. - Question 5Intermediate
Handling date, time, text, numeric and boolean values · Manipulate date, time, duration, period, instant and time-zone objects using Date-Time API
A financial application needs to process transactions from different time zones. A developer writes the following code to handle a transaction timestamp from Tokyo and convert it to the system's default time zone. What is the outcome of executing this code snippet?
Show answer & explanation
Correct answer: C
The code correctly uses the
java.timeAPI.LocalDateTime.atZone()is the correct way to combine a local date-time with a time zone, creating aZonedDateTime.withZoneSameInstant()correctly converts this instant to another time zone. The program will printTokyo: 10:00and then the equivalent time in the system's default time zone, reflecting the offset difference. - Question 6IntermediateSelect 2
Packaging and deploying Java code and use the Java Platform Module System · Define modules and their dependencies, expose module content including for reflection. Define services, producers, and consumers
A developer is creating a Java module for a billing service. The module
com.example.billingneeds to use a logging framework provided as a service. It also needs to expose its main API packagecom.example.billing.apibut keep the implementation packagecom.example.billing.internalhidden. Whichmodule-info.javafile correctly defines these requirements? (Select TWO)Show answer & explanation
Correct answers: A, D
This is a correct definition.
exports com.example.billing.api;makes the API package public, anduses com.example.logging.Logger;declares that this module consumes theLoggerservice, allowing it to discover and use implementations provided by other modules.This is also a correct definition.
requires staticindicates an optional dependency at compile time, which is a valid way to depend on a service provider module. The core requirements of exporting the API package (exports) and consuming the service (uses) are correctly stated. - Question 7Advanced
Managing concurrent code execution · Develop thread-safe code, using different locking mechanisms and concurrent API
A developer is implementing a thread-safe counter. To avoid the overhead of explicit locking, they decide to use
java.util.concurrent.atomic.AtomicInteger. Which statement accurately describes the primary mechanism that makesAtomicIntegerthread-safe without traditional locks?Show answer & explanation
Correct answer: C
The core of
AtomicInteger's lock-free thread safety is the Compare-And-Swap (CAS) instruction provided by the underlying CPU. A CAS operation is an atomic instruction that reads a memory location, compares its content with an expected value, and, only if they match, modifies the memory location's content to a new given value. This allows for non-blocking, optimistic updates, avoiding the performance costs and potential deadlocks of traditional locking. - Question 8Intermediate
Implementing Localization · Implement localization using locales, resource bundles, parse and format messages, dates, times, and numbers including currency and percentage values
A developer needs to format monetary values for an e-commerce application that serves customers in Germany and the United States. Given the following code, what is the expected output?
Show answer & explanation
Correct answer: B
NumberFormat.getCurrencyInstance(Locale)creates a formatter that correctly applies the currency symbol, grouping separators (comma vs. period), and decimal separator (period vs. comma) for the specified locale. Foren_US, it formats as$12,345.67. Forde_DE, it formats as12.345,67 €, correctly using the period as a grouping separator, comma as a decimal separator, and placing the Euro symbol at the end (a common convention). - Question 9Intermediate
Working with Streams and Lambda expressions · Use Java object and primitive Streams, including lambda expressions implementing functional interfaces, to supply, filter, map, consume, and sort data
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 & explanation
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. - Question 10Advanced
Utilizing Java Object-Oriented Approach · Java Inheritance
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 & explanation
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:
Ready for the real thing?
The full 1Z0-829 simulator has every exam-style question, timed mode, and instant scoring.