Exam Information
Free practice questions with explanations
Oracle 1Z0-819 Practice Questions
Answer a question to see the correct answer and the explanation, or click Show answer. Newest questions first.
- Questions
- 19
- Answered
- 0
- Correct
- 0
- Score
- -
-
1 Question 1 Single choice Java Object-Oriented Approach
A payments team maintains a value class Money with a mutable List field holding currency conversion notes. The class is shared across threads and must be immutable. A junior developer proposes simply declaring the class final and making the fields private final. During review, the lead notes that callers can still alter the list through the getter. Which change makes the class immutable while keeping the constructor-supplied notes intact and avoiding shared mutable state?
Correct Answer: DExplanationImmutability requires both defensive copying on the way in and an unmodifiable view on the way out. List.copyOf in Java 11 produces an unmodifiable snapshot, so storing that copy prevents later mutation through the constructor argument, and returning it directly from the getter is safe because it cannot be modified. Returning a fresh ArrayList from the getter keeps the internal state safe only on output, but the stored reference still aliases the caller's list, so later caller edits leak in. Making the field static changes sharing semantics across all instances rather than fixing mutability. Synchronizing the getter does nothing to stop callers from mutating the returned list.
-
2 Question 2 Multiple choice Concurrency
A reporting service must fetch quarterly totals from four independent remote endpoints in parallel, waiting at most 2 seconds for each result, and then combine them. The team uses Java SE 11 without external libraries. Which two approaches meet these requirements? (Choose two.)
Correct Answer: A, EExplanationCallable tasks submitted to an ExecutorService return Futures whose get(timeout, unit) overload enforces the per-endpoint 2-second limit, and this is standard Java SE 11 API. CompletableFuture.supplyAsync runs the calls concurrently, allOf waits for all of them, and join gives the combined result, also available in Java 11. Writing to an unsynchronized ArrayList from several threads is a data race. Polling with Thread.sleep wastes resources and is not a timeout mechanism. A single-threaded executor serializes the calls, and get without a timeout cannot enforce the limit.
-
3 Question 3 Dropdown Controlling Program Flow
A log-processing utility classifies incoming HTTP status codes into categories and must handle every class without fall-through bugs. The engineer is completing the switch statement on an int variable named code, where the classification for 2xx responses must stop at the correct point. Select the correct value for each blank.
Choose the correct value for each blank.
switch (code) { case 200: case 201: System.out.println("success"); case 404: System.out.println("not found"); default: System.out.println("other"); }Correct Answer:switch (code) { case 200: case 201: System.out.println("success"); break; case 404: System.out.println("not found"); break; default: System.out.println("other"); }
ExplanationA switch statement falls through from one case label into the next until a break transfers control out of it, so the success branch needs break to avoid running the not-found output. The second blank also needs break so the not-found branch does not fall into default. Continue only applies within loops and is a compile error in a plain switch outside one. Return would exit the whole method, which the scenario does not ask for. Yield is a switch-expression construct in Java 13 and later and is not valid in a Java SE 11 switch statement. Pass and next are not Java keywords.
-
4 Question 4 Drag and drop Exception Handling
A data import service in a Java SE 11 application opens a file, a database connection, and a network stream, and must guarantee that every resource is closed even when an exception occurs, while keeping suppressed exceptions visible to the operator. Match each requirement to the construct that satisfies it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
Handle two unrelated checked exception types with one identical recovery blockGuarantee automatic closing of each resource in reverse order of declarationKeep close-time failures attached to the primary exception for diagnosticsThrowable.addSuppressed mechanismthrows clause on the main method onlytry-with-resources statementmulti-catch clausefinally block that calls close explicitlyCorrect Answer:- Guarantee automatic closing of each resource in reverse order of declaration → try-with-resources statement
- Keep close-time failures attached to the primary exception for diagnostics → Throwable.addSuppressed mechanism
- Handle two unrelated checked exception types with one identical recovery block → multi-catch clause
ExplanationTry-with-resources closes declared resources automatically, in reverse order, even when the body throws, and it is the construct meant for this. When close throws after a primary exception, the JVM attaches the close failure as a suppressed exception via addSuppressed, which the operator can inspect. Multi-catch lets one handler cover unrelated exception types. A manual finally block can close resources, but it does not provide the automatic suppression behaviour and is more error-prone. A throws clause only propagates exceptions and does not close anything.
-
5 Question 5 Single choice Java I/O API
A nightly job must stream a 6 GB CSV file from a shared NFS mount, count lines matching a pattern, and never load the file fully into memory. The team targets Java SE 11 and wants the most idiomatic option that also closes the file handle on every path. Which implementation is the BEST choice?
Correct Answer: CExplanationFiles.lines returns a lazily populated Stream backed by an open file, so memory use stays bounded while filter and count run. The Stream holds an OS resource, so wrapping it in try-with-resources guarantees closure. Files.readAllLines materializes every line in memory, violating the constraint. A Scanner that is never closed leaks the file handle. Reading the whole file into one byte array requires about 6 GB of heap and contradicts the streaming requirement.
-
6 Question 6 Order list Java Platform Module System
A team is migrating an order-processing library into a modular application that must run on the module path with Java SE 11. The library exposes an OrderService interface and must not expose its implementation package to other modules. The team also wants the implementation discovered through the ServiceLoader mechanism by the consuming application. Arrange the steps in the correct order.
Drag the steps into the correct order, or use the arrows.
- In the consuming module, declare a uses clause for the service interface in its module-info
- Keep the implementation package unexported so consumers cannot reference the concrete class directly
- Compile both modules with the module path so the consumer resolves the library module at build time
- Create module-info.java in the library declaring the package that contains the interface as exported
- Declare a provides clause in the library's module-info naming the interface and the implementation class
Correct Answer:- Create module-info.java in the library declaring the package that contains the interface as exported
- Declare a provides clause in the library's module-info naming the interface and the implementation class
- Keep the implementation package unexported so consumers cannot reference the concrete class directly
- In the consuming module, declare a uses clause for the service interface in its module-info
- Compile both modules with the module path so the consumer resolves the library module at build time
ExplanationThe library must first describe itself with a module-info file that exports only the API package, keeping the implementation hidden. The provides clause then registers the implementation, which requires the implementing class to be reachable from the module. The consumer declares uses for the interface so it can call ServiceLoader. Compilation against the module path is the final step, after both descriptors exist, so the resolver can verify the wiring. Placing the compile step earlier would fail because the descriptors it checks would not yet exist.
-
7 Question 7 Single choice Localization
A booking platform displays prices and dates for travellers in Germany, Japan, and Brazil. The product owner requires that numbers and dates follow each user's locale conventions, that message text comes from translatable resource files, and that the application does not hardcode any locale-specific format. The team uses Java SE 11. Which design best satisfies these requirements?
Correct Answer: BExplanationNumberFormat and DateTimeFormatter with ofLocalizedDate consult the locale data to pick grouping separators, currency placement, and date order, which avoids hardcoded patterns. ResourceBundle.getBundle selects a bundle matching the user's Locale and falls back to the base bundle, meeting the translation requirement. Hardcoded format strings ignore the per-user conventions the owner asked for. Formatted strings from the database fix one locale for everyone. A single fixed date pattern and a single properties file both violate the locale-aware requirement.
-
8 Question 8 Drag and drop Annotations
A team builds a custom validation framework in Java SE 11 where field constraints are declared with annotations and read at runtime by a processor using reflection. The annotations must be available when the program runs, must apply only to fields, and must be repeatable where a field carries several constraints. Match each requirement to the annotation meta-information that provides it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
Allow the same constraint annotation to appear more than once on one fieldRetain the annotation in the compiled class so reflection can read it at runtimeRestrict the annotation so it can only be placed on field declarations@Repeatable with a containing annotation type@Inherited on the annotation declaration@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)@Documented on the annotation declarationCorrect Answer:- Retain the annotation in the compiled class so reflection can read it at runtime → @Retention(RetentionPolicy.RUNTIME)
- Restrict the annotation so it can only be placed on field declarations → @Target(ElementType.FIELD)
- Allow the same constraint annotation to appear more than once on one field → @Repeatable with a containing annotation type
ExplanationRuntime reflection only sees annotations whose retention policy is RUNTIME, so that setting is required for the processor. The Target meta-annotation with ElementType.FIELD limits where the annotation may be applied. Repeatable needs a containing annotation type so multiple instances on one element are legal. Inherited only affects class-level annotations inherited by subclasses and does not enable repetition or retention. Documented only affects Javadoc output and has no runtime effect.
-
9 Question 9 Single choice Database Applications with JDBC
A order-management service runs an UPDATE that decrements stock and inserts an order row, and both must commit together or not at all. The service uses JDBC against a database with auto-commit enabled by default, and a failure while inserting the order must not leave the stock decremented. Which sequence of JDBC operations correctly enforces this?
Correct Answer: DExplanationWith auto-commit on, each statement commits immediately, so a failed insert cannot undo the stock change. Disabling auto-commit with setAutoCommit(false) groups the statements into one transaction, commit makes both durable, and rollback in the failure path reverts the decrement. Calling commit with auto-commit still enabled is misleading because the first statement has already committed. Setting auto-commit true or closing the connection does not create a transaction boundary. Using separate connections means two independent transactions, so one can succeed while the other fails.
-
10 Question 10 Single choice Secure Coding in Java SE Application
A web service builds SQL queries from request parameters to filter invoices by customer name. A security review flagged possible SQL injection and asked for a fix that also keeps the existing query plan reusable for performance. The service runs on Java SE 11 with a JDBC driver. Which change is the BEST remediation?
Correct Answer: BExplanationA PreparedStatement sends the SQL structure separately from the bound value, so the driver treats the customer name strictly as data, eliminating injection and allowing the database to reuse the compiled plan. Manual quote escaping is error-prone and misses other injection vectors and dialect differences. Regex validation reduces input but still concatenates into SQL, and a stored procedure built by concatenation has the same flaw. Only parameter binding removes the root cause while preserving plan reuse.
-
11 Question 11 Dropdown Annotations
A build tool must verify at compile time that a custom annotation is applied only where intended. The developer is completing a method signature in an annotation processor test fixture that declares an annotation with a Retention policy and a Target. Select the correct value for each blank so the annotation is retained at runtime and applies only to methods.
Choose the correct value for each blank.
@(RetentionPolicy.) @Target(ElementType.METHOD) public @interface Audited { }Correct Answer:@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Audited { }
ExplanationThe Retention meta-annotation controls how long an annotation persists, and RetentionPolicy.RUNTIME keeps it available to reflection during execution. Documented only affects Javadoc generation and Inherited only applies to class annotations inherited by subclasses. RetentionPolicy.SOURCE discards the annotation before compilation finishes, and CLASS keeps it in class files but not visible at runtime. IMMUTABLE is not a RetentionPolicy constant in Java SE 11.
-
12 Question 12 Single choice Working with Streams and Lambda expressions
An analytics job groups a stream of Sale objects by region and must produce a Map from region to the total revenue as a BigDecimal, using a parallel stream over several million records. The developer also wants the reduction to be correct under parallel execution. Which collector configuration meets this requirement?
Correct Answer: AExplanationCollectors.groupingByConcurrent is designed for parallel streams and produces a ConcurrentMap, and the reducing collector with an identity, mapper, and BigDecimal::add is associative and side-effect free, so parallel combination is correct. Mutating a shared array from parallel workers creates a data race. Mutating a static HashMap in a merge function is also unsafe under parallel execution. partitioningBy splits only into true and false groups rather than by region, and summingInt cannot sum BigDecimal values.
-
13 Question 13 Multiple choice Working with Arrays and Collections
A developer maintains a utility that sorts a list of Employee objects first by department name ascending, then by salary descending, and must be able to reuse the ordering in several places without repeating logic. The Employee class is fixed and cannot be modified. Which two approaches correctly implement this ordering? (Choose two.)
Correct Answer: B, CExplanationComparator.comparing with thenComparing and a reverseOrder key comparator gives the mixed ascending and descending ordering directly, and storing it as a named static constant makes it reusable without repetition. Making Employee implement Comparable is impossible because the class cannot be modified. Calling reversed after thenComparingDouble reverses the department order too, so departments would sort descending. A lambda comparing salary in ascending order ignores the required descending salary order.
-
14 Question 14 Single choice Working with Java data types
A financial calculation service computes a fee as int quantity times int unitPriceCents, then divides by a long divisor and stores the result in an int, and the team has seen incorrect totals for large orders. The code must keep exact integer precision without introducing floating-point error. Which change is the BEST fix, given that the team must stay on primitives?
Correct Answer: AExplanationTwo int operands multiply in 32-bit arithmetic and can overflow before the result ever reaches the long divisor, so casting the operands to long before multiplying keeps the product in 64-bit range and preserves integer precision. Casting to double introduces floating-point rounding, which the scenario forbids. Shrinking the types to short makes overflow worse. Wrapper objects still perform the same int arithmetic after unboxing, so they do not fix the overflow.
-
15 Question 15 Order list Concurrency
A batch service uses a shared ConcurrentHashMap cache and a ReentrantLock to guard a multi-step update that rebuilds one cache entry atomically. Worker threads must never observe a half-updated entry, and the lock must be released even if the update throws. Arrange the steps in the correct order inside each worker.
Drag the steps into the correct order, or use the arrows.
- Return the computed result to the caller after the unlock
- Call lock on the shared ReentrantLock before reading the cache entry
- Read the current entry and compute the replacement value
- Call unlock inside a finally block that always executes
- Write the new value into the cache entry
Correct Answer:- Call lock on the shared ReentrantLock before reading the cache entry
- Read the current entry and compute the replacement value
- Write the new value into the cache entry
- Call unlock inside a finally block that always executes
- Return the computed result to the caller after the unlock
ExplanationThe lock must be acquired before the entry is read, so no other worker can observe or change it mid-update. The read and computation happen under protection, followed by the write that completes the change. Unlock belongs in a finally block so it runs even on exceptions, and returning only after release keeps the critical section as short as the update. Unlocking before the write would expose a half-updated state, and returning before unlocking would hold the lock longer than needed and risk leaks.
-
16 Question 16 Single choice Java Object-Oriented Approach
A library defines an abstract class Shape with a constructor that calls an overridable method describe(). A subclass Circle overrides describe() and initializes its own field radius in its field declaration with a non-default value of 5. A test creates new Circle() and expects describe() to print the radius. The team uses Java SE 11 and wants the output to be reliable. Which change ensures the subclass state is correct when describe() runs?
Correct Answer: DExplanationThe superclass constructor runs before subclass field initializers, so during Shape's constructor the Circle radius is still the default 0 and describe() prints the wrong value. Moving the call to an explicit method invoked after full construction ensures radius is already set. Marking describe() final prevents overriding but still runs before Circle's fields are initialized, so the output stays wrong. Making radius static changes its sharing semantics and still does not guarantee subclass state is ready in the constructor chain. An instance initializer in Circle still runs after the superclass constructor, so it cannot precede it.
-
17 Question 17 Drag and drop Java I/O API
An application must persist a configuration object to disk, read it back later, and manage file system tasks around it, using only Java SE 11 APIs. The team wants the proper API for each need. Match each requirement to the API that fulfils it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
Write a Serializable configuration object to a binary file for later restorationCreate a directory tree and check whether a path exists and is a regular fileRead a text file line by line with explicit charset decodingjava.nio.file.Files utility methodsObjectOutputStream wrapping a FileOutputStreamPrintStream used to list directory entries recursivelyBufferedReader over an InputStreamReader with a CharsetObjectInputStream used to write text configuration linesCorrect Answer:- Write a Serializable configuration object to a binary file for later restoration → ObjectOutputStream wrapping a FileOutputStream
- Create a directory tree and check whether a path exists and is a regular file → java.nio.file.Files utility methods
- Read a text file line by line with explicit charset decoding → BufferedReader over an InputStreamReader with a Charset
ExplanationObjectOutputStream serializes Serializable objects to a binary stream, and the matching ObjectInputStream restores them. The java.nio.file Files class provides createDirectories, exists, and isRegularFile for file system operations. BufferedReader over InputStreamReader with an explicit Charset decodes text with a chosen encoding. ObjectInputStream is for reading serialized objects rather than writing text, and PrintStream writes output but does not list directories recursively.
-
18 Question 18 Single choice Java Platform Module System
A team is modularizing a legacy JAR named legacy-utils.jar that has no module-info.class and must be used from a modular application on Java SE 11. The application needs to require the library by name, without editing the JAR. Which statement about how the JAR is treated on the module path is correct?
Correct Answer: CExplanationA JAR without a module descriptor placed on the module path becomes an automatic module whose name is derived from the JAR file name, and automatic modules export all their packages and read every other module. This lets the application require it by that name without modifying the JAR. Unnamed modules are JARs on the classpath and cannot be required by a named module. Repackaging is not necessary for automatic modules. Classpath placement does not let named modules read it through a requires transitive directive.
-
19 Question 19 Single choice Exception Handling
A payment gateway client throws a custom checked exception PaymentDeclinedException to signal a business decision, distinct from transient network failures. Callers must be forced to handle it, and the exception must carry the decline reason code for logging. The team uses Java SE 11. Which class declaration BEST satisfies these requirements?
Correct Answer: DExplanationExtending Exception makes the class a checked exception, so the compiler forces callers either to catch it or declare it, which matches the requirement that callers handle declines. A reason-code field and a message-passing constructor give the logging detail the team needs. Extending RuntimeException makes it unchecked, so callers would not be forced to handle it. Extending Error is meant for unrecoverable JVM conditions and should not be used for application exceptions. Extending IOException conflates business declines with transient I/O failures, which the scenario explicitly separates.
These are 19 of the 296 questions in the full 1Z0-819 pack.
Get All 296 QuestionsGet all 296 questions & answers
Full access options for Oracle 1Z0-819
Self-study
PDF Version
- 296 actual exam questions
- Compatible with all devices
- Printable PDF format
- No download limits
- 90 days free updates
- 24/7 customer support
Best value
Bundle Pack
- Discounted PDF + online access
- 296 actual exam questions
- Both PDF and online practice test
- Free 90 days updates
- No download or practice limits
- 24/7 customer support
Exam simulation
Online Practice Test
- 296 actual exam questions
- Actual exam environment
- 90 days free updates
- Browser-based software
- 24/7 customer support
100% Money Back Guarantee
Your success comes first
At DumpsProvider, we give you a 100% money back guarantee on all of our exam dumps. For us, your success is the #1 priority and we are more than confident that our exam material will help you pass the 1Z0-819 Exam (Java SE 11 Developer) on your very first attempt.
In a rare case, if you fail your exam, we will refund your amount without asking a single question.