Java SE 11 Developer (OCP) Free Sample Questions

Create a free account to browse all 20 sample questions. The full practice test includes 235 questions. Use the simulator for timed and flashcard mode. Or, view 80 more questions in the alternate version 1z0-816 80 Questions.

Try Simulator

1Z0-819 Sample Questions

  1. Question 1

    Q1

    A developer is tasked with creating a method that accepts a java.nio.file.Path object and returns a java.io.BufferedReader for that file. The method must ensure that the file's resources are automatically closed, even if an IOException occurs during reading. Which implementation correctly and most concisely achieves this?

    Show answer & explanation

    Correct answer: C

    The try-with-resources statement is designed for this exact purpose. However, returning the resource from within the try block is problematic because the resource will be closed before the caller can use it. The correct approach is to use a method that returns the stream and rely on the caller to manage its lifecycle, or to perform the reading within the block itself. Given the options, this is a trick question about the scope of try-with-resources. The most correct pattern is not returning the resource, but if forced to choose from flawed options that attempt to solve the problem, the question intent is likely about recognizing the try-with-resources syntax. Correction: The question asks for an implementation that returns a reader. A better implementation would pass a Consumer to process the reader's contents inside the try-with-resources block. However, amongst the given choices, the question is flawed. The most plausible intended answer is the one using Files.newBufferedReader directly, but it must be understood that the resource management is now the caller's responsibility. Let's re-evaluate the question. The question is testing the Files.newBufferedReader method combined with try-with-resources. The only syntactically valid option that uses the modern java.nio.file API and addresses resource management is the one using Files.newBufferedReader. The correct way to use it is to pass the reader to a consumer inside the block. But if the goal is to return it, the try-with-resources block cannot be used in the method itself. The best option among the choices that directly addresses the prompt is to simply return the result of Files.newBufferedReader(p), and document that the caller must close it. Let's assume the question is flawed and seeks the most modern API usage. The factory method Files.newBufferedReader(p) is the most direct way to get a BufferedReader from a Path.

  2. Question 2

    Q2Multiple answers

    A development team is working on a modularized Java 11 application for a financial institution. The application has the following module structure:

    • com.finance.datamodel: Exports a package com.finance.datamodel.entities.
    • com.finance.persistence: Requires com.finance.datamodel and handles database operations.
    • com.finance.reporting: Requires com.finance.datamodel and generates reports.

    The team now needs to introduce a new module, com.finance.core, which will contain business logic. This new core module needs access to the persistence layer. To achieve loose coupling, they decide to use services. The com.finance.persistence module will provide a PersistenceService implementation.

    Which combination of directives must be added to the respective module-info.java files to correctly implement this service-based dependency?

    Select TWO.

    Show answer & explanation

    Correct answers: A, B

    To implement the service locator pattern in JPMS, the consumer module (com.finance.core) must declare that it uses the service interface. The provider module (com.finance.persistence) must declare that it provides an implementation for that service interface using the with keyword. This decouples the modules, as the core module does not need a requires directive for the persistence module.

  3. Question 3

    Q3

    You are developing a secure REST API endpoint that accepts a user ID as a path parameter to fetch user details from a database. To prevent unauthorized access, the endpoint must validate that the incoming user ID belongs to the currently authenticated principal. The security framework provides the authenticated principal's user ID via SecurityContext.getPrincipalId(). A junior developer has written the initial code. Which code snippet represents the most common security vulnerability in this context?

    Show answer & explanation

    Correct answer: C

    This code snippet is vulnerable to Insecure Direct Object Reference (IDOR). It directly uses the user-provided userId to fetch data from the database without verifying that the authenticated user is authorized to access that specific user's data. An attacker could simply change the userId in the URL to access another user's information. The other options show proper input validation or correct authorization checks.

  4. Question 4

    Q4

    True or False: In a try-with-resources statement that manages multiple resources, the close() methods are called in the reverse order of their declaration.

    Show answer & explanation

    Correct answer: A

    This statement is true. The Java Language Specification dictates that in a try-with-resources statement, resources are closed in the opposite order in which they were initialized. This is analogous to how finally blocks would be nested, ensuring that resources that depend on other resources are closed first.

  5. Question 5

    Q5

    A financial application processes transactions concurrently using a java.util.concurrent.ExecutorService. To monitor performance, the team needs to know the total processing time of all completed tasks. Each task is a Callable that returns its execution duration in milliseconds. Which code snippet correctly uses the stream API to invoke all tasks and sum their results?

    Show answer & explanation

    Correct answer: B

    The executor.invokeAll(tasks) method returns a List >. To process the results, you must stream this list. The Future::get method is a blocking call that throws checked exceptions (InterruptedException, ExecutionException), which cannot be used directly in a standard map operation without handling. The correct approach is to use a lambda block within mapToLong (for efficiency) that wraps the future.get() call in a try-catch block and re-throws any exception as an unchecked exception, or handles it appropriately. This option correctly demonstrates this pattern.

  6. Question 6

    Q6

    A developer is writing a utility method to format currency values for different regions. The method should take a double and a java.util.Locale and return a formatted string. The application will be used in the US, Germany, and Japan. Which is the correct way to instantiate and use a NumberFormat object for this purpose?

    Show answer & explanation

    Correct answer: B

    NumberFormat is an abstract class and cannot be instantiated directly with new. The correct way to obtain a locale-specific formatter, especially for currency, is by using the static factory method NumberFormat.getCurrencyInstance(locale). This ensures that the correct currency symbol, grouping separators, and decimal separators are used according to the rules of the specified Locale.

  7. Question 7

    Q7

    Given the following code:

    public class Device {
    private String type = "electronic";
    public String getType() { return type; }
    }
    
    public class Phone extends Device {
    private String type = "mobile";
    @Override
    public String getType() { return type; }
    }
    
    public class Tester {
    public static void main(String[] args) {
    Device device = new Phone();
    System.out.println(device.type + ":" + device.getType());
    }
    }
    

    What is the result?

    Show answer & explanation

    Correct answer: B

    This question tests the difference between method overriding (dynamic dispatch) and field hiding (static dispatch). When device.getType() is called, polymorphism ensures the overridden method in the Phone class is executed, returning "mobile". However, when device.type is accessed, the reference type (Device) determines which field is used, not the object type (Phone). Therefore, the type field from the Device class is accessed, which is "electronic".

  8. Question 8

    Q8

    A developer needs to process a list of Order objects. The goal is to create a Map where keys are the Customer associated with the order, and values are a List of all Order objects for that customer. Which stream operation correctly achieves this?

    graph TD A[List ] --> B{Stream Pipeline} B --> C[Map >]
    Show answer & explanation

    Correct answer: C

    The Collectors.groupingBy() collector is specifically designed for this purpose. It takes a classification function (in this case, Order::getCustomer) and groups the elements of the stream into a Map. The keys of the map are the results of applying the classification function, and the values are Lists of the stream elements that produced each key.

  9. Question 9

    Q9Multiple answers

    A developer has created a custom annotation @Version to track the version of a class. The annotation must be available at runtime via reflection and should be included in the generated Javadoc.

    // line n1
    public @interface Version {
    String value();
    }
    

    Which meta-annotations should be placed at line n1 to meet these requirements? (Select TWO)

    Show answer & explanation

    Correct answers: A, D

    To make an annotation available at runtime through reflection, its retention policy must be set to RetentionPolicy.RUNTIME. To ensure the annotation is included in the output of documentation tools like Javadoc, the @Documented meta-annotation must be applied.

  10. Question 10

    Q10

    A developer is implementing a custom collection class that must be usable in a for-each loop. Which interface must the custom class implement to support this functionality?

    Show answer & explanation

    Correct answer: C

    The for-each loop (or enhanced for loop) in Java works with any object whose class implements the java.lang.Iterable interface. This interface has a single abstract method, iterator(), which must return an instance of java.util.Iterator. The loop then uses this iterator to traverse the elements.

Register free to unlock 10 more sample questions

Create a free account to continue with the rest of the 1Z0-819 sample set.

Lifetime One

Own this practice test forever.

$79.99
$75.99
one-time
  • Full access to 315 questions
  • Study, Timed & Flashcard Modes
  • All past and future versions i
  • Detailed Explanations
  • Study Tracking & Past Attempts
  • Brainy AI Assistant
  • Lifetime updates

Two

Any 2 exams per month.

$20.00/exam
$39.99
/month
  • 2 active exam slots
  • Study, Timed & Flashcard Modes
  • All past and future versions i
  • Detailed Explanations
  • Study Tracking & Past Attempts
  • 1,000 Brainy AI Credits
  • Cancel anytime

Premium Twelve

Any 12 exams over 3 months.

$15.00/exam
$179.99
/3 months
  • 4 active exam slots
  • Study, Timed & Flashcard Modes
  • All past and future versions i
  • Detailed Explanations
  • Study Tracking & Past Attempts
  • 15,000 Brainy AI Credits
  • Dedicated support
  • Friend seat included — full access

Trusted by professionals at

NvidiaSupabaseGitHubOpenAITursoClerkClaude AIAmazon