Search Tutorials


Oracle Java 17 1Z0-829 Certification Exam Practice Test 2 (2024) | JavaInUse

Oracle Java 17 1Z0-829 Certification Exam Practice Test 2

Q. Given code:

package com.javainuse.ocp;
import java.util.*;
class Student {
private String name;
private int age;
CopyStudent(String name, int age) {
    this.name = name;
    this.age = age;
}

public String toString() {
    return "Student[" + name + ", " + age + "]";
}

public boolean equals(Object obj) {
    if(obj instanceof Student) {
        Student stud = (Student)obj;
        return this.name.equals(stud.name) &&
                            this.age == stud.age;
    }
    return false;
}
}
public class Test {
public static void main(String[] args) {
Set<Student> students = new HashSet<>();
students.add(new Student("Bill", 25));
students.add(new Student("Bill", 25));
students.add(new Student("Bill", 26));
Copy    System.out.println(students.size());
}
}

What will be the output when the main method is executed?

3
2
1
Runtime Exception

Q. Given code:

package com.javainuse.ocp;
public class Test {
public static void main(String[] args) {
String s1 = new String("ALL IS WELL"); //Line n1
String s2 = new String("ALL IS WELL"); //Line n2
System.out.println(s1 == s2); //Line n3
}
}

Which of the following changes, done independently, allows the code to compile and on execution prints true?

Replace Line n1 with: String s1 = new String("ALL IS WELL").intern();
Replace Line n2 with: String s2 = new String("ALL IS WELL").intern();
Replace Line n3 with: System.out.println(s1.toString() == s2.toString());
Replace Line n2 with: String s2 = s1.toString();
Replace Line n1 with: String s1 = "ALL IS WELL";
Replace Line n2 with: String s2 = "ALL IS WELL";

Q. Given code:

package com.javainuse.ocp;
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(0, 10);
list.addFirst(20);
list.add(1, 30);
list.addLast(40);
Copy    if(list.contains(40)) {
        list.removeLast();
    }
    
    for(int num : list) {
        System.out.print(num + " ");
    }
}
}

What will be the output when the main method is executed?

Runtime error
Compilation error
20 10 30 40
20 30 10
10 20 30 40

Q. Given code:

package com.javainuse.ocp;
interface Comparable<T> {}
class Animal {}
class Dog extends Animal {}
class AnimalComparator<T extends Animal> implements Comparable<T> {}
class DogComparator extends AnimalComparator<Dog> {}

Will this code compile successfully?

Yes
No

Q. Given code:

package com.javainuse.ocp;
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.push(Integer.valueOf("10"));
list.push(Integer.valueOf("20"));
list.push(Integer.parseInt("30"));
list.push(40);
System.out.println(list.pop() + ":"
+ list.peek() + ":" + list.size());
}
}

What will be the output when the main method is executed?

40:30:3
30:40:3
40:40:3
40:30:4

Q. Given code:

package com.javainuse.ocp;
public class Test {
public static void main(String[] args) {
int sum = 0;
outer: for (var i = 0; i < 3; i++) {
middle: for (var j = 0; j < 3; j++) {
inner: for (var k = 0; k < 3; k++) {
if (i == j) {
continue middle;
} else if (j == k) {
continue inner;
} else {
sum += i + j + k;
}
}
}
}
System.out.println(sum);
}
}

What will be the output when the main method is executed?

9
12
15
18
Compilation error

Q. Given code:

package com.javainuse.ocp;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
var scanner = new Scanner(System.in);
System.out.print("Enter a number between 1 and 5: "); //Line n1
var input = scanner.nextLine(); //Line n2
var num = Integer.parseInt(input.substring(0, 1));
var result = switch(num) {
case 1, 2, 3, 4, 5 -> "#".repeat(num);
default -> "INVALID";
};
System.out.println(result); //Line n3
}
}

Which of the following statements are correct regarding the program when executed from the command line?

