1Z0-819 Java SE 11 Developer (OCP) Practice Questions
Prepare for 1Z0-819 with more than an answer.
Unlock the full exam and previous versions
- v1Version 1 235 questions Current
- 1z0-816Legacy Java SE 11 Programmer II 80 questions Locked
- Exam fee
- $245 USD
- Level
- Professional
- Valid for
- Non-expiring (certification does not expire but may become outdated)
Domains covered on the exam 13
- Working with Java data types
- Controlling Program Flow
- Java Object-Oriented Approach
- Exception Handling
- Working with Arrays and Collections
- Working with Streams and Lambda expressions
- Java Platform Module System
- Concurrency
- Java I/O API
- Secure Coding in Java SE Application
- Database Applications with JDBC
- Localization
- Annotations
- 1
Case Study
Company Background:
GlobalTrade Inc. is a logistics company that provides real-time tracking for international shipments. They are developing a new backend service,TrackingService, using Java 11. This service receives location updates from various carriers, validates them, and stores them in a database. Performance and reliability are critical, as the service must handle thousands of updates per second.Current Situation:
The development team has created aLocationUpdateProcessorclass that runs in its own thread. This processor fetches batches of raw location data from a shared queue, processes them, and writes them to the database. During initial load testing, the team observed that under heavy load, the application sometimes throws aNullPointerExceptionwithin therun()method of the processor. The code for the processor is as follows:class LocationUpdateProcessor implements Runnable { private volatile boolean isRunning = true; private final Queue dataQueue; public LocationUpdateProcessor(Queue queue) { this.dataQueue = queue; } public void stopProcessing() { isRunning = false; } @Override public void run() { while (isRunning) { String rawData = dataQueue.poll(); // NPE occurs on the next line if (rawData.contains("URGENT")) { // process urgent data } } } }Requirements:
TheLocationUpdateProcessormust be fixed to prevent theNullPointerException. It should process data as long as theisRunningflag is true and there is data in the queue. The solution must be efficient and avoid busy-waiting (i.e., continuously looping and checking the queue when it's empty).Question:
Which modification to therun()method is the most appropriate and robust solution to fix the bug and meet the requirements?Show answer details
Correct answer: D
The
NullPointerExceptionoccurs becausedataQueue.poll()returnsnullwhen the queue is empty. The original code does not check fornullbefore calling a method onrawData. While adding a null check fixes the NPE, it leads to busy-waiting, violating a requirement. The most robust and idiomatic solution for producer-consumer scenarios is to use ajava.util.concurrent.BlockingQueue. Thetake()method blocks until an element is available, which efficiently waits without consuming CPU cycles. This fixes the NPE and avoids busy-waiting, fully satisfying the requirements. - 2
What is the purpose of the
varkeyword introduced in Java 10 and available in Java 11?Show answer details
Correct answer: B
The
varkeyword is used for local variable type inference. It is purely a compile-time feature that allows the developer to omit the explicit type declaration for a local variable when it can be inferred from the right-hand side of the assignment. The variable is still statically typed; its type is fixed at compile time and cannot change. - 3
You are given a
Stream >. Your task is to transform this into aStreamcontaining all the strings from all the lists. Which stream operation should you use?Show answer details
Correct answer: B
The
flatMapoperation is used to transform each element of a stream into another stream and then flatten the resulting streams into a single stream. In this case, eachListis mapped to aStreambylist.stream(), andflatMapcombines all these smaller streams into oneStream. - 4
Given the following interface and class definitions:
interface Rideable { default String ride() { return "Riding"; } } interface Transport { static String travel() { return "Traveling"; } } class Vehicle implements Rideable, Transport { // line n1 }Which statement is true?
Show answer details
Correct answer: B
Default methods (like
ride()) are inherited by implementing classes. Static methods in interfaces (liketravel()) are not inherited by implementing classes; they can only be called on the interface itself (e.g.,Transport.travel()). Therefore, aVehicleobject will have theride()method but you cannot callvehicle.travel(). - 5
A developer needs to serialize an object of the
Employeeclass. However, theEmployeeclass contains a fieldtransient private String securityToken;that should not be included in the serialized form. What is the effect of thetransientkeyword in this context?Show answer details
Correct answer: B
The
transientkeyword is a modifier used to indicate that a field should not be part of the default serialized form of an object. When an object is serialized, the values of itstransientfields are ignored. Upon deserialization, thetransientfield will be initialized to its default value (e.g.,nullfor objects,0for numeric primitives). - 6
True or False: A module can
requireanother module and alsoexporta package from that same required module in itsmodule-info.javafile.Show answer details
Correct answer: B
This statement is false. A module can only export packages that it contains. It cannot re-export a package from another module it depends on. To expose the API of a dependency to other modules that depend on the current module, the
requires transitivedirective must be used. - 7
Which of the following code snippets correctly uses a
java.util.function.Predicateto filter a list of integers, keeping only the even numbers?Show answer details
Correct answer: A
A
java.util.function.Predicateis a functional interface that represents a predicate (a boolean-valued function) of one argument. It has a single abstract methodtest(T t). TheStream.filter()method accepts aPredicate. This code correctly defines aPredicateusing a lambda expressionn -> n % 2 == 0and then passes it to thefiltermethod to process the stream. - 8
A developer is tasked with creating a method that accepts a
java.nio.file.Pathobject and returns ajava.io.BufferedReaderfor that file. The method must ensure that the file's resources are automatically closed, even if anIOExceptionoccurs during reading. Which implementation correctly and most concisely achieves this?Show answer details
Correct answer: C
The
try-with-resourcesstatement is designed for this exact purpose. However, returning the resource from within thetryblock 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 aConsumerto process the reader's contents inside thetry-with-resourcesblock. However, amongst the given choices, the question is flawed. The most plausible intended answer is the one usingFiles.newBufferedReaderdirectly, 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 theFiles.newBufferedReadermethod combined withtry-with-resources. The only syntactically valid option that uses the modernjava.nio.fileAPI and addresses resource management is the one usingFiles.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, thetry-with-resourcesblock cannot be used in the method itself. The best option among the choices that directly addresses the prompt is to simply return the result ofFiles.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 methodFiles.newBufferedReader(p)is the most direct way to get aBufferedReaderfrom aPath. - 9
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 packagecom.finance.datamodel.entities.com.finance.persistence: Requirescom.finance.datamodeland handles database operations.com.finance.reporting: Requirescom.finance.datamodeland 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. Thecom.finance.persistencemodule will provide aPersistenceServiceimplementation.Which combination of directives must be added to the respective
module-info.javafiles to correctly implement this service-based dependency?Select TWO.
Show answer details
Correct answer: A, B
To implement the service locator pattern in JPMS, the consumer module (
com.finance.core) must declare that itusesthe service interface. The provider module (com.finance.persistence) must declare that itprovidesan implementation for that service interface using thewithkeyword. This decouples the modules, as the core module does not need arequiresdirective for the persistence module. - 10
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 details
Correct answer: C
This code snippet is vulnerable to Insecure Direct Object Reference (IDOR). It directly uses the user-provided
userIdto 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 theuserIdin the URL to access another user's information. The other options show proper input validation or correct authorization checks.
