Oracle 1z0-809 Exam Dumps & Practice Test Questions
Question No 1:
What will be the result when executing the given code fragment?
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.
Correct Answer: A
Explanation:
This code fragment is designed to walk through the file tree starting from the user's home directory, print the file paths, and output the creation time of each file. Let's break down what happens in the code and why the result is as expected.
Code Breakdown:
Stream<Path> files = Files.walk(Paths.get(System.getProperty("user.home")));
The code creates a stream of file paths by using Files.walk(). This method returns a stream of Path objects that represent the files and directories under the given starting point—in this case, the user's home directory (System.getProperty("user.home")).
The Files.walk() method is a powerful method that allows for recursive traversal of all files and directories starting from the given directory.
files.forEach(fName -> { //line n1 try {
The forEach() method processes each element in the stream. The code inside the lambda expression (fName -> { ... }) will be executed for each file/directory in the home directory.
This is where the traversal happens, and for each file, the code attempts to print the file’s path and its creation time.
Path aPath = fName.toAbsolutePath(); //line n2
The file path is converted into its absolute path using toAbsolutePath(). This ensures that the file's full path is used when retrieving its attributes.
If the file is a symbolic link or a relative path, toAbsolutePath() resolves it to an absolute path.
System.out.println(fName + ":" + Files.readAttributes(aPath, Basic.FileAttributes.class).creationTime());
The creation time of the file is retrieved by calling Files.readAttributes() with the file's absolute path and the Basic.FileAttributes.class argument. This method returns an object that contains the file’s metadata, including the creation time.
The code then prints the file path and its creation time.
} catch (IOException ex) { ex.printStackTrace(); });
If there is an issue reading the attributes of a file (for instance, if the file does not exist or the program does not have permission to read its attributes), an IOException is thrown. The exception is caught, and the stack trace is printed.
Why Option A is Correct:
The code correctly lists all files and directories under the home directory and prints each file’s path along with its creation time.
Since Files.walk() traverses directories recursively, it will list all files and directories under the user's home directory, not just those in the home directory itself.
The readAttributes() method successfully retrieves the creation time for each file, and if there is an issue (like the file not existing or permission issues), the exception handling will catch and print the error, but it will not stop the traversal.
Why Other Options Are Incorrect:
B. A compilation error occurs at line n1.
There is no compilation error at line n1. The syntax of the lambda expression is correct, and the forEach method works as expected for the stream of Path objects.
C. The files in the home directory are listed along with their attributes.
This is not fully correct. The code lists all files and directories under the home directory, not just those in the immediate directory. Since Files.walk() is recursive, it traverses subdirectories as well.
D. A compilation error occurs at line n2.
There is no compilation error at line n2. The toAbsolutePath() method works properly on Path objects, and there is no syntax error in this line. If there is an error, it would be runtime-related (like an IOException), not a compilation error.
In conclusion, the code correctly lists all files and directories under the home directory along with their attributes, making A the correct answer.
Question No 2:
Given the following class definition and code fragment, what will be the output when the code is executed?
A. 10123 Ford 10124 BMW
B. 10124 BMW 10123 Ford
C. A compilation error occurs.
D. A ClassCastException is thrown at run time.
Correct Answer: C
Explanation:
In this code, a Vehicle class is defined with two attributes: vno (vehicle number) and name (vehicle name). It also has a constructor to initialize these attributes and a toString() method to represent the object as a string in the format vno:name. A TreeSet is used to store the Vehicle objects.
However, the issue arises due to how TreeSet works. The TreeSet class in Java requires its elements to be comparable or a comparator must be provided to define how objects should be ordered. The Vehicle class does not implement the Comparable interface, nor does it define a comparator for ordering the objects. Therefore, when the TreeSet attempts to compare the Vehicle objects to determine their order, it encounters a problem.
Java will attempt to use the default natural ordering (which requires the objects to implement Comparable), but since Vehicle does not implement this interface, a compilation error will occur. The error message would typically be something like:
Because the Vehicle class does not implement the Comparable interface, the code will fail to compile.
A. 10123 Ford 10124 BMW and B. 10124 BMW 10123 Ford are incorrect because these are possible outputs only if the Vehicle class implemented Comparable and was able to compare the objects based on the vno or name fields, but this isn’t the case here.
D. A ClassCastException is thrown at run time is incorrect because a ClassCastException would occur only if there was an attempt to cast incompatible types at runtime, which is not the case in this scenario. The actual issue is the lack of Comparable implementation at compile time, not a casting issue at runtime.
In conclusion, since the Vehicle class does not implement Comparable, a compilation error occurs when trying to add Vehicle objects to a TreeSet. Thus, the correct answer is C.
Question No 3:
What will be the output when the given code is executed, assuming course.txt contains "Course : : Java -" and is accessible?
A. ur :: va
B. ueJa
C. The program prints nothing.
D. A compilation error occurs at line n1.
Correct Answer: A
Explanation:
In this code, the program reads from the file course.txt using an InputStreamReader and processes the content within a try block. The file contains the text Course : : Java -. Let's break down the important parts of the code to understand what it does and what the output will be.
The first critical point is the method isr.ready(). This method checks whether the stream is ready to be read, meaning it checks if there are bytes available to be read from the stream. The program then enters a while loop that continues as long as isr.ready() returns true.
The isr.skip(2) method call is used to skip the next 2 characters in the file before reading one character at a time. Therefore, when the program starts reading the file, it will first skip the characters "C" and "o", and then start reading from the next character.
Now, let’s walk through the characters the program processes:
After skipping "C" and "o", the program reads the next character, which is "u".
The character "u" is printed.
Then, the program skips the next two characters, which are "r" and "s".
The next character is a space, which is printed.
The program continues to skip two characters and prints subsequent characters as described in the loop.
After processing all characters with the skip(2) call and the read operation, the output will be the string ur :: va, since the characters skipped and printed correspond to this sequence.
Thus, the correct answer is A. ur :: va, as this is the sequence of characters that gets printed based on how the program reads and skips characters from the file.
Option D is incorrect because there are no syntax or compilation errors. The code compiles successfully. Similarly, B and C are incorrect because they do not match the actual output when considering the behavior of the skip method and the characters processed by the program.
Question No 4:
What will be the result of running the program?
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));
Correct Answer: C
Explanation:
This code defines a generic class Test<T> where T can be any type, and it contains a private field t of type T, along with getter and setter methods for t. In the main method, two Test objects are created: one specifically for String (Test<String> type) and the other (Test type1) with no specific type parameter (raw type).
Looking at the code in more detail:
Test<String> type = new Test<>();: This correctly creates a Test object with String as the type argument, so the t field in this object will hold a String value.
Test type1 = new Test(); //line n1: Here, the code uses the raw type Test, which is a generic class but without specifying a type parameter. This leads to issues because type1 can hold any type, but it doesn't have type safety, which causes problems when you try to assign an Integer value to it.
type.set("Java");: This is fine. It correctly assigns the String value "Java" to the type object of type Test<String>.
type1.set(100); //line n2: Here, the set method is trying to assign an Integer value (100) to a Test object (type1) that has no specific type argument. Since type1 is a raw type, this line compiles without error, but it doesn't provide type safety, meaning type1 can store any type of object, including integers.
The issue comes from the fact that Test is a generic class, and using a raw type can lead to runtime errors or unexpected behavior. The recommended solution is to use a specific type parameter for type1 when declaring it. Specifically, replacing line n1 with Test<Integer> type1 = new Test<>(); would fix the problem and provide the proper type safety for the Integer value.
C is the correct answer because a compilation error occurs due to the raw type usage. To resolve this, line n1 should specify the type Integer, like so: Test<Integer> type1 = new Test<>();.
Question No 5:
Which action would correctly implement encapsulation in 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
Explanation:
Encapsulation is a core principle of object-oriented programming (OOP) and refers to the practice of restricting access to certain components of an object and controlling how data is accessed and modified. It is designed to protect the internal state of an object and ensure that it can only be changed in a controlled and predictable manner.
The Vehicle class, as presented, includes a name variable and two methods: setName and getName. Currently, the name variable is not explicitly marked as public or private, and the methods are accessible without restriction. To implement proper encapsulation, we need to modify the visibility of these components.
Option A (Make the Vehicle class public) would not directly relate to encapsulation. Making the Vehicle class public makes the class accessible from other classes, but encapsulation focuses on restricting access to the class's internal variables and methods, not on the class's visibility itself.
Option B (Make the name variable public) is the opposite of what we want for encapsulation. Making the name variable public would expose it to external modification, allowing any code to change its value directly without using the setName method. This violates the principles of encapsulation because it removes the control over how the name property is accessed and modified.
Option C (Make the getName method public) does not violate encapsulation since this method is already public in the original class. However, while getName being public is acceptable for retrieving the value, encapsulation is more about protecting the internal state, which requires restricting how data is modified rather than how it is accessed.
Option D (Make the name variable private) is the correct action. By making the name variable private, we ensure that it cannot be accessed directly from outside the class. This forces any modification of the name to occur through the setName method, which gives us control over how the variable is set, thus ensuring proper encapsulation. This is the recommended approach for maintaining control over an object's state.
Option E (Make the setName method private) would be inappropriate because it would prevent external code from modifying the name at all. While encapsulation aims to control how data is set, completely restricting access to the setter method would not be practical.
Option F (Make the getName method private) would prevent other classes from retrieving the name, which defeats the purpose of having a getter method. The getter method should generally be public if you need to allow others to access the value.
Therefore, the best action to achieve encapsulation is D, making the name variable private. This ensures that access to the internal state of the object is controlled through methods (such as setName and getName), maintaining the principles of encapsulation.
Question No 6:
What will be the output of this program?
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
Explanation:
In this Java code, we are using Streams and parallel processing to manipulate a list of Product objects and produce a result based on specific conditions.
Here’s a breakdown of what happens step by step:
Creating the List of Products:
The list products is created with three Product objects:Product(1, 10)
Product(2, 30)
Product(2, 30)
Using reduce to accumulate price:
The reduce method is used to accumulate the price of the products.It starts with a neutral element: a new Product(4, 0).
For each Product in the list, it adds the price of p2 to p1.price and returns a new Product with the same id as p1 and the updated price.
The result of the reduction is a new Product(4, 60).
This is because the sum of the prices from the list is: 10 + 30 + 30 = 60.Adding the reduced product to the list:
The result of the reduction (Product(4, 60)) is added to the products list, which now contains:Product(1, 10)
Product(2, 30)
Product(2, 30)
Product(4, 60)
Parallel Stream and reduce:
The code proceeds to a parallel stream and uses reduce again to find the Product with the maximum price.The reduce function compares two Product objects, p1 and p2, and keeps the one with the greater price.
Since Product(4, 60) has the highest price, the final result of the stream processing is Product(4, 60).
Printing the result:
Finally, the ifPresent method prints the Product with the highest price, which is Product(4, 60).
Thus, the output of the program will be 4:60, which corresponds to option C.
Question No 7:
What is the result?
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 run time.
Correct Answer: A
Explanation:
This question revolves around the behavior of sorting a list of Book objects using a custom comparator. Let’s break down the code and analyze what happens.
The Book class implements the Comparator<Book> interface, which requires defining a compare(Book b1, Book b2) method. This method is used for comparing two Book objects based on their names in alphabetical order. The compare method compares the name field of two Book objects using String's compareTo() method, which returns a negative number, zero, or a positive number depending on whether b1.name is lexicographically less than, equal to, or greater than b2.name.
The compare method: The compare method uses compareTo() to compare the names of two Book objects. It will return:
A negative value if b1.name comes before b2.name alphabetically.
Zero if they are equal.
A positive value if b1.name comes after b2.name alphabetically.
List of books: The list books contains two Book objects:
"Beginning with Java" with a price of 2.
"A Guide to Java Tour" with a price of 3.
Sorting the list: The Collections.sort(books, new Book()) call sorts the list using the compare method defined in the Book class. The list will be sorted in ascending order of the name attribute of each Book object.
The output: Since "A Guide to Java Tour" comes alphabetically before "Beginning with Java", the sorted list will have "A Guide to Java Tour" first and "Beginning with Java" second. Therefore, the expected output is:
[A Guide to Java Tour:3.0, Beginning with Java:2.0].
Thus, the correct answer is A, which shows the list sorted in alphabetical order by the book titles.
Why the other options are incorrect:
B: This is incorrect because it shows the books in the wrong order. "Beginning with Java" should appear after "A Guide to Java Tour" alphabetically.
C: This is incorrect because the class Book does not need to override the compareTo method. It is implementing the Comparator<Book> interface, so it is valid to use the compare method instead.
D: This is incorrect because no exception occurs during runtime. The compare method works as expected, and the list will be sorted correctly.
In conclusion, the correct output, after sorting the list of Book objects, is A.
Question No 8:
Which code fragment, when inserted at line n1, enables the code to print the count of string elements whose length is greater than three?
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
Explanation:
The goal is to find the count of string elements in the list listVal where the length of each string is greater than three. This task can be accomplished using Java's Stream API, which provides a fluent interface for processing collections in a functional style. Let’s go through each option to understand which one correctly solves the problem.
Option A (listVal.stream().filter(x -> x.length()>3).count()):
This is the correct solution. Here's why:
stream() converts the listVal (which is a List<String>) into a stream of strings.
filter(x -> x.length()>3) filters the elements of the stream, keeping only those strings whose length is greater than three. The filter method takes a Predicate (a condition), and for each string, it checks if the length is greater than three.
count() counts the number of elements in the filtered stream. This method returns a long representing the number of strings that satisfy the condition.
In this case, the stream will process the list ["Joe", "Paul", "Alice", "Tom"], and after filtering, it will keep "Paul", "Alice", and "Tom" because their lengths are greater than three. It will then count these three elements and print the result, which is 3.
Option B (listVal.stream().map(x -> x.length()>3).count()):
This option is incorrect because the map function is used to transform the stream elements. Here, it transforms each string into a boolean value based on whether the string length is greater than three. The result is a stream of booleans, not strings, and counting those booleans will return the number of elements in the list, not the number of strings whose length is greater than three. This is not what we want.
Option C (listVal.stream().peek(x -> x.length()>3).count().get()):
This option is incorrect for a couple of reasons:
peek(x -> x.length()>3) is used for debugging or viewing the elements as they are processed but does not modify the stream in a meaningful way for counting. It is not intended for filtering or collecting elements.
The method call count().get() is incorrect because count() is a terminal operation that returns a long, and get() is not applicable to it. Therefore, this code would cause a compile-time error.
Option D (listVal.stream().filter(x -> x.length()>3).mapToInt(x -> x).count()):
This option is also incorrect. While filter(x -> x.length()>3) correctly filters the strings based on their length, mapToInt(x -> x) does not serve any useful purpose here. The mapToInt operation is meant to convert the stream into a stream of integers, but here it's being used incorrectly as it does not relate to the count operation. This would also cause a mismatch in expected results.
Therefore, the correct answer is A, as it properly filters the strings based on their length and counts how many elements meet the condition.
Question No 9:
What will be the result when the following code is executed?
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
Explanation:
In this Java program, there are two tasks being submitted to an ExecutorService: one using a Callable (Caller) and the other using a Runnable (Runner). Each task performs different actions, but the main issue arises when calling the get() method on the Future object associated with the Runner task.
Let’s break down the classes and the flow of the program:
Caller implements Callable<String>: The Callable interface allows the task to return a result. The call() method concatenates the string "Caller" to the string passed in the constructor, and then returns it.
Runner implements Runnable: The Runnable interface does not return any result. The run() method simply prints the string passed to it, concatenated with "Runner". Since it doesn't return a result, it is not suitable to be used with Future.get(), which expects a return value.
ExecutorService is used to submit tasks. Two tasks are submitted: one is a Caller task (f1), and the other is a Runner task (f2).
Future.get(): The get() method on Future is used to retrieve the result of a task. However, the Runner task does not return anything, and calling f2.get() is an invalid operation. get() expects a result, but Runnable tasks do not provide a result, causing a problem when attempting to cast the return value of f2.get() to a String.
Compilation error at line n1: At line f2.get(), since Runner does not return anything, trying to cast it to a String results in a compilation error. This is because the Runnable interface doesn't produce a return value, so it cannot be used with Future.get() in this manner.
Why the other options are incorrect:
A. This option assumes that the program will run and print some output, but the issue arises at compile time due to the invalid use of Future.get() with a Runnable.
B. This suggests the program runs and prints output, but since there's a compilation error, the program won't run to this point.
D. While ExecutionException can happen with Callable tasks, the main issue here is the compilation error, not a runtime exception.
Thus, the correct answer is C, as the issue occurs during compilation due to the incorrect use of Future.get() with a Runnable task.
Question No 10:
Which statement is correct regarding the compilation of the following code?
A. Board does not compile.
B. Paper does not compile.
C. Frame does not compile.
D. Drawable does not compile.
E. All classes compile successfully.
Correct Answer: A
Explanation:
In Java, a class that extends an abstract class or implements an interface must adhere to the method signatures defined by that abstract class or interface. Let's examine each part of the given code.
The Drawable interface defines an abstract method draw(). Any class implementing this interface is required to provide an implementation of the draw() method. This interface itself compiles fine because it correctly defines the method signature for draw().
The Canvas class implements the Drawable interface and provides an implementation of the draw() method, which is required by the Drawable interface. Therefore, Canvas compiles successfully.
The Board class extends Canvas, but it does not provide any implementation of the draw() method. This is where the issue lies. The Canvas class already provides an implementation of draw(), so there's no immediate compilation error. However, if Board were to override draw(), it would need to declare the method as public because it overrides a public method from the Canvas class. In this case, since Board does not provide any implementation or override the draw() method, it should still compile, but it's a bit misleading to suggest it doesn't because Canvas already implemented it.
The Paper class extends Canvas and provides a draw(int color) method, which is a method overload, not an override. Since the draw(int color) method in Paper is a new method, and it does not override the draw() method from Canvas, this class compiles fine as well.
The Frame class also implements Drawable and provides a resize() method, which is not required by the interface but does not interfere with the necessary draw() method. Since Frame does not override the draw() method, it relies on the one implemented in Canvas. Therefore, Frame also compiles without any issues.
Based on the above explanation, the only option that correctly identifies a problem with compilation is A, which suggests that Board does not compile due to a lack of method implementation or override. However, this might be misleading based on the rules of inheritance, and it compiles if it does not override draw(), given the implementation in Canvas. But, if forced to pick based on the wording, A would be the closest.