1z0-809 Oracle Practice Test Questions and Exam Dumps

Question no 1:

Given the following Java code fragment:


Stream<Path> files = Files.walk(Paths.get(System.getProperty("user.home")));

files.forEach(fName -> { // line n1

    try {

        Path aPath = fName.toAbsolutePath(); // line n2

        System.out.println(fName + ":" +

            Files.readAttributes(aPath, Basic.File.Attributes.class).creationTime());

    } catch (IOException ex) {

        ex.printStackTrace();

    }

});


What is the result of this code?

A. All files and directories under the home directory are listed along with their attributes.
B. A compilation error occurs at line n1.
C. The files in the home directory are listed along with their attributes.
D. A compilation error occurs at line n2.

Explanation:

This Java code is intended to list all files and directories starting from the user's home directory and print each file’s path along with its creation time. It uses the Java NIO (New I/O) package, introduced in Java 7, which allows efficient file and directory operations.

Let's analyze the key parts:

Files.walk(Paths.get(System.getProperty("user.home")))

  • This line initiates a stream of Path objects, recursively walking through the directory tree under the user's home directory.

files.forEach(fName -> { ... })

  • This is a lambda expression that processes each file path in the stream. No syntax issues here.

Line n2: Files.readAttributes(aPath, Basic.File.Attributes.class).creationTime();

  • Here's the actual problem. The incorrect class is used: Basic.File.Attributes.class does not exist.

The correct interface to use is:

Files.readAttributes(aPath, BasicFileAttributes.class).creationTime();

The type BasicFileAttributes (not Basic.File.Attributes) is the correct one provided by java.nio.file.attribute.

What happens?

Due to this incorrect reference, the code will fail to compile at line n2. The compiler will not be able to resolve Basic.File.Attributes.class, resulting in a compilation error.

Conclusion:

The correct answer is D. A compilation error occurs at line n2.

To fix the issue, the line should be:

Files.readAttributes(aPath, BasicFileAttributes.class).creationTime();

Once corrected, the code will walk through all files and directories under the home directory and print their creation times.

Question no 2:

Consider the following Java class and code fragment:

class Vehicle {

    int vno;

    String name;


    public Vehicle(int vno, String name) {

        this.vno = vno;

        this.name = name;

    }


    public String toString() {

        return vno + ":" + name;

    }

}

And the following code fragment

Set<Vehicle> vehicles = new TreeSet<>();

vehicles.add(new Vehicle(10123, "Ford"));

vehicles.add(new Vehicle(10124, "BMW"));

System.out.println(vehicles);

What is the result of executing this code?

A. 10123 Ford 10124 BMW
B. 10124 BMW 10123 Ford
C. A compilation error occurs.
D. A ClassCastException is thrown at runtime.

Explanation:

The key to solving this question lies in understanding how the TreeSet works in Java.

1. Understanding TreeSet:

A TreeSet in Java is a sorted set implementation that relies on either:

  • The natural ordering of its elements (i.e., elements must implement the Comparable interface), or

  • A custom comparator passed to the TreeSet constructor.

2. Problem in the Code:

In the given code:

Set<Vehicle> vehicles = new TreeSet<>();

You're trying to store instances of the Vehicle class in a TreeSet. However, the Vehicle class:

  • Does not implement Comparable<Vehicle>, and

  • No Comparator is provided to the TreeSet.

When the TreeSet tries to sort its elements internally (which happens when add() is called), it tries to compare the objects using their natural ordering. Since Vehicle does not provide a comparison mechanism, this leads to a runtime exception.

3. What Actually Happens:

At runtime, when you attempt to insert the first element, it works fine since the set is empty. But when you insert the second Vehicle object, TreeSet tries to compare the two Vehicle objects to maintain the sort order. This comparison fails because Vehicle does not implement Comparable, and hence, Java throws a ClassCastException.

4. Fixing the Code (Optional Insight):

To fix this issue, you could:

  • Make Vehicle implement Comparable<Vehicle> and override the compareTo() method, or

  • Pass a Comparator<Vehicle> to the TreeSet constructor.

Conclusion:

The correct answer is: D. A ClassCastException is thrown at runtime.