If user input is 5, then it prints #####
It causes compilation failure
If user input is 7, then it prints #######
It waits indefinitely for the user input after displaying the text: "Enter a number between 1 and 5: "
If user input is 11, then it prints #

Q. Given code:

package com.javainuse.ocp;
// This is a conceptual question, so no specific code is provided.
// The focus is on understanding module dependencies and migration strategies.

You are tasked with modularizing an application that consists of four JAR files: ui.jar, logic.jar, data.jar, and util.jar. The dependencies are as follows: ui.jar depends on logic.jar, logic.jar depends on data.jar, and all three depend on util.jar. You decide to use a bottom-up approach for modularization. Which of the following sequences represents the correct order for modularizing these components?

Modularize ui.jar first, then convert the rest to automatic modules
Modularize util.jar, then data.jar, logic.jar, and finally ui.jar
Modularize logic.jar and data.jar, leaving util.jar as a regular JAR
Convert all JARs to automatic modules simultaneously
Modularize ui.jar and logic.jar, leaving data.jar and util.jar as regular JARs

Q. Given code

package com.javainuse.ocp;
import java.util.LinkedList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Character> list = new LinkedList<>();
list.add('J');
list.add('A');
list.add('V');
list.add('A');
Copy    List<Character> subList = list.subList(1, 3); // Line n1
    subList.set(1, 'I');                         // Line n2
    subList.add('D');                             // Line n3

    System.out.println(String.join("", list.stream()
                            .map(String::valueOf)
                            .toList()));
}
}

What is the output?

JAVA
JAID
JAVID
An exception is thrown at Line n3

Q. Given code

package com.javainuse.ocp;
public class Test {
public static void main(String[] args) {
String text = "  \t\nHello, World!\r\n  "; // Contains various whitespace characters
System.out.println(text./INSERT/);
}
}

Consider the code of Test.java file below. Which of the following options, if used to replace /INSERT/, will compile successfully and on execution will print "Hello, World!" on to the console? Select all correct answers:

trimAll()
strip()
trim()
removeWhitespace()
stripLeading().stripTrailing()
trim().strip()

Q. Given code

package com.javainuse.ocp;
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) {
var df1 = new DecimalFormat("#,##0.0#");
var df2 = new DecimalFormat("#,##0.##");
double value = 12345.67;
System.out.println(df1.format(value)
.equals(df2.format(value)));
}
}

What will be printed to the console? Select the correct answer:

true
false
Compilation error
Runtime exception

Q. Given code:

package com.javainuse.ocp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Java", "Python", "C++"));
list.stream()
.map(String::toUpperCase)
.sorted()
.limit(2)
.collect(Collectors.toList());
System.out.println(list.get(1));
}
}

What will be printed to the console?

JAVA
PYTHON
Python
RuntimeException

Q. Given the directory structure below and the code that follows, what will be printed to the console when the Test class is compiled and executed?

F:
+---Projects
|   \---JavaApp
|           Main.java
|
+---Temp
|       Config.ini
|
\---Backup
    \---Archive

    
package com.javainuse.ocp;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String[] args) {
Path path1 = Paths.get("F:", "Projects", "JavaApp");
Path path2 = Paths.get("..", "..", "Temp", "Config.ini");
Copy    Path path3 = path1.resolve(path2).normalize();
    Path path4 = path1.getParent().resolve(path2).normalize();

    System.out.println(path3.equals(path4));
}
}

What will be printed to the console?

true
false
RuntimeException
CompilationError

Q. Consider the code below. Which of the following statements can replace Line n1 such that there is no change in the output?

package com.javainuse.ocp;
@FunctionalInterface
interface Transformer {
String transform(String s);
}
class StringUtils {
public static String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
}
public class Test {
public static void main(String[] args) {
Transformer t = s ->
new StringBuilder(s).reverse().toString(); //Line n1
System.out.println(t.transform("Java"));
}
}

