Limited-Time Offer: Enjoy 50% Savings! Coupon code: 50OFF Use it at checkout
Skip to content

Free Oracle Java SE 8 Programmer II 1Z0-809 Exam Questions

Last updated: · 15 practice questions with answers and explanations

Page: 1 / 14 Total 208 questions

Want more questions? Get Premium Access.

Question 1

New Single answer

Topic: Java Class Design

Skill tested: Designs immutable classes with defensive copying and controlled field exposure.

A billing service stores a customer's mailing address when an invoice is created. The Address type is mutable, and the service must ensure later changes by either the caller or the invoice user cannot alter the address captured on the invoice. The address has two mutable components, and the Invoice API should not expose mutable internal state. Which design best meets these requirements while keeping Invoice instances immutable?

Correct Answer: B. Copy the Address in the constructor, keep the field private and final, and return a new copy from the getter.
Explanation:

A final reference does not make the referenced Address immutable. Copying on construction prevents the caller from changing Invoice state through the original object; returning a copy prevents callers from mutating that state through the getter. A setter, as in C, means the Invoice is not immutable. Making the class final does not protect the mutable object returned by a getter, and assigning and returning the original reference in A leaves both mutation paths open.

Question 2

New Single answer

Topic: Advanced Java Class Design

Skill tested: Applies Java 8 interface default-method conflict resolution in an implementing class.

A plug-in framework defines two interfaces, `Readable` and `Auditable`. Each declares a default method `status()` with a different implementation. A concrete class `Report` implements both interfaces and must retain their public API while providing a status that combines the two behaviors. The interfaces cannot be changed, and callers must continue to invoke `status()` on a `Report` reference without choosing an interface type. Which implementation is required to compile and meet the requirement?

Correct Answer: B. Declare `public String status()` in `Report` and provide the combined implementation.
Explanation:

When unrelated interfaces provide conflicting default methods, the implementing class must resolve the conflict by declaring an overriding method. That method can combine behavior as required, and it must be public because interface methods are public. There is no automatic selection between unrelated defaults, so A fails. A concrete class cannot leave the conflict unresolved with an abstract method, and merely referring to one interface's default does not constitute the required class implementation; D also does not combine both behaviors.

Question 3

New Multiple answers

Topic: Generics and Collections

Skill tested: Uses TreeMap comparators to define ordering and ensure key uniqueness correctly.

A logistics application groups delivery records by route code. Route codes are case-insensitive, and the records must be iterated in case-insensitive alphabetical order. The map must treat `north-2` and `NORTH-2` as the same key, preserving only one mapping for that logical route. Which two choices correctly configure a `TreeMap` for this requirement? Select two.

Correct Answer: A. Construct the map with `String.CASE_INSENSITIVE_ORDER` as its comparator.; D. Construct the map with a comparator that returns `a.compareToIgnoreCase(b)`.
Explanation:

A TreeMap uses its comparator both to order keys and to determine whether keys compare as equal; a zero comparison means the keys occupy the same map entry. `String.CASE_INSENSITIVE_ORDER` and a comparator based on `compareToIgnoreCase` provide the required ordering and key equivalence. Lowercasing only during retrieval does not change how the map stores or compares keys. D can be problematic for locale-sensitive case conversion and is not the specified case-insensitive ordering; a HashMap does not provide this ordering or key-equivalence behavior.

Question 4

New Single answer

Topic: Lambda Built-in Functional Interfaces

Skill tested: Selects primitive-specialized functional interfaces to avoid boxing in numeric pipelines.

A telemetry pipeline processes millions of integer sensor readings. For each reading it must determine whether a value is within a permitted range, then accumulate accepted values into a `long`. The implementation should avoid boxing each input as an `Integer` or each predicate result as a `Boolean` when applying the predicate. Which functional interface is the best fit for the range test?

Correct Answer: D. `IntPredicate`
Explanation:

`IntPredicate` accepts a primitive `int` and returns a primitive `boolean`, avoiding boxing at the predicate boundary. It directly represents the required test and can be used with APIs such as `IntStream.filter`. `Predicate` and `Function` use reference types and can incur boxing and unboxing. `UnaryOperator` transforms an Integer into another Integer; it does not model a boolean test.

Question 5

New Multiple answers

Topic: Java Stream API

Skill tested: Builds stream pipelines with flatMap, partitioning, and terminal collection operations.

A reporting service receives a list of departments, each containing a list of employees. It must produce a `Map` containing every employee's name exactly once: the `true` group for employees whose name begins with `A`, and the `false` group for all others. Empty departments contribute no employees. The service should perform this with a stream pipeline and the standard collectors, without building intermediate lists manually. Which two approaches meet these requirements? Select two.

Correct Answer: A. Use `departments.stream().flatMap(d -> d.getEmployees().stream()).map(Employee::getName).collect(Collectors.partitioningBy(n -> n.startsWith("A")))`.; D. Use `departments.stream().flatMap(d -> d.getEmployees().stream()).map(Employee::getName).collect(Collectors.partitioningBy(n -> n.startsWith("A"), Collectors.toList()))`.
Explanation:

Both A and D flatten the nested employee lists, map each employee to one name, and partition those names using the required predicate. `partitioningBy` produces the two Boolean groups, including a group with an empty list when appropriate; D explicitly supplies the list downstream collector, while A uses its default list collector. B partitions departments rather than employees. C uses `groupingBy`, which creates only keys represented in the data and does not guarantee both Boolean keys. E partitions streams rather than individual names.

Question 6

New Single answer

Topic: Exceptions and Assertions

Skill tested: Uses try-with-resources and suppressed exceptions when resource closure fails.

A batch importer opens a `Reader` in a try-with-resources statement and parses a record. Parsing throws `IllegalArgumentException`, then closing the Reader also throws `IOException`. The importer catches the exception propagated from the try-with-resources statement and logs its suppressed exceptions. Which behavior should the error-handling code expect?

Correct Answer: D. The `IllegalArgumentException` is propagated, and the close-time `IOException` is available as a suppressed exception.
Explanation:

When the try body throws an exception and resource closure also fails, try-with-resources propagates the body exception as the primary exception and records the close exception as suppressed. The catch block can retrieve suppressed exceptions through `getSuppressed()`. The close failure does not replace the original failure, so A reverses their roles. Java does not invoke a catch block twice for the two exceptions, and the body exception is not discarded.

Question 7

New Single answer

Topic: Use Java SE 8 Date/Time API

Skill tested: Resolves local date-times in a time zone across daylight-saving gaps.

A booking system accepts appointments as a `LocalDateTime` in a named regional zone. On the spring daylight-saving transition, a customer submits a local time that falls inside the one-hour clock gap, when the local clock jumps forward. The system must convert the appointment to an instant and reject any local time that does not exist rather than silently shifting it. Which approach enforces this policy?

Correct Answer: C. Call `zone.getRules().getValidOffsets(localDateTime)` and reject the input when the returned list is empty; otherwise use the valid offset to create the instant.
Explanation:

A local date-time has no offset or zone information by itself. The zone rules' valid-offset list is empty during a daylight-saving gap, so checking it allows the application to reject nonexistent local times. When an offset is valid, the application can combine it with the local date-time to obtain an instant. `atZone` adjusts a gap time forward rather than enforcing rejection. UTC conversion ignores the named regional zone, and Duration does not establish whether a local time is valid in that zone.

Question 8

New Single answer

Topic: Java I/O Fundamentals

Skill tested: Writes serialized objects safely using ObjectOutputStream resource management.

A desktop application must persist a serializable `SessionSnapshot` to a file and later restore it using Java object serialization. A snapshot includes a collection of serializable records, and failures during writing must not leave the output stream open. The application does not need a human-readable file format. Which implementation is most appropriate?