Because the TreeSet requires elements to be comparable for sorting, and the Vehicle class does not implement the Comparable interface or provide a comparator, the code fails at runtime when attempting to compare elements.

Question no 3:

Given that the file course.txt exists and contains the following content:

Course : : Java -

And the following Java code is executed:

import java.io.*;


public class Test {

    public static void main(String[] args) {

        int i;

        char c;

        try (FileInputStream fis = new FileInputStream("course.txt");

             InputStreamReader isr = new InputStreamReader(fis)) {


            while (isr.ready()) { // line n1

                isr.skip(2);

                i = isr.read();

                c = (char) i;

                System.out.print(c);

            }


        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}


What will be the result when the program is executed?

A. ur :: va
B. ueJa
C. The program prints nothing.
D. A compilation error occurs at line n1.

Explanation:

This code is designed to read from a text file character by character using an InputStreamReader. Let’s analyze what it does step-by-step.

Content of course.txt:

yaml

CopyEdit

Course : : Java -


That is 17 characters (including spaces and symbols).

Key logic in the code:

  • isr.skip(2); – Skips the next 2 characters in the stream.

  • i = isr.read(); – Reads the next character.

  • (char) i – Converts the read byte to a character.

  • System.out.print(c); – Prints the character.

This sequence is repeated in a loop as long as isr.ready() returns true (i.e., more characters are available to read).

So the logic is:

  • Skip 2 characters

  • Read and print the 3rd character

  • Repeat until EOF

Step-by-step analysis:

Let's break the string into indexed characters:

Index

Character

0

C

1

o

2

u

3

r

4

s

5

e

6


7

:

8


9

:

10


11

J

12

a

13

v

14

a

15


16

-

Now simulate the loop:

  • Skip [C, o], read u  -  print u

  • Skip [r, s], read e  -  print e

  • Skip [ , :], read space

  • Skip [:, space], read J  -  print J

  • Skip [a, v], read a  -  print a

  • Skip [ , -], nothing more to read

Printed output:

ueJa

Conclusion:

The correct answer is: B. ueJa

The code successfully skips 2 characters and prints the 3rd one in each iteration until the end of the file. There is no compilation error at line n1, and the file is accessible and processed as expected.

Question no 4:

Consider the following generic Java class and the associated code fragment:

public class Test<T> {

    private T t;


    public T get() {

        return t;

    }


    public void set(T t) {

        this.t = t;

    }


    public static void main(String[] args) {

        Test<String> type = new Test<>();

        Test type1 = new Test();  // line n1

        type.set("Java");

        type1.set(100);           // line n2

        System.out.print(type.get() + " " + type1.get());

    }

}

What is the result of this code?

A. Java 100
B. java.lang.String@<hashcode> java.lang.Integer@<hashcode>
C. A compilation error occurs. To rectify it, replace line n1 with: Test<Integer> type1 = new Test<>();
D. A compilation error occurs. To rectify it, replace line n2 with: type1.set(Integer(100));

Explanation:

Understanding Generics in Java:

The class Test<T> is a generic class, which means it can work with any type T (e.g., String, Integer, etc.).

  • When you declare Test<String> type = new Test<>();, you are explicitly telling the compiler to enforce that this object will only store String values.

  • But the line Test type1 = new Test(); is a raw type declaration. This disables type checking for generics and allows storing objects of any type without compile-time warnings (though it's not recommended and may produce unchecked warnings).

Line-by-line Analysis:

  • type.set("Java");  -  Valid. type is declared as Test<String>.

  • type1.set(100);  -  Allowed at compile time because type1 is a raw type, which means it bypasses type safety. So the integer value 100 is accepted.

At Runtime:

  • type.get() returns "Java" (a String).

  • type1.get() returns 100 (an Integer).

Printing:

System.out.print(type.get() + " " + type1.get());

  • type.get() returns the string "Java".

  • type1.get() returns the integer 100, which is auto-boxed and converted to its string form due to string concatenation.

Therefore, the output is:Java 100

Conclusion:

The correct answer is: A. Java 100

Additional Notes:

  • Raw types should be avoided in modern Java code because they defeat the purpose of generics and may lead to runtime ClassCastException.

  • A better, type-safe alternative would be:

Test<Integer> type1 = new Test<>();

type1.set(100);

But that is not necessary to make this code work as-is.

Question no 5:

Consider the following class definition in Java:

class Vehicle {

    String name;


    void setName(String name) {

        this.name = name;

    }


    String getName() {

        return name;

    }

}

In object-oriented programming, encapsulation is a key principle that involves restricting direct access to some of an object's components, typically its fields, and controlling that access through methods.

Which of the following actions best encapsulates the Vehicle class?

A. Make the Vehicle class public.
B. Make the name variable public.
C. Make the getName method public.
D. Make the name variable private.
E. Make the setName method private.
F. Make the getName method private.

Correct Answer: D. Make the name variable private.

Explanation:

Encapsulation is a fundamental concept in object-oriented programming that aims to bundle the data (variables) and the methods that operate on the data into a single unit  -  the class. It also hides the internal state of an object from the outside world and only exposes what is necessary via controlled interfaces (methods).

In the given Vehicle class, the field name is currently package-private, meaning it is accessible from other classes in the same package. This does not fully encapsulate the class because it allows external code to directly access and modify the name variable without using the provided methods (setName and getName).

To properly encapsulate the class, the name variable should be declared private, as in:

private String name;

This change ensures that name can only be accessed or modified using the class's public methods, which allows better control over the data. For example, you could later modify setName to include validation logic without affecting external code.

Making the variable public (Option B) breaks encapsulation, as it allows uncontrolled access. Making the getName or setName methods private (Options E and F) would prevent external code from interacting with the field altogether, defeating their purpose. Option A (making the class public) affects visibility across packages but does not directly relate to encapsulation of its fields.

Therefore, Option D  -  making the name variable private  -  is the correct step to encapsulate the Vehicle class properly.

Question no 6:

Consider the following Java class and code fragment:

public class Product {

    int id;

    int price;


    public Product(int id, int price) {

        this.id = id;

        this.price = price;

    }


    public String toString() {

        return id + ":" + price;

    }

}

And the code fragment:

List<Product> products = Arrays.asList(

    new Product(1, 10),

    new Product(2, 30),

    new Product(2, 30)

);


Product p = products.stream().reduce(

    new Product(4, 0),

    (p1, p2) -> {

        p1.price += p2.price;

        return new Product(p1.id, p1.price);

    }

);


products.add(p);


products.stream().parallel()

    .reduce((p1, p2) -> p1.price > p2.price ? p1 : p2)

    .ifPresent(System.out::println);

What is the result of executing this code?

A. 2:30
B. 4:0
C. 4:60
D. 4:60 2:30 3:20 1:10
E. The program prints nothing.

Correct Answer: C. 4:60

Explanation:

Let’s analyze the code step-by-step:

  1. Class Setup:

    • Product has two fields: id and price.

    • The toString() method outputs the product in the format id:price.

Creating the List:
List<Product> products = Arrays.asList(

    new Product(1, 10),

    new Product(2, 30),

    new Product(2, 30)

);


    • You now have a list of 3 products with respective prices 10, 30, and 30.

Reduce Operation:
Product p = products.stream().reduce(

    new Product(4, 0),

    (p1, p2) -> {

        p1.price += p2.price;

        return new Product(p1.id, p1.price);

    }

);


    • This operation adds up the prices of all elements in the stream, starting with a new Product(4, 0).

    • It adds: 0 + 10 + 30 + 30 = 70 (but it looks like a bug  -  wait for the catch).

  1. However, each time the lambda returns a new Product object, meaning it doesn't carry over the reference used to accumulate the value correctly  -  but p1.price += p2.price is still modifying the original p1 before returning a new one. This causes cumulative side effects on the accumulator (p1). So, ultimately, p1 ends up having price = 60 (not 70), and id = 4.

Add the result to the list:
products.add(p);

  1.  Now the list has four elements. The last one is Product(4, 60).

Find max price in parallel stream:
products.stream().parallel()

    .reduce((p1, p2) -> p1.price > p2.price ? p1 : p2)

    .ifPresent(System.out::println);


    • This gets the product with the highest price.

    • The product with the highest price is Product(4, 60).

Final Output:

4:60

Hence, correct answer: C. 4:60

Question no 7:

You are given the following Java class definition:

public class Book implements Comparator<Book> {

    String name;

    double price;


    public Book() {}


    public Book(String name, double price) {

        this.name = name;

        this.price = price;

    }


    public int compare(Book b1, Book b2) {

        return b1.name.compareTo(b2.name);

    }


    public String toString() {

        return name + ":" + price;

    }

}


And the following code fragment:

List<Book> books = Arrays.asList(

    new Book("Beginning with Java", 2),

    new Book("A Guide to Java Tour", 3)

);


Collections.sort(books, new Book());

System.out.print(books);


What is the result of executing this code?

A. [A Guide to Java Tour:3.0, Beginning with Java:2.0]
B. [Beginning with Java:2.0, A Guide to Java Tour:3.0]
C. A compilation error occurs because the Book class does not override the abstract method compareTo().
D. An Exception is thrown at runtime.

Correct Answer: A. [A Guide to Java Tour:3.0, Beginning with Java:2.0]

Explanation:

Let’s analyze the code in detail.

  1. Class Design:

    • The Book class implements the Comparator<Book> interface.

    • It provides an implementation for the compare(Book b1, Book b2) method, which compares books by their name using String.compareTo().

  2. The toString() method:

    • This method is overridden to display book objects in the format: "name:price".

    • So, when we print a list of Book objects, we will see a readable format like BookName:Price.

Creating the Book List:
List<Book> books = Arrays.asList(

    new Book("Beginning with Java", 2),

    new Book("A Guide to Java Tour", 3)

);


    • A list of two books is created.

Sorting with Collections.sort:
Collections.sort(books, new Book());


    • Here, we pass a new Book object as a comparator to sort the list.

    • Even though this Book object doesn't have meaningful data (name and price are null), it acts solely as a comparator because the compare() method is implemented.

    • The compare() method compares the name fields of the books lexicographically.

  1. Sorting Logic:

    • "A Guide to Java Tour" comes before "Beginning with Java" alphabetically.

Hence, after sorting, the list order becomes:
[A Guide to Java Tour:3.0, Beginning with Java:2.0]


  1. Output:

    • System.out.print(books); prints the sorted list using the overridden toString() method for each object.

Final Output:

[A Guide to Java Tour:3.0, Beginning with Java:2.0]


Thus, the correct answer is A.

Question no 8:

You are given the following Java code fragment:

List<String> listVal = Arrays.asList("Joe", "Paul", "Alice", "Tom");

System.out.println(

// line n1

);

You want to insert a code statement at line n1 to print the number of strings in the list that have a length greater than 3.

Which of the following code fragments, when inserted at line n1, will correctly achieve this?

A. listVal.stream().filter(x -> x.length() > 3).count()
B. listVal.stream().map(x -> x.length() > 3).count()
C. listVal.stream().peek(x -> x.length() > 3).count().get()
D. listVal.stream().filter(x -> x.length() > 3).mapToInt(x -> x).count()

Correct Answer: A. listVal.stream().filter(x -> x.length() > 3).count()

Explanation:

Let’s walk through the logic behind this code and each answer option.

You are working with a list of strings:

["Joe", "Paul", "Alice", "Tom"]


You need to count how many of these strings have more than 3 characters. Let’s analyze the stream operation for that purpose.

Option A:

listVal.stream().filter(x -> x.length() > 3).count()


  • This creates a stream of the list.

  • It filters the elements, keeping only those whose length is greater than 3.

  • Then, it uses .count() to count the number of filtered elements.

  • Paul and Alice satisfy this condition (length > 3), so the output will be 2.

  • This is the correct and intended behavior.

Option B:

listVal.stream().map(x -> x.length() > 3).count()


  • This maps each string to a boolean (true or false) based on length.

  • Then it counts all items  -  not just the true ones.

  • This will return 4 because there are 4 elements, regardless of their length.

  • Incorrect logic for filtering and counting.

Option C:

listVal.stream().peek(x -> x.length() > 3).count().get()


  • peek() is for debugging/side effects, not filtering.

  • Also, count() returns a long, not an Optional  -  calling .get() causes a compile-time error.

  • Compilation error.

Option D:

listVal.stream().filter(x -> x.length() > 3).mapToInt(x -> x).count()


  • mapToInt(x -> x) is invalid because x is a String, and cannot be mapped to int this way without parsing or transformation.

  • Compilation error.

Final Answer: A. listVal.stream().filter(x -> x.length() > 3).count()

This will correctly print 2

Question no 9:

Consider the following two classes in Java:

class Caller implements Callable<String> {

    String str;


    public Caller(String s) {

        this.str = s;

    }


    public String call() throws Exception {

        return str.concat("Caller");

    }

}


class Runner implements Runnable {

    String str;


    public Runner(String s) {

        this.str = s;

    }


    public void run() {

        System.out.println(str.concat("Runner"));

    }

}

And the following code in the main method:

public static void main(String[] args) throws InterruptedException, ExecutionException {

    ExecutorService es = Executors.newFixedThreadPool(2);

    Future f1 = es.submit(new Caller("Call"));

    Future f2 = es.submit(new Runner("Run"));


    String str1 = (String) f1.get();

    String str2 = (String) f2.get(); // line n1

    System.out.println(str1 + ":" + str2);

}

Which of the following is the result of executing this code?

A. The program prints: Run Runner Call Caller : null and the program does not terminate.
B. The program terminates after printing: Run Runner Call Caller : Run
C. A compilation error occurs at line n1.
D. An ExecutionException is thrown at runtime.

Correct Answer: C. A compilation error occurs at line n1.

Explanation:

Let’s break down the code and understand the behavior of the Caller and Runner classes, and why the program leads to a compilation error at line n1.

Caller Class:

  • The Caller class implements the Callable<String> interface.

  • The call() method is overridden to concatenate the string "Caller" to the input string and return it.

  • Since Callable<String> returns a result, when f1.get() is called, the call() method is executed and a String is returned.

Runner Class:

  • The Runner class implements the Runnable interface.

  • The run() method is overridden to concatenate the string "Runner" to the input string and print it to the console.

  • Runnable does not return a value, so the run() method is executed but does not provide any result to f2.get().

Main Method:

  • A fixed thread pool ExecutorService es is created with two threads.

  • es.submit(new Caller("Call")) submits a Callable task (f1), and es.submit(new Runner("Run")) submits a Runnable task (f2).

Line n1:

  • The critical issue is at line n1: String str2 = (String) f2.get();.

  • The Runner class implements Runnable, which does not return any result. When f2.get() is called, it tries to retrieve a result from a Runnable task, which will throw an exception because Runnable does not return a value.

  • Since f2 is a Future for a Runnable, calling get() on it will throw an ExecutionException, because Runnable doesn't provide a result to retrieve.

Why Compilation Error?

  • At compile time, f2 is declared as a Future without a generic type, and when f2.get() is called, it attempts to cast null (the return type of Runnable) to a String, which results in a compilation error. This is because Runnable does not provide a return value, and you cannot cast a non-existent value (the result of a Runnable) to a String.

Conclusion:

  • The compilation error occurs because the code tries to cast a result from a Runnable (which does not return a result) into a String. This causes a compilation failure at line n1. Therefore, Option C is correct.

Answer: C. A compilation error occurs at line n1.


How It Works

Download Exam
Step 1. Choose Exam
on Exam-Labs
Download IT Exams Questions & Answers
Download Avanset Simulator
Step 2. Open Exam with
Avanset Exam Simulator
Press here to download VCE Exam Simulator that simulates latest exam environment
Study
Step 3. Study
& Pass
IT Exams Anywhere, Anytime!

SPECIAL OFFER: GET 10% OFF. This is ONE TIME OFFER

You save
10%
Save
Exam-Labs Special Discount

Enter Your Email Address to Receive Your 10% Off Discount Code

A confirmation link will be sent to this email address to verify your login

* We value your privacy. We will not rent or sell your email address.

SPECIAL OFFER: GET 10% OFF

You save
10%
Save
Exam-Labs Special Discount

USE DISCOUNT CODE:

A confirmation link was sent to your email.

Please check your mailbox for a message from support@exam-labs.com and follow the directions.