Which statement can replace Line n1?

Transformer t = (String s) -> StringUtils.reverse(s);
Transformer t = StringUtils::reverse;
Transformer t = ("Java") -> StringUtils.reverse("Java");
Transformer t = StringUtils::reverse();
Transformer t = s -> StringUtils.reverse(s);

Q. Given the code below, what will be printed to the console?

package com.javainuse.ocp;
import java.util.*;
class Product {
private String name;
private double price;
Copypublic Product(String name, double price) {
    this.name = name;
    this.price = price;
}

public String getName() { return name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }

public String toString() {
    return "[" + name + ", $" + price + "]";
}
}
public class Test {
public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product("Laptop", 1000),
new Product("Phone", 500));
products.stream()
.filter(p -> p.getPrice() > 700)
.peek(p -> p.setPrice(p.getPrice() * 0.9))
.forEach(System.out::println);
}
}

What will be printed to the console?

[Laptop, $900.0]
[Laptop, $1000.0]
[Phone, $500.0]
[Laptop, $900.0]
[Phone, $450.0]
No output

Q. Given the code, what will be printed when the main method is executed?

package com.javainuse.ocp;
public class Test {
private static class Outer {
private String message = "JAVA ";
Copy    class Inner {
        private String message = "IS ";
        
        void concatenate(String s) {
            System.out.print(Outer.this.message);
            System.out.print(this.message);
            System.out.print(s);
        }
    }
}

public static void main(String[] args) {
    new Outer().new Inner().concatenate("COOL");
}
}

What will be printed when the main method is executed?

JAVA IS COOL
JAVA JAVA COOL
IS IS COOL
Compilation error

Q. Given the code, what will be the output when the main method is executed?

package com.javainuse.ocp;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) throws IOException {
Path dir = Paths.get(System.getProperty("user.home"));
try (Stream<Path> stream = Files.walk(dir, 1)) {
stream.filter(path -> !path.equals(dir))
.map(Path::getFileName)
.forEach(System.out::println);
}
}
}

What will be the output when the main method is executed?

It will print only the names of files (not directories) in the HOME directory
It will print the names of both files and directories in the HOME directory
It will print the full paths of files and directories in the HOME directory
It will print the names of files and directories in the HOME directory and all its subdirectories

Q. Given the code, what will be the output when the main method is executed?

package com.javainuse.ocp;
import java.io.*;
class Animal {
private String species;
private int age;
Copypublic Animal(String species, int age) {
    this.species = species;
    this.age = age;
}

public String getSpecies() {
    return species;
}

public int getAge() {
    return age;
}
}
class Pet extends Animal implements Serializable {
private String name;
Copypublic Pet(String species, int age, String name) {
    super(species, age);
    this.name = name;
}

public String getName() {
    return name;
}
}
public class Test {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
var pet = new Pet("Dog", 3, "Buddy");
try (var oos = new ObjectOutputStream(
new FileOutputStream("pet.ser"));
var ois = new ObjectInputStream(
new FileInputStream("pet.ser")))
{
oos.writeObject(pet);
Copy        var p = (Pet) ois.readObject();
        System.out.printf("%s, %d, %s", p.getSpecies(), 
                           p.getAge(), p.getName());
    }
}
}

What will be the output when the main method is executed?

Dog, 3, Buddy
null, 0, Buddy
Runtime Exception
Compilation Error

Q. Given the code, what will be the output when the main method is executed?

package com.javainuse.ocp;
import java.util.Set;
public class Test {
public static void main(String[] args) {
var colors =
Set.of("RED", "GREEN", "BLUE");
colors.add("YELLOW");
System.out.println(colors);
}
}

What will be the output when the main method is executed?

[RED, GREEN, BLUE, YELLOW]
[RED, GREEN, BLUE]
An exception is thrown at runtime
Compilation error
[RED, GREEN, BLUE, YELLOW] (order may vary)

Q. Given code:

package com.javainuse.ocp;
import java.util.Arrays;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Stream stream =
Arrays.asList(2, 3, 4, 5).stream();
Copy    /INSERT/
}
}

Which statement when inserted in place of /INSERT/ will print the product of all elements in the stream?

System.out.println(stream.reduce(1, (a, b) -> a * b));
System.out.println(stream.reduce(0, (a, b) -> a * b));
System.out.println(stream.reduce(1.0, (a, b) -> a * b));
System.out.println(stream.product());

Q. Given code:

package com.javainuse.ocp;
public class Test {
public static void main(String[] args) {
try {
process();
} catch(Exception e) {
System.out.println(e.getClass()
.getName()); //Line n1
}
}
Copyprivate static void process() {
    try {
        Exception e = 
                new Exception(); //Line n2
        throw e; //Line n3
    } catch(Exception e) {
        System.out.println("A");
        NullPointerException npe = 
                (NullPointerException)e; //Line n4
        System.out.println("B");
        throw npe;
    }
}
}

What will be the output when the main method is executed?

A
B
java.lang.Exception
A
java.lang.NullPointerException
A
java.lang.ClassCastException
A
B
java.lang.NullPointerException

Q. Given code:

package com.javainuse.ocp;
class Outer {
private String str1 = "Hello";
class Inner {
private String str2 = "World";
public void display() {
System.out.println(str1 + " " + str2);
}
}
Copypublic static void main(String[] args) {
    Outer outer = new Outer();
    Outer.Inner inner = outer.new Inner();
    inner.display();
}
}

What will be the output when the main method is executed?

Hello World
Compilation error
HelloWorld
Hello null

Q. Given code:

package com.javainuse.ocp;
public class Test {
public static void main(String[] args) {
// Code using lambda expressions
}
}

Which of the following aspects of Java programming are directly impacted by the introduction of lambda expressions?

Syntax
Performance
Functional interfaces
All of the above

Here's the converted format for the given question:

Q. Given code:

package com.javainuse.ocp;
public class Test {
private static class Nested {
private String message = "HELLO WORLD";
private void display() {
System.out.println(message);
}
}
Copypublic static void main(String[] args) {
    /INSERT/
}
}

Which of the following options can replace /INSERT/ such that on executing class Test, the output is: HELLO WORLD?

Test.Nested obj1 = new Test.Nested(); obj1.display();
Nested obj2 = new Nested(); obj2.display();
var obj3 = new Test.Nested(); obj3.display();
Test.Nested obj4 = new Test().new Nested(); obj4.display();

Q. Given code:

package com.javainuse.ocp;
import java.time.ZoneId;
public class Test {
public static void main(String[] args) {
var zoneId = ZoneId.of("Europe/Paris"); //Line 7
zoneId.systemDefault(); //Line 8
System.out.println(ZoneId.systemDefault());
}
}

Which of the following statements is correct about the code?

Line 8 causes compilation failure
Code compiles and executes successfully and prints Europe/Paris on to the console
Code compiles and executes successfully but may print a time zone other than Europe/Paris
Code compiles but throws a runtime exception

Q. Given code:

package com.javainuse.ocp;
public class Test {
public static void main(String[] args) {
int i1 = 65; //ASCII code of 'A' is 65
char c1 = (char)i1; //Line n1
System.out.println(c1); //Line n2
}
}

What will be the output when the main method is executed?

Line n1 causes compilation failure
Line n1 causes runtime error
65
A

Q. Given code:

package com.javainuse.ocp;
public class Test {
public static void main(String[] args) {
Integer[] arr = new Integer[3];
System.out.println(arr[0] + "-" + arr[1] + "-" + arr[2]);
}
}

What will be the output when the main method is executed?

0-0-0
null-null-null
An Exception is thrown at runtime

Q. Given code:

package com.javainuse.ocp;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import java.util.Locale;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class MagicTest {
public static void main(String[] args) throws IOException {
var locale = new Locale("en", "GB");
var bundle = ResourceBundle.getBundle("Potion", locale);
var formatter = new MessageFormat(bundle.getString("recipe"));
Copy    System.out.println(
        formatter.format(Files.readAllLines(
            Paths.get("C:", "potions", "Ingredients.txt")).toArray()
        )
    );
}
}
// Potion.properties (in CLASSPATH)
recipe=First add {1}, then stir in {0}.
// C:\potions\Ingredients.txt
NETTLE
WORMWOOD

What will be the output when the main method is executed?

First add WORMWOOD, then stir in NETTLE.
First add NETTLE, then stir in WORMWOOD.
First add {1}, then stir in {0}.
A MissingResourceException is thrown at runtime.

Q. Given code:

package com.javainuse.ocp;
import java.util.function.BiPredicate;
public class StringTest {
public static void main(String[] args) {
BiPredicate<String, String> startsWithPred = String::startsWith;
System.out.println(startsWithPred.test("Java", "J"));
System.out.println(startsWithPred.test("Python", "Java"));
}
}

What will be the output when the main method is executed?

true
false
false
true
true
true
Compilation error

Q. Given code:

package com.javainuse.ocp;
import java.util.stream.LongStream;
public class StreamTest {
public static void main(String[] args) {
System.out.println(LongStream.rangeClosed(100, 100).sum());
}
}

What will be the output when the main method is executed?

0
100
200
Runtime Exception

Q. Given code:

public class Star {
}

Which of the following can be used as a constructor for the class given above?

public void Star(double magnitude) {}
public Star() {}
public void Star() {}
None of the other options

Q. Given code:

package com.javainuse.ocp;
class CustomResource implements AutoCloseable {
@Override
public void close() throws RuntimeException {
System.out.println("Resource closed");
}
Copypublic void doWork() {
    System.out.println("Doing work");
}
}
public class ResourceTest {
public static void main(String[] args) {
try (CustomResource resource = new CustomResource()) {
resource.doWork();
}
}
}

What will be the output when the main method is executed?

Doing work
Resource closed
Doing work
Resource closed
Compilation error

Q. Given the code and the PRODUCT table structure, what will be the output when the main method is executed?

package com.javainuse.ocp;
import java.sql.*;
public class ProductTest {
public static void main(String[] args) throws Exception {
var url = "jdbc:mysql://localhost:3306/inventory";
var user = "admin";
var password = "adminpass";
var query = "SELECT ID, NAME, PRICE FROM PRODUCT ORDER BY ID";
try (var con = DriverManager.getConnection(url, user, password);
var stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
) {
var rs = stmt.executeQuery(query);
rs.last();
rs.moveToInsertRow();
rs.updateInt(1, 105);
rs.updateString(2, "NewProduct");
rs.updateDouble(3, 99.99);
rs.insertRow();
rs.beforeFirst();
rs.next();
System.out.println(rs.getInt(1));
}
}
}

What will be the output?

101
105
An exception is thrown by rs.insertRow();
An exception is thrown by rs.beforeFirst();

Q. Given the code, what will be the output when the main method is executed?

package com.javainuse.ocp;
public class IncrementTest {
public static void main(String[] args) {
int x = 5;
if(++x == x++) {
System.out.println("EQUAL " + x);
} else {
System.out.println("NOT EQUAL " + x);
}
}
}

What will be the output?

EQUAL 6
EQUAL 7
NOT EQUAL 6
NOT EQUAL 7

Q. Given the code, what will be the output when the main method is executed?

package com.javainuse.ocp;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
public class DateTest {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2024, Month.FEBRUARY, 15);
LocalDate date2 = LocalDate.of(2024, Month.MARCH, 1);
Copy    System.out.println(Period.between(date1, date2));
}
}

What will be the output?

P14D
P15D
P16D
P1M15D

Q. Given the code, what will be the result when the main method is executed?

package com.javainuse.ocp;
@FunctionalInterface
interface Greeter {
void greet();
}
public class LambdaTest {
public static void main(String[] args) {
Greeter obj = () -> System.out.println("Hello, World!");
}
}

What will be the result?

Hello, World!
Compilation error
Runtime exception
Program compiles and executes successfully but nothing is printed to the console

Q. Given the code, what will be the result when the main method is executed?

package com.javainuse.ocp;
public class MonthTest {
public static void main(String[] args) {
int month = 3;
String season = switch(month) {
case 12, 1, 2 : "WINTER";
case 3, 4, 5 : "SPRING";
case 6, 7, 8 : "SUMMER";
case 9, 10, 11 : "FALL";
default : "UNKNOWN";
};
System.out.println(season);
}
}

What will be the result?

SPRING
Compilation error
UNKNOWN
Runtime exception

Q. Given the code, which statements are correct? Choose 3 options.

package com.javainuse.ocp;
public class VariableTest {
int x = 5;
static int y = 10;
Copyprivate void modify1(int val) {
    x = val++; //Line n1
    y = ++val; //Line n2
}

private static void modify2(int val) {
    x = --val; //Line n3
    y = val--; //Line n4
}

public static void main(String[] args) {
    modify1(15); //Line n5
    modify2(20); //Line n6
    System.out.println(x + y); //Line n7
}
}

Which statements are correct? Choose 3 options.

Line n2 causes a compilation error
Line n3 causes a compilation error
Line n5 causes a compilation error
Line n7 causes a compilation error
The code compiles successfully
The code prints 30 on execution
Line n1 causes a compilation error
Line n4 causes a compilation error
Line n6 causes a compilation error
The code prints 25 on execution

Q. Given code:

package com.javainuse.ocp;
class Parent {
int value = 100;
CopyParent() {
    print();
}

void print() {
    System.out.println("Parent: " + value);
}
}
class Child extends Parent {
int value = 200;
CopyChild() {}

void print() {
    System.out.println("Child: " + value);
}
}
public class InheritanceTest {
public static void main(String[] args) {
Parent obj = new Child();
}
}

What will be the output when the main method is executed?

Parent: 100
Child: 200
Parent: 0
Child: 0
Compilation error
Runtime exception

Q. Given code:

package com.javainuse.ocp;
interface Printable {
default void print() {
System.out.println("Printable");
}
}
class Document {
public static void print() {
System.out.println("Document");
}
}
class Report extends Document implements Printable {}
public class PrintTest {
public static void main(String[] args) {
Report report = new Report();
report.print();
}
}

Which of the following statements is correct?

The code compiles successfully and prints "Printable"
The code compiles successfully and prints "Document"
There is a compilation error in the Printable interface
There is a compilation error in the Document class
There is a compilation error in the Report class

Q. Given code:

package com.javainuse.ocp;
module com.javainuse.app {
requires java.base;
requires java.sql;
exports com.javainuse.ocp;
}
public class ModuleTest {
public static void main(String[] args) {
System.out.println("Module test");
}
}

Which Java command option will list all modules in the module path and their dependencies?

--list-modules
--show-modules
--display-modules
--describe-modules

Q. Consider the following code in the Test.java file:

package com.javainuse.ocp;
import java.time.Duration;
public class Test {
public static void main(String[] args) {
Duration duration = Duration.ofSeconds(3661);
System.out.println(duration);
}
}

What will be the output?

PT3661S
PT1H1M1S
P0Y0M0DT1H1M1S
1:1:1

Q. Consider the following code in the Test.java file:

package com.javainuse.ocp;
abstract class Vehicle {
private String model;
CopyVehicle(String model) {
    this.model = model;
}

public String getModel() {
    return model;
}
}
class Car extends Vehicle {
private int year;
CopyCar(int year) {
    this.year = year;
}

Car(String model, int year) {
    super(model);
    this.year = year;
}

public int getYear() {
    return year;
}
}
public class Test {
public static void main(String[] args) {
Car car1 = new Car(2022);
Car car2 = new Car("Sedan", 2023);
System.out.println(car1.getModel() + ":"
+ car1.getYear() + ":"
+ car2.getModel() + ":"
+ car2.getYear());
}
}

What will be the result when compiling and running this code?

Compilation error for Vehicle(String) constructor
Compilation error for Car(int) constructor
Compilation error for Car(String, int) constructor
Compilation error for Test Class
null:2022:Sedan:2023

Q. Given the following code in the Test.java file:

package com.javainuse.ocp;
public class Test {
enum Colors {
RED("#FF0000"), GREEN("#00FF00"), BLUE("#0000FF")
Copy    private String hexCode;

    Colors(String hexCode) {
        this.hexCode = hexCode;
    }

    public String getHexCode() {
        return hexCode;
    }
}

public static void main(String[] args) {
    System.out.println(Test.Colors.RED.getHexCode());
}
}

What will be the result when compiling and running this code?

#FF0000
RED
Compilation error
Exception is thrown at runtime

Q. Given the following code:

package com.javainuse.ocp;
import java.util.Random;
import java.util.function.*;
public class Test {
public static void main(String[] args) {
/INSERT/ obj = Random::new; //Constructor reference for no-argument Random() constructor
Random random = obj.get(); //Creates an instance of Random class.
System.out.println(random.nextInt(100));
}
}

What should be inserted at /INSERT/ to make the code compile and run correctly?

Supplier
Supplier<Random>
Function<Object>
Supplier<Object>
Function<Random>
Function

Q. Consider the following code:

package com.javainuse.ocp;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) {
var time = LocalTime.of(14, 30, 15);
var str = time.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println("Time is: " + str);
}
}

What will be the result when running this code?

Time is: 14:30:15
Time is: 14:30:15+00:00
Given code executes successfully but output does not match with the given options
Runtime exception
Time is: 2:30:15 PM

Q. Consider the following code snippet:

interface Printable {
    void print();
}
/INSERT/ {
public void print() {} //Line n1
}

How many statements can replace /INSERT/ without causing a compilation error?

One statement
Two statements
Three statements
Four statements
Five statements

Q. Consider the following code fragment:

package com.javainuse.ocp;
abstract class Vehicle {
protected abstract int getMaxSpeed();
}
class Car extends Vehicle {
int getMaxSpeed() {
return 180;
}
}

Which modifications will allow the code to compile? (Choose all that apply)

Make the getMaxSpeed() method of Vehicle class private
Make the getMaxSpeed() method of Car class private
Make the getMaxSpeed() method of Car class protected
Make the getMaxSpeed() method of Vehicle class public
Make the getMaxSpeed() method of Car class public
Remove the protected access modifier from the getMaxSpeed() method of Vehicle class

Q. Given the following code:

package com.javainuse.ocp;
import java.io.*;
import java.util.Set;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
var stream = Stream.of(Set.of("A", "B"));
try (var oos = new ObjectOutputStream(new FileOutputStream("data.ser"));
var ois = new ObjectInputStream(new FileInputStream("data.ser")))
{
oos.writeObject(stream);
Copy        var object = (Stream<?>) ois.readObject();
        System.out.println(object.findFirst().get());
    }
}
}

What will be the result when running this code?

[A, B]
Runtime Exception
Compilation error
[B, A]

Q. Given the following code:

package com.javainuse.ocp;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
System.out.println(Stream.of("cat", "dog", "bird")
.sorted()
.findFirst()
.orElse("fish"));
}
}

Which statements are true about the output of this code? (Choose all that apply)

It will always print "bird" on to the console
It can print any string from the stream
It will never print "fish" on to the console
It will always print "cat" on to the console
It will always print "dog" on to the console