Correct Answer: A. Open an `ObjectOutputStream` over a `FileOutputStream` in try-with-resources and call `writeObject(snapshot)`.
Explanation:

`ObjectOutputStream` writes an object graph using Java serialization, and `FileOutputStream` supplies the byte-oriented file destination. Try-with-resources closes the stream even if writing fails. A and C write text representations rather than a serialized object graph, and `toString()` is not a persistence format. D uses an input stream for reading; it cannot write the snapshot, and `readObject` does not accept an object argument.

Question 9

New Multiple answers

Topic: Java File I/O (NIO.2)

Skill tested: Uses NIO.2 file-tree streams and file attributes for safe recursive cleanup.

An operations utility must locate regular files beneath a configured directory whose names end in `.tmp`, delete only those files, and leave directories and symbolic links untouched. The utility should handle a large tree without first storing every path in memory, and it must close any traversal resource. Which two approaches satisfy these requirements? Select two.

Correct Answer: B. Use `Files.find(root, Integer.MAX_VALUE, (path, attrs) -> attrs.isRegularFile() && path.getFileName().toString().endsWith(".tmp"))` in try-with-resources, then delete each result.; E. Use `Files.walk(root)` in try-with-resources, filter with `Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)` and the filename suffix, then delete matching paths.
Explanation:

`Files.walk` and `Files.find` provide lazy streams that can traverse a directory tree and should be closed with try-with-resources. A explicitly checks regular-file status without following symbolic links, then filters by suffix. B uses the attributes supplied to `Files.find`, which are gathered without following links by default, and applies the same regular-file and suffix constraints. C removes directories and nonmatching files as well. `Files.list` is not recursive, and E risks deleting directories, links, or names that merely contain the suffix.

Question 10

New Multiple answers

Topic: Java Concurrency

Skill tested: Coordinates worker tasks with CyclicBarrier and identifies barrier synchronization requirements.

A data-processing job splits one input into four independent partitions. Four worker tasks must each finish loading their partition before any task begins a shared merge phase. After the merge, each task continues with its own validation work. The same barrier will be reused for several batches, and the coordinator should not poll worker status. Which two implementation choices satisfy these requirements? Select two.

Correct Answer: C. Create a `CyclicBarrier` with four parties and have each worker call `await()` after loading and before merging.; E. Use a `CyclicBarrier` with four parties at the phase boundary; after all four arrive, the barrier releases them for the merge, and it can be reused for a later batch.
Explanation:

A four-party `CyclicBarrier` blocks each worker at the phase boundary until all four participating tasks arrive, then releases them to proceed. A CyclicBarrier is reusable after its parties pass, making it suitable for repeated batches. A and C describe the same suitable barrier configuration and usage. The latch approach in B uses the wrong direction for coordination: workers should count down and a coordinating thread should await; it also is not resettable. A single-threaded executor cannot provide the required parallel phase, and unrelated locks do not coordinate the workers.

Question 11

New Single answer

Topic: Building Database Applications with JDBC

Skill tested: Executes JDBC queries with proper resource ownership and deterministic closure.

A reporting component obtains a JDBC `Connection` from `DriverManager`, executes a `SELECT`, and processes every row in the returned `ResultSet`. The report may fail while reading a column, and the component must close the JDBC resources reliably without closing a connection supplied by another layer. Which approach is appropriate for this component?

Correct Answer: D. Use nested try-with-resources for the locally created `Statement` and `ResultSet`, and close the locally obtained `Connection` in an outer try-with-resources.
Explanation:

The component owns the Connection it obtained from `DriverManager`, so try-with-resources should close it along with the Statement and ResultSet. Nested resource scopes make the ownership explicit and ensure resources are closed if query execution or row processing fails. Closing a JDBC Connection also closes dependent resources, but each resource should still be managed predictably. B leaks resources, C closes the connection before result processing, and D closes them in the wrong dependency order and risks a close failure preventing later cleanup.

