Java SE 17 Developer (OCP) Free Sample Questions

Description

Covers primitives, text and date-time handling, program flow control, object-oriented class and record design, exceptions, collections, streams and lambdas, the module system, concurrency, and JDBC.

20 free sample questions225 in the full practice test Other versions: 1z0-809(366),1z0-816(80),1Z0-819(235)

Try simulator

1Z0-829 Sample Questions

  1. Question 1

    Advanced

    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:

    1. There are three and only three types of packages: Standard, Express, and Fragile.
    2. No other package types should be permissible in the system to ensure strict domain modeling.
    3. A Standard package has a weight.
    4. An Express package has a weight and a priority level (an integer).
    5. A Fragile package has a weight and special handling instructions (a String).
    6. 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 switch expression for calculating shipping costs.

    Which code implementation best satisfies all the given requirements?

    Answer and explanation

    Correct answer: B

    This solution perfectly meets all requirements. The sealed interface Package with a permits clause ensures that only Standard, Express, and Fragile can implement it, satisfying requirement #1 and #2. Using record for 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 in switch expressions.

  2. Question 2

    Advanced

    Utilizing Java Object-Oriented Approach · Java Inheritance

    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 PaymentMethod type, but restrict implementations to a known, fixed set: CreditCard, PayPal, and BankTransfer. No other developers, now or in the future, should be able to create new, unknown implementations of PaymentMethod outside 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?

    Answer and explanation

    Correct answer: D

    This is the ideal solution. The sealed keyword 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.

  3. Question 3

    Beginner

    Utilizing Java Object-Oriented Approach · Java Inheritance

    A developer is building a system that processes different geometric shapes. The following sealed interface 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?

    Answer and explanation

    Correct answer: C

    The purpose of a sealed interface or class is to restrict which other types can implement or extend it. Because Shape is sealed and only permits Circle and Rectangle, any attempt to implement it with another class like Triangle will result in a compilation error. This is a key feature of sealed types for creating closed hierarchies.

  4. Question 4

    Intermediate

    Utilizing Java Object-Oriented Approach · Java Inheritance

    Case Study

    A financial services company is designing a system to model various types of accounts. The system must support CheckingAccount, SavingsAccount, and InvestmentAccount. A key architectural requirement is that the set of account types is fixed and cannot be extended by other development teams or third-party libraries. This ensures that all account processing logic can be handled exhaustively and safely within the core application.

    The architect wants to create a common supertype called Account that all specific account types will implement. The solution must enforce the closed hierarchy at compile time and should use modern Java features for conciseness and type safety.

    Which code snippet best models this domain according to the requirements?

    classDiagram direction LR class Account { > +getAccountNumber() +getBalance() } class CheckingAccount class SavingsAccount class InvestmentAccount Account <|.. CheckingAccount : implements Account <|.. SavingsAccount : implements Account <|.. InvestmentAccount : implements
    Answer and explanation

    Correct answer: B

    This solution perfectly meets the requirements. Using a sealed interface with a permits clause restricts the implementation of Account to only the three specified classes (CheckingAccount, SavingsAccount, InvestmentAccount). This enforces the closed hierarchy at compile time, preventing any other class from implementing the Account interface. Using final record for the implementations is a good choice for concise, immutable data carriers, which is often suitable for account types.

  5. Question 5

    Intermediate

    Utilizing Java Object-Oriented Approach · Java Inheritance

    A financial data processing application uses a sealed interface Transaction with three implementing records: Deposit, Withdrawal, and Transfer. A method is designed to process a list of these transactions and calculate a risk score. Examine the following code:

    sealed interface Transaction permits Deposit, Withdrawal, Transfer {}
    record Deposit(double amount) implements Transaction {}
    record Withdrawal(double amount) implements Transaction {}
    record Transfer(double amount, String recipient) implements Transaction {}
    
    public class TransactionProcessor {
    public int calculateRisk(Transaction tx) {
    return switch (tx) {
    case Deposit d -&gt; {
    if (d.amount() &gt; 10000) yield 2;
    yield 1;
    }
    case Withdrawal w -&gt; {
    if (w.amount() &gt; 5000) yield 3;
    yield 1;
    }
    // Missing Transfer case
    };
    }
    }
    

    What is the result of compiling the TransactionProcessor class?

    Answer and explanation

    Correct answer: B

    The compiler enforces exhaustiveness for switch expressions on sealed types. Since Transaction is a sealed interface permitting Deposit, Withdrawal, and Transfer, any switch expression on a Transaction object must handle all three cases or provide a default case. The provided code is missing a case for Transfer, so it will result in a compilation error.

  6. Question 6

    Advanced

    Utilizing Java Object-Oriented Approach · Java Inheritance

    A developer is designing a system to model hierarchical configurations. A ConfigNode can contain other ConfigNode objects. The design must ensure that only specific, predefined types of nodes (FileNode, DirectoryNode, PropertyNode) can extend ConfigNode. Additionally, DirectoryNode itself must be extensible, but only by RootDirectoryNode. Which class and interface structure best achieves these requirements?

    Answer and explanation

    Correct answer: B

    This solution correctly uses sealed classes to enforce the inheritance constraints. ConfigNode is sealed and explicitly permits only FileNode, DirectoryNode, and PropertyNode. FileNode and PropertyNode are final, preventing further extension as required. DirectoryNode is declared non-sealed, which breaks the sealing and allows any class, including RootDirectoryNode, to extend it. This perfectly matches all design requirements.

  7. Question 7

    Intermediate

    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 switch expression without requiring a default case. Given the following sealed hierarchy, what is the problem with the processTransaction method?

    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 -&gt; "Processing Deposit";
    case Withdrawal w -&gt; "Processing Withdrawal";
    case FxTrade f -&gt; "Processing FX Trade";
    };
    }
    }
    
    Answer and explanation

    Correct answer: B

    This is the correct answer. Because FxTrade is declared as non-sealed, other classes (like SpotTrade or any other class in any package) can extend it. Therefore, the compiler cannot guarantee that all possible subtypes of Transaction are covered by the case labels. To fix this, the switch expression must include a default case to handle any unknown subtypes of FxTrade.

  8. Question 8

    Advanced

    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:

    1. There are three primary types of containers: Standard, Refrigerated, and OpenTop.
    2. All container types must have a capacity and a containerId.
    3. Refrigerated containers must also have a temperature setting.
    4. The system must be able to handle these specific container types exhaustively in switch expressions for processing logic.
    5. In the future, a subcontractor may need to introduce a new HeavyDuty container type that extends the Standard container's functionality. This new type should NOT break the exhaustiveness of existing switch statements.

    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 : processes

    Answer and explanation

    Correct answer: C

    This design correctly meets all requirements. sealed interface Container ensures that switch expressions can be exhaustive for the three primary types. Using records for Refrigerated and OpenTop is ideal for these immutable data carriers. Crucially, making Standard a non-sealed class explicitly allows it to be extended by other classes, such as HeavyDuty, fulfilling the extensibility requirement. Because HeavyDuty is not a direct permitted subtype of Container, existing switch statements over Container remain exhaustive and do not need to be updated, preventing code breakage.

  9. Question 9

    Intermediate

    Utilizing Java Object-Oriented Approach · Java Inheritance

    A developer is implementing a sealed interface to model different types of application events. A switch expression 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 -&gt; "Login from " + le.ipAddress();
    case LogoutEvent le -&gt; "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:2px
    Answer and explanation

    Correct answer: B

    One of the key benefits of combining sealed types with switch expressions is compile-time exhaustiveness checking. Because AppEvent is a sealed interface, the compiler knows all possible direct subtypes (LoginEvent, LogoutEvent, ErrorEvent). The switch expression must cover all these permitted subtypes or include a default case. Since the case for ErrorEvent is missing and there is no default branch, the compiler will report an error, preventing potential runtime errors from unhandled types.

  10. Question 10

    Intermediate

    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?

    Answer and explanation

    Correct answer: C

    The code correctly uses the java.time API. LocalDateTime.atZone() is the correct way to combine a local date-time with a time zone, creating a ZonedDateTime. withZoneSameInstant() correctly converts this instant to another time zone. The program will print Tokyo: 10:00 and then the equivalent time in the system's default time zone, reflecting the offset difference.

Register free for 10 more questions

Or unlock all 225 1Z0-829 questions with explanations, timed mode and flashcards.