Oracle · Free Practice Questions · Last reviewed May 2026
48real exam-style questions organised by domain, each with the correct answer highlighted and a plain-English explanation of why it's right — and why the others are wrong.
12% of exam · 6 sample questions below
A company uses CI/CD to build and package a Java 17 application. They want to produce a single executable JAR that includes all dependencies. Which tool should be used to achieve this?
Maven JAR Plugin
Maven Shade Plugin
The Maven Shade Plugin repackages compiled classes and all transitive dependencies into one uber-JAR, rewriting manifests so java -jar executes it standalone. This satisfies the single executable JAR constraint, unlike the Assembly Plugin, which leaves dependency JARs external unless extra configuration is added.
Java jar command
jlink tool
A developer has a module named 'com.example.app' that exports a package 'com.example.api'. Another module 'com.example.client' requires 'com.example.app'. Which directive must be in the module-info.java of 'com.example.client'?
opens com.example.app;
uses com.example.api;
exports com.example.api;
requires com.example.app;
The client module must declare a readability dependency on the module exporting the API package. The 'requires' directive in module-info.java grants that module access to com.example.app's exported packages, satisfying the compile-time and runtime access requirement.
A development team wants to ensure that a Java 17 application runs with a specific set of modules. They want to minimize the footprint by including only necessary modules. Which tool should they use?
javac
jlink
jlink assembles a custom runtime image containing only the modules the application requires, producing a minimal footprint. Unlike the full JDK, it excludes unnecessary modules, directly satisfying the size-reduction constraint for the Java 17 application.
jmod
jar
Which TWO statements are true about Java modules in Java 17? (Choose two.)
A module can export a package only to specific modules using 'exports ... to ...'
Qualified exports limit access to specified modules.
The module-info.java file must be compiled with javac and placed in the root of the JAR.
module-info.class must be at the root of the modular JAR.
All packages in a module are automatically exported.
The jdeps tool can be used to create a module graph.
The jlink tool creates a JAR file containing the module.
Which THREE are valid ways to package a Java 17 application for distribution? (Choose three.)
JMOD file
JMOD is a packaging format for modules.
ZIP file containing compiled classes
Native installer (e.g., MSI, DMG)
jpackage can create native installers.
Shell script that compiles and runs the application
JAR file with a manifest
Standard JAR packaging is valid.
A developer runs 'java --list-modules' and sees the output above. Which command can be used to create a custom runtime image containing only the 'java.base' module?
jar --create --file myimage --module java.base
jimage --add-modules java.base --output myimage
jlink --modules java.base --output myimage
jlink --add-modules java.base --output myimage
`jlink` builds a custom runtime image from the named modules, and `--add-modules java.base` restricts the image to that single module, satisfying the stem's requirement to include only `java.base`. The `--output myimage` flag then writes the generated image to the specified directory, producing a minimal runtime.
Want more Java Platform Overview and Packaging practice?
Practice this domain13% of exam · 6 sample questions below
Which TWO statements are true about the sealed class feature in Java 17?
A sealed class restricts which other classes or interfaces may extend or implement it.
Sealed classes use the `permits` clause to declare an explicit, closed set of subtypes, so the compiler enforces exactly which classes or interfaces may extend or implement them. This directly satisfies the stem's Java 17 constraint, restricting inheritance to named permitted subclasses that must be final, sealed, or non-sealed.
A sealed interface cannot use the permits clause.
A subclass of a sealed class must be declared as final, sealed, or non-sealed.
Subclasses of a sealed class must declare one of three modifiers, ensuring the permitted hierarchy stays closed. Marking a subclass final ends further extension, sealed continues restriction, and non-sealed reopens it. This satisfies Java 17's requirement that every direct subclass explicitly state its inheritance intent.
The permits clause must list all direct subclasses of a sealed class.
A sealed class must be declared as abstract.
Arrange the steps to override equals() and hashCode() correctly in Java.
Override equals() with @Override, check identity (==), check null/class, cast, compare fields, override hashCode() with @Override, use Objects.hash() with same fields
This order ensures the equals() and hashCode() contract: reflexive, symmetric, transitive, consistent; and that equal objects have equal hash codes.
Override hashCode() with @Override and Objects.hash(), then override equals() with @Override, check identity, cast, compare fields (skip type/null check)
Override equals() with @Override, check identity, cast directly compare fields, override hashCode() with @Override using random values
Override equals() with @Override, check identity, check type, override hashCode() with @Override and Objects.hash(), then cast and compare fields
Given the following code snippet: `List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.remove(1); System.out.println(list);` What is the output?
[10, 20]
[]
[20]
[10]
`List.remove(int)` removes the element at index 1, which is 20, leaving [10]. The overload taking an `Object` argument would remove the value 10, but the primitive `int` literal selects the index-based method, satisfying the stem's autoboxing-versus-indexing constraint.
Which design pattern is best suited for creating a family of related objects without specifying their concrete classes?
Builder
Singleton
Abstract Factory
Abstract Factory defines an interface for creating families of related or dependent objects, letting client code work through abstract product interfaces rather than concrete classes. This directly satisfies the stem's constraint: producing related object families while hiding concrete implementations, unlike Factory Method, which handles one product type.
Factory Method
A class `Account` has a method `public void deposit(double amount)`. Which approach correctly demonstrates method overloading?
Adding a method `public void deposit(int amount)`
Adding `public void deposit(int amount)` overloads `deposit` because the parameter list differs in type, satisfying the overloading requirement within the same class. The compiler distinguishes the two methods by their signatures at compile time, so calls with an `int` argument bind to the new method and `double` calls bind to the original.
Adding a method `public void deposit(double amount)` with different implementation
Adding a method `public int deposit(double amount)`
Adding a method `protected void deposit(double amount)`
A developer needs to ensure that a class `Shape` cannot be instantiated but can be extended. Which modifier should be used?
private
final
abstract
`abstract` prevents direct instantiation while permitting subclassing, satisfying both constraints in the stem. The compiler rejects `new Shape()`, yet concrete subclasses can extend it and implement any abstract members. Unlike `final`, which blocks extension entirely, or `static`, which is irrelevant to top-level classes, `abstract` is the precise axis of difference required here.
sealed
Want more Utilizing Java Object-Oriented Approach practice?
Practice this domain13% of exam · 6 sample questions below
A developer writes code to iterate over a list of strings and print each element. The code uses an enhanced for loop. Which statement is true about the enhanced for loop?
It can be used with arrays and any object that implements Iterable.
The enhanced for loop relies on the Iterable interface for collections and has special compiler handling for arrays, so it works with both; it removes the need for explicit iterators or index variables when traversing elements sequentially.
It can only be used with arrays.
It requires an explicit counter variable.
It allows removing elements from the collection during iteration without ConcurrentModificationException.
Given the code snippet:
int x = 10;
if (x > 5) {System.out.print("A");
} else if (x > 7) {System.out.print("B");
} else {System.out.print("C");
}
What is the output?
C
ABC
A
Since x is 10, the first condition x > 5 evaluates true, so 'A' prints and the else-if and else branches are skipped entirely. Java's if-else-if chain stops at the first true condition, making 'A' the sole output.
B
A method contains a try-with-resources statement that uses two resources: a FileInputStream and a BufferedInputStream. The FileInputStream constructor throws a FileNotFoundException. Which statement about resource closing is true?
The BufferedInputStream is closed if it was successfully created, but the FileInputStream is not.
Both resources are closed even if the FileInputStream constructor throws an exception.
No resources are closed because the FileInputStream constructor failed before any resource was opened.
Resource acquisition happens in declaration order. The FileInputStream constructor throws before that resource is created, so the try block never begins and neither stream is registered for closing; no close() is attempted on either resource.
The programmer must explicitly close the resources in a finally block.
Which TWO statements are true about the switch statement in Java?
Case values can be variables that are not final.
It can be used with String objects.
String is allowed in switch since Java 7.
It requires a default case.
It can be used as an expression that yields a value.
Switch expressions were introduced in Java 14.
Each case must have a unique code block.
Which THREE statements are true about loops in Java?
The break statement can be used to exit a loop prematurely.
Break exits the loop.
A while loop always executes at least once.
The continue statement skips the rest of the current iteration.
Continue jumps to the next iteration.
A do-while loop may execute zero times if the condition is false.
A for loop can have multiple loop variables.
Multiple variables can be declared and updated.
Which loop construct guarantees that the body executes at least once?
for loop
enhanced for loop
while loop
do-while loop
A do-while loop evaluates its condition after executing the body, so the body always runs at least once even if the condition is initially false. The while and for loops test before each iteration, allowing zero executions, which fails the guarantee.
Want more Controlling Program Flow practice?
Practice this domain12% of exam · 6 sample questions below
Given: HashSet<String> set = new HashSet<>(); set.add("A"); set.add("B"); set.add("C"); set.add("A"); System.out.println(set.size()); What is the output?
Compilation fails
3
HashSet enforces uniqueness through the hashCode and equals contract, so the duplicate "A" is rejected on insertion rather than stored twice. The set therefore holds only "A", "B" and "C", satisfying the stem's requirement to report the collection's element count, which prints 3.
4
2
Which interface provides the ability to store key-value pairs and allows null keys?
ConcurrentHashMap
TreeMap
HashMap
HashMap permits one null key and multiple null values, storing entries in a hash table indexed by key hashCode, with collisions resolved by chaining. TreeMap and ConcurrentHashMap both reject null keys, so HashMap uniquely satisfies the stem's requirement to store key-value pairs while allowing a null key.
Hashtable
A method returns a List<Integer>. The caller wants to ensure the list cannot be modified. Which is the best approach?
return Arrays.asList(list.toArray());
return new ArrayList<>(list);
return (List<Integer>) list.clone();
return Collections.unmodifiableList(list);
`Collections.unmodifiableList` returns a read-only view backed by the original list, so any attempt to add, remove or set elements throws `UnsupportedOperationException`. This satisfies the caller's requirement that the returned list cannot be modified, while avoiding the cost of copying the underlying elements.
Which method of Collection interface returns a primitive int?
contains(Object o)
isEmpty()
toArray()
size()
Collection.size() returns a primitive int representing the element count. This differs from methods such as toArray(), which return object arrays, or stream(), which returns a Stream, making size() the direct primitive-returning member of the Collection interface.
A developer writes: List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add(1, "C"); System.out.println(list); What is the output?
[A, C, B]
Inserting at index 1 shifts the existing element "B" rightward, so "C" occupies the second position. ArrayList permits index-based insertion within its size, and the resulting order is "A", "C", "B", which the default toString prints as [A, C, B].
[A, B, C]
[A, B]
[C, A, B]
Given: Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.merge("A", 3, (v1, v2) -> v1 + v2); System.out.println(map.get("A")); What is the result?
1
4
merge finds the existing value 1 for key "A", applies the remapping function to 1 and 3, and stores 4. This satisfies the stem's scenario, since the key already existed, so the function runs rather than the value being replaced.
3
null
Want more Working with Arrays and Collections practice?
Practice this domain13% of exam · 6 sample questions below
Which TWO statements are true about the java.time.Duration class? (Choose two.)
Duration represents a time-based amount of time, such as hours, minutes, seconds.
Duration is based on seconds/nanoseconds.
Duration.ofDays(1) returns a Duration that is daylight-saving-safe.
Duration.between(LocalDate.now(), LocalDate.now().plusDays(1)) returns a Duration of 1 day.
Duration can represent a period of months.
Duration can be negative.
Duration can be negative.
Which THREE statements are true about the Boolean class? (Choose three.)
The parseBoolean(String) method returns false if the string is null or not equal to "true" (case-insensitive).
parseBoolean returns false for non-matching strings.
The Boolean constructor is the preferred way to create a Boolean object.
Boolean.TRUE and Boolean.FALSE are static constants.
Yes, they are predefined static final instances.
The valueOf(String) method returns Boolean.TRUE or Boolean.FALSE without creating a new instance.
valueOf returns cached constants.
Boolean has three possible values: true, false, and null.
A company's Java application processes time-sensitive data from IoT sensors. The system must handle timestamps across multiple time zones. The application runs on a server set to UTC. Developers have been using java.util.Date and SimpleDateFormat for date parsing. Recently, there have been intermittent failures where timestamps from sensors in the America/New_York time zone are parsed incorrectly around daylight saving time transitions. Specifically, during the spring forward (March 12, 2023, at 2:00 AM EST to 3:00 AM EDT), timestamps like "2023-03-12 02:30:00" are being interpreted as times that do not exist, causing DateTimeParseException. The team decides to migrate to the java.time API. They need to parse sensor timestamps that include a time zone offset (e.g., "2023-03-12 02:30:00 -05:00") into an OffsetDateTime. Which course of action correctly parses the timestamp and handles the DST issue?
Use LocalDateTime.parse(timestamp, formatter) and then apply a ZoneOffset.
Use ZonedDateTime.parse(timestamp, formatter) with a formatter that includes time zone ID, then convert to OffsetDateTime.
Use DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX") and OffsetDateTime.parse(timestamp, formatter).
OffsetDateTime.parse with pattern XXX reads the explicit -05:00 offset, so 02:30:00 resolves to a real instant rather than an invalid local time. This avoids the DST gap that broke SimpleDateFormat, satisfying the requirement to parse offset-bearing sensor timestamps correctly.
Keep using SimpleDateFormat but set the time zone of the parser to America/New_York.
Which TWO of the following are valid ways to create a LocalDate object in Java 17?
LocalDate.from(Instant.now())
LocalDate.of(2023, Month.JANUARY, 15)
LocalDate.of(int year, Month month, int dayOfMonth) is a valid overload, accepting the Month enum constant JANUARY for the month argument. The year, month and day values are within valid ranges, so the call compiles and returns the corresponding date.
LocalDate.of(2023, 13, 1)
LocalDate.parse("2023-01-15")
LocalDate.parse accepts an ISO-8601 formatted string, and "2023-01-15" matches the yyyy-MM-dd pattern exactly. This static factory method parses the text into a LocalDate without requiring a DateTimeFormatter, satisfying the question's requirement for a valid creation approach in Java 17.
LocalDate.ofEpochDay("19375")
What is the output?
EL
The enhanced for loop iterates the list in insertion order, printing each element's string form. Because `List.of("E", "L")` preserves encounter order and `System.out.print` emits without separators, the two characters concatenate to `EL`. This satisfies the stem's requirement for the exact console output.
HEL
ELLO
HELL
Arrange the steps to create a custom exception class in Java in the correct order.
1. Define a class that extends Exception or RuntimeException. 2. Add constructors (default, with message, with cause). 3. Optionally override methods like getMessage() or toString().
This is the correct order because the class must be defined to extend the appropriate exception class first, then constructors are added to allow custom error messages and cause propagation, and finally any method overrides are optional.
1. Add constructors (default, with message, with cause). 2. Define a class that extends Exception or RuntimeException. 3. Optionally override methods.
1. Define a class (without extending Exception or RuntimeException). 2. Add constructors that call super(message). 3. Optionally override methods.
1. Override methods like getMessage() or toString(). 2. Define a class extending Exception or RuntimeException. 3. Add constructors.
Want more Handling Date, Time, Text, Numeric and Boolean Values practice?
Practice this domain13% of exam · 6 sample questions below
A developer is writing a method that reads a file and processes its content. The method must ensure that if an IOException occurs during reading, the method throws a custom ApplicationException that wraps the original IOException, and that any resources opened are closed properly. Which approach correctly implements this requirement?
try { ... } catch (IOException e) { System.err.println(e); } finally { reader.close(); }
catch (Exception e) { throw new ApplicationException(e); } finally { reader.close(); }
try (BufferedReader reader = Files.newBufferedReader(path)) { ... } catch (IOException e) { throw new ApplicationException(e); }
The try-with-resources statement guarantees the BufferedReader closes automatically, satisfying the resource-cleanup constraint even when an exception propagates. Catching IOException and throwing ApplicationException(e) preserves the original exception as the cause, wrapping it exactly as the stem requires. This combination handles both the closing and wrapping requirements in one construct.
try { ... reader.close(); } catch (IOException e) { throw new ApplicationException(e); }
A team is designing a logging framework. The framework's core method log(String message) may throw a checked LogException if the logging system fails. The team wants to allow callers to choose whether to handle the exception or declare it as thrown. Which declaration of the log method satisfies this requirement?
public void log(String message) throws LogException { ... }
Declaring `throws LogException` on the method signature satisfies the requirement by propagating the checked exception to callers, who may then either catch it in a try-catch block or declare it in their own throws clause. This preserves caller flexibility, unlike catching internally, which would remove the choice entirely.
public void log(String message) { ... }
public void log(String message) throws Error { ... }
public void log(String message) throws RuntimeException { ... }
Which TWO statements about the try-with-resources statement are correct? (Choose two.)
The resource class must implement AutoCloseable.
Correct: only AutoCloseable resources are allowed.
The resource variable must be declared as final.
Resources are closed in the reverse order of their declaration.
Correct: resources are closed in reverse order.
A try-with-resources statement cannot have a finally block.
Resources are closed before the try block executes.
You are responsible for a Java 17 application that processes user uploads. The application uses a custom AutoCloseable resource, UploadSession, which must always be closed after use to free server resources. A junior developer wrote the following code:
``` UploadSession session = new UploadSession(); try { session.upload(data); // more processing
} catch (UploadException e) {log.error("Upload failed", e);
} finally {session.close();
}
```
During a code review, you notice that the close() method of UploadSession throws a checked CloseException. The current code does not handle this exception. Which course of action should you recommend to ensure the application is robust and follows best practices?
Add a try-catch block inside the finally block to handle CloseException from session.close().
Declare the method with throws CloseException, and remove the finally block.
Keep the code as-is. The CloseException is not critical; it can be ignored.
Rewrite the code to use try-with-resources: try (UploadSession session = new UploadSession()) { ... } catch (UploadException e) { ... }
Try-with-resources handles closure automatically and properly suppresses exceptions.
Which TWO of the following are checked exceptions in Java?
SQLException
SQLException extends Exception directly and is declared checked by the JDBC API, so callers must catch or declare it. It is not a subclass of RuntimeException, which is the axis separating checked from unchecked exceptions in Java.
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
IOException
IOException extends Exception, making it a checked exception that the compiler forces callers to handle or declare via throws. This directly satisfies the stem's requirement, since java.io operations such as file and stream access must be guarded at compile time, unlike RuntimeException subclasses that remain unchecked.
You are developing a microservice that processes financial transactions. The service reads transaction data from a message queue, validates it, and writes results to a database. The code uses a try-with-resources statement to manage database connections. During testing, you notice that when a transaction fails validation, the service throws an IllegalStateException before closing the database connection, causing a resource leak. You need to ensure that the database connection is always closed properly, even if an exception is thrown during validation. The current code structure is:
try (Connection conn = DriverManager.getConnection(url, user, pass)) { // read from queue // validate transaction // if invalid, throw new IllegalStateException("Invalid transaction"); // write to database
}
Which course of action would you recommend?
Move the connection creation outside the try-with-resources to manually manage it.
No change is needed; the try-with-resources ensures the connection is closed.
Try-with-resources closes any resource declared in its header when the block exits, whether normally or via exception. The IllegalStateException thrown during validation still triggers close() on the Connection, so no leak occurs and no code change is required.
Replace the try-with-resources with a try-catch-finally block and close the connection in the finally block.
Add a catch block to catch the IllegalStateException and close the connection.
Want more Handling Exceptions practice?
Practice this domain12% of exam · 6 sample questions below
A developer writes the following code using the Stream API:
List<String> list = List.of("a", "b", "c"); String result = list.stream().reduce("", (s1, s2) -> s1 + s2); System.out.println(result);
What is the output?
abc
The three-argument `reduce` overload takes an identity value, here the empty string, then combines it with each element using the accumulator. Because `"" + "a" + "b" + "c"` concatenates sequentially, the result is `abc`. The identity also guarantees a defined result for an empty stream.
a
Optional[abc]
cba
A developer writes:
List<Integer> list = List.of(1, 2, 3); Optional<Integer> opt = list.stream().reduce((a, b) -> a + b); System.out.println(opt.get());
What is the result?
6
The two-argument `reduce` returns an `Optional`, since an empty stream yields no result. Here the stream holds three elements, so the accumulator sums 1, 2 and 3, producing 6, which `opt.get()` prints. The stem's constraint is the `Optional`-returning overload, not the identity-based variant.
Optional[6]
Optional.empty
NoSuchElementException
Which statement about the Stream API is true?
Parallel streams always improve performance.
Streams are always finite.
Intermediate operations are executed eagerly.
A stream can be consumed only once.
A stream pipeline executes its source and intermediate operations only on a terminal operation, after which the stream is consumed and any further reuse throws IllegalStateException. This satisfies the stem's requirement for a universally true Stream API statement, unlike options describing reusable or collection-like behaviour.
Given:
List<String> words = Arrays.asList("apple", "banana", "cherry"); Map<Integer, List<String>> map = words.stream().collect(Collectors.groupingBy(String::length)); System.out.println(map);
What is the output?
[apple, banana, cherry]
{5=[5], 6=[6, 6]}
{5=[apple], 6=[banana, cherry]}
groupingBy(String::length) classifies each word by its character count, producing keys 5 and 6. "apple" has five characters, while "banana" and "cherry" each have six, so they collect into the same list under key 6, matching this output exactly.
{apple=[5], banana=[6], cherry=[6]}
A developer wants to find the longest word in a list of strings. Which stream operation should be used?
stream().sorted(Comparator.comparingInt(String::length).reversed()).findFirst()
stream().min(Comparator.comparingInt(String::length))
stream().sorted(Comparator.comparingInt(String::length)).findFirst()
stream().max(Comparator.comparingInt(String::length))
`Stream.max(Comparator.comparingInt(String::length))` returns the element with the greatest length, satisfying the requirement to find the longest word. It compares strings by their integer length rather than natural ordering, so lexicographic order never interferes. The result arrives wrapped in an `Optional<String>`, handling empty lists safely.
What does the following code print?
List<Integer> list = List.of(1, 2, 3, 4, 5); list.stream().filter(i -> i % 2 == 0).forEach(System.out::print);
No output
12345
135
24
Filtering the stream with `i % 2 == 0` retains only even integers, so 2 and 4 pass through. `forEach(System.out::print)` then outputs each without separators, producing the concatenated result 24. This satisfies the stem's requirement to print the filtered elements of the immutable list.
Want more Working with Streams and Lambda Expressions practice?
Practice this domain12% of exam · 6 sample questions below
A developer is tasked with reading a large binary file (1 GB) from a network share using the least amount of memory possible. Which approach should be used?
Use a FileInputStream wrapped in a BufferedInputStream with a 8 KB buffer
A FileInputStream wrapped in a BufferedInputStream with an 8 KB buffer reads the 1 GB file in small sequential chunks rather than loading it whole. This satisfies the minimal-memory constraint, because buffering reduces syscall overhead while the resident footprint stays bounded at roughly the buffer size.
Read the entire file into a byte array using Files.readAllBytes()
Use a FileReader wrapped in a BufferedReader to read lines
Use a RandomAccessFile to read the file in segments
An application must read a configuration file that is updated frequently by another process. The developer wants to avoid stale data and minimize I/O operations. Which approach is best?
Use java.nio.file.WatchService to monitor the file for modifications and reload when notified
WatchService registers the file with the OS and delivers change events asynchronously, so the application reloads only when the file actually changes. This satisfies both constraints: no stale data, and I/O is limited to genuine modifications rather than repeated polling reads.
Read the file from disk every time it is accessed using Files.newInputStream()
Periodically check the file's lastModified timestamp using File.lastModified() and reload if changed
Read the file once at startup and cache the content in memory
A developer needs to write text to a file with UTF-8 encoding. Which class should be used?
BufferedWriter
new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)
Wrapping FileOutputStream in OutputStreamWriter with StandardCharsets.UTF_8 converts characters to UTF-8 bytes before writing, satisfying the encoding constraint. FileOutputStream alone writes raw bytes, while FileWriter uses the platform default charset, which may not be UTF-8. This explicit bridge guarantees correct encoding.
FileWriter
PrintWriter with default constructor
A developer is designing a service that processes multiple files concurrently. To avoid resource leaks, which practice is essential?
Ensure each thread has its own copy of the file handle
Use try-with-resources for each AutoCloseable resource
Try-with-resources guarantees each AutoCloseable is closed automatically at block exit, even when exceptions occur during concurrent file processing. This directly prevents the resource leaks the scenario warns about, unlike manual finally blocks that developers can forget or misorder.
Call close() on each stream in a separate try-catch block
Use FileLock to prevent concurrent access
Which statement about java.io and java.nio.file packages is true?
The java.nio.file package provides support for symbolic links and file attributes
The java.nio.file package exposes symbolic link handling through methods such as createSymbolicLink and readSymbolicLink, plus attribute access via Files.readAttributes and PosixFileAttributes. This satisfies the stem's requirement for a true statement, since java.io offers no symbolic link support and only limited attribute querying.
Classes in java.nio.file are thread-safe by default
The java.io package includes the Path interface
The java.nio.file package is deprecated in favor of java.io
A developer needs to copy a large directory tree from one location to another, preserving file attributes. Which method should be used?
Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES)
Implement a FileVisitor using Files.walkFileTree and copy each file with COPY_ATTRIBUTES
Files.walkFileTree with a FileVisitor traverses the entire directory hierarchy recursively, invoking visitFile for each entry, so every file and subdirectory is reached. Passing COPY_ATTRIBUTES to Files.copy preserves the source attributes, satisfying both the large-tree traversal and attribute-preservation constraints in the stem.
Use Files.walk() and then Files.copy() for each entry
Use FileUtils.copyDirectory from Apache Commons IO
Want more Java I/O API and Securing Applications practice?
Practice this domainThe 1Z0-829 exam has 50 questions and must be completed in 90 minutes. The passing score is 680/1000.
Scenario-based questions covering exam objectives with detailed answer explanations.
The exam covers 8 domains: Java Platform Overview and Packaging, Utilizing Java Object-Oriented Approach, Controlling Program Flow, Working with Arrays and Collections, Handling Date, Time, Text, Numeric and Boolean Values, Handling Exceptions, Working with Streams and Lambda Expressions, Java I/O API and Securing Applications. Questions are weighted by domain — higher-weight domains appear more on your actual exam.
No. These are original exam-style practice questions written against the official Oracle 1Z0-829 exam objectives. They are not copied from the real exam. Courseiva focuses on genuine understanding, not memorisation of braindumps.
Courseiva tracks your accuracy per domain and routes you toward weak areas automatically. Free, no account required.