Question 12

New Single answer

Topic: Localization

Skill tested: Loads locale-specific resource bundles using explicit Locale selection and fallback behavior.

A desktop application supports English and French message bundles. A user chooses French, but the installation contains only the default bundle and `Messages_fr.properties`; there is no country-specific French bundle. The application must load the most specific available bundle for the requested language while preserving standard ResourceBundle fallback. Which code is the appropriate choice?

Correct Answer: A. Call `ResourceBundle.getBundle("Messages", Locale.FRANCE)`.
Explanation:

Passing `Locale.FRANCE` requests the French language and France country bundle, then ResourceBundle searches its normal fallback candidates, including the language-only `Messages_fr` bundle and the base bundle. This supports standard locale selection without changing the process-wide default. `Locale.ROOT` requests the root locale rather than French. Loading a Properties file directly bypasses ResourceBundle's locale lookup and fallback. Changing the default locale globally is unnecessary and can affect unrelated application behavior.

Question 13

New Multiple answers

Topic: Java Class Design

Skill tested: Implements singleton initialization safely with Java class-initialization guarantees.

A server library needs a singleton registry that is initialized lazily when first accessed, remains safe when multiple threads access it concurrently, and can hold a non-serializable internal resource. The API must not permit callers to create additional instances through reflection under ordinary conditions. Which two design choices are appropriate? Select two.

Correct Answer: C. Use a private constructor and synchronize the accessor while lazily initializing a private static instance.; E. Use a private constructor and a private static nested holder class containing a static final Registry instance; expose it through a static accessor.
Explanation:

The initialization-on-demand holder idiom initializes the instance when the accessor first references the nested class; Java class initialization is thread-safe. A private constructor discourages ordinary external construction. Synchronized lazy initialization in D is also thread-safe, though it may add synchronization overhead on each access unless optimized with a correct pattern. B has a race and can create multiple instances. C is eager rather than lazy, and an enum cannot extend another class because every enum already extends `java.lang.Enum`.

Question 14

New Single answer

Topic: Advanced Java Class Design

Skill tested: Uses enum constructors and methods to associate behavior with enum constants.

A shipping application supports three service levels. Each level has a fixed number of business days, and the application must calculate an estimated dispatch date by adding that count to a supplied `LocalDate`. The service levels are a closed set, and callers should use the enum constant's behavior rather than a separate conditional mapping. Which design best meets the requirement?

Correct Answer: B. Store the day count in a private final enum field, initialize it through a private enum constructor, and expose a method that adds it to the supplied date.
Explanation:

Enum constants can be associated with constructor-supplied state, and enum constructors are implicitly private; a method can use the immutable day count to calculate the dispatch date. This keeps the supported set closed while placing the behavior with the service-level value. Java does not allow callers to instantiate new enum constants through a public constructor. Mutable static state would make results depend on call order and introduce concurrency risks. An abstract method must be implemented by each constant or the enum type will not compile.

Question 15

New Single answer

Topic: Generics and Collections

Skill tested: Applies wildcard variance to consume and produce values in generic APIs.

A library method copies elements from a source list into a destination list. The method must accept a list of `Integer` values as the source and a list of `Number` values as the destination, while also supporting other subtype/supertype combinations. It does not need to insert values into the source or read from the destination. Which signature expresses this safely using Java generics?

Correct Answer: A. `static void copy(List
Explanation:

The source produces values, so `? extends T` allows a list of a subtype such as `Integer` to be read as T. The destination consumes values, so `? super T` allows insertion into a list of a supertype such as `Number`. This is the producer-extends, consumer-super pattern. A requires both lists to have exactly the same type argument, preventing `List` to `List`. C reverses the variance, and D cannot accept a `List` as a `List` because generic types are invariant.