Oracle Java 17 1Z0-829 Certification Exam Practice Test 3
Q. Given code:
package com.javainuse.ocp; class NumberPrinter { private int maxNumber = 5; public class PyramidPrinter { public PyramidPrinter(int n) { if(n > 0 && n <= 10) maxNumber = n; } public void printPyramid() { for(int i = 1; i <= maxNumber; i++) { String line = " ".repeat(maxNumber - i); for(int j = 1; j <= i; j++) { line += j + " "; } System.out.println(line.trim()); } } } } public class Test { public static void main(String[] args) { //Insert statement here } }
Which statement when inserted in the main(String[] args) method will print a pyramid pattern of numbers from 1 to 5?
new NumberPrinter().PyramidPrinter(5).printPyramid();new NumberPrinter.PyramidPrinter(5).printPyramid();
new NumberPrinter().new PyramidPrinter(5).printPyramid();
NumberPrinter.PyramidPrinter(5).printPyramid();
Q. Your team has provided you with a modular jar for logging functionality. Given the file structure and module information, which javac command will successfully compile your module code?
Jar File name: logger.jar Module name: logger Class name: com.logging.util.Logger Method: public static void log(String message) {...} module-info.java contents: module logger { exports com.logging.util to appmodule; } File/Directory structure on your Windows platform is: C: +---src | \---appmodule | | module-info.java | | | \---com | \---myapp | \---main | App.java | +---bin \---lib logger.jar C:\src\appmodule\module-info.java: module appmodule { requires logger; } C:\src\appmodule\com\myapp\main\App.java: package com.myapp.main; import com.logging.util.Logger; public class App { public static void main(String[] args) { Logger.log("Application started"); } }
Which javac command will successfully compile your module code?
javac -d bin --module-source-path src -p lib\logger.jar -m appmodulejavac -d bin --module-source-path src,lib\logger.jar -m appmodule
javac -d bin --module-source-path src;lib\logger.jar -m appmodule
javac -d bin --module-source-path src --module-class-path lib\logger.jar -m appmodule
Q. Given code:
package com.javainuse.ocp; class Outer { Outer() { System.out.print("B"); } /INSERT 1/ class Inner { Inner() { System.out.print("D"); } /INSERT 2/ } } public class Test { public static void main(String[] args) { new Outer().new Inner(); } }
Which pair of insertions will result in the output "ABCD" when the Test class is executed?
Replace /INSERT 1/ with {System.out.print("A");} and /INSERT 2/ with {System.out.print("C");}Replace /INSERT 1/ with static {System.out.print("A");} and /INSERT 2/ with {System.out.print("C");}
Replace /INSERT 1/ with {System.out.print("A");} and /INSERT 2/ with static {System.out.print("C");}
Replace /INSERT 1/ with static {System.out.print("A");} and /INSERT 2/ with static {System.out.print("C");}
Q. Consider the following code in the Test.java file:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { boolean flag1 = 1 == 1; boolean flag2 = 2; System.out.println(flag1 + flag2); } }
What will be the result?
true2
Compilation error
Runtime exception
Q. Given the following code in the Test.java file:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { var b = 10; var y = 30; switch(y) { case 20 -> b += 5; case 30 -> b *= 2; case 40 -> b -= 5; } System.out.println(b); } }
What will be the output?
1015
20
25
5
Q. Given the following code:
package com.javainuse.ocp; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Test { public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { var es = Executors.newFixedThreadPool(2); var f1 = es.submit(() -> "Task 1"); var f2 = es.submit(() -> { Thread.sleep(100); return "Task 2"; }); var f3 = es.submit(() -> {}, "Task 3"); System.out.println(f1.get(1, TimeUnit.MINUTES)); System.out.println(f2.get(2, TimeUnit.MINUTES)); System.out.println(f3.get(3, TimeUnit.MINUTES)); es.shutdown(); } }
What will be the result of executing this code?
The code will take at least 6 minutes to executeThe code will take at least 3 minutes to execute
The code will take at least 1 minute to execute
The code may finish execution within a few seconds
The code will cause a TimeoutException
Q. Consider the following code in the Test.java file:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { String str = " "; //single space boolean b1 = str.isEmpty(); boolean b2 = str.isBlank(); System.out.println(b1 + " : " + b2); //Line n1 Copy str.strip(); //Line n2 b1 = str.isEmpty(); b2 = str.isBlank(); System.out.println(b1 + " : " + b2); //Line n3 } }
What will be the output?
true : falsetrue : false
false : true
false : true
false : true
true : true
true : true
true : true
false : false
false : false
Q. Given the following code in the Test.java file:
package com.javainuse.ocp; abstract class Animal { abstract void jump() throws RuntimeException; } class Deer extends Animal { void jump() { //Line n1 System.out.println("DEER JUMPS"); } Copyvoid jump(int i) { System.out.println("DEER JUMPS TO " + i + " FEET"); } } public class Test { public static void main(String[] args) { Animal animal = new Deer(); ((Deer)animal).jump(); //Line n2 ((Deer)animal).jump(5); //Line n3 } }
What will be the result?
Line n1 causes compilation errorLine n2 causes compilation error
Test class executes successfully and prints:
DEER JUMPS
DEER JUMPS TO 5 FEET
An exception is thrown at runtime
Line n3 causes compilation error
Q. Given the following code:
package com.javainuse.ocp; class Container<E implements Comparable> { private E element; Copypublic void setElement(E element) { this.element = element; } public E getElement() { return element; } } public class Test { public static void main(String[] args) { Container<String> container = new Container<>(); container.setElement("Hello World"); System.out.println(container.getElement()); } }
Which statement is true about the compilation and execution of the Test class?
The code compiles and runs successfully, printing "Hello World"The code fails to compile due to an error in the Container class declaration
The code fails to compile due to an error in the Test class
The code compiles but throws a runtime exception
Q. Given the following code:
package com.javainuse.ocp; import java.util.function.BinaryOperator; public class Test { public static void main(String[] args) { BinaryOperator<String> operator = String::concat; System.out.println(operator.apply("Hello ", "World")); } }
What will be the output when the Test class is executed?
Compilation errorHelloWorld
Runtime error
Hello World
Q. Given the following code:
package com.javainuse.ocp; import java.nio.file.*; public class Test { public static void main(String[] args) { var path = Paths.get("C:", "users", ".", "..", "documents", "file.txt").normalize(); System.out.println(path.getNameCount() + ":" + path.getName(1)); } }
What will be the output when the Test class is executed?
2:documents3:users
2:users
An exception is thrown at runtime
1:documents
Q. Given code:
package com.javainuse.ocp; interface Greeting { default void sayHello() { System.out.println("Hello from Greeting"); } Copystatic void printInfo() { printVersion(); printAuthor(); } private static void printAuthor() { System.out.println("Author: John Doe"); } private static void printVersion() { System.out.println("Version: 1.0"); } String toString(); } interface CustomGreeting extends Greeting { void greet(); } public class GreetingTest { public static void main(String[] args) { CustomGreeting customGreeting = () -> System.out.println("Custom greeting!"); customGreeting.greet(); customGreeting.sayHello(); } }
What will be the output when the main method is executed?
Compilation error in Greeting interfaceCompilation error in GreetingTest class
Runtime exception when executing GreetingTest
Custom greeting!
Hello from Greeting
Q. Given code:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { int x = 5; int y = ++x * x-- + x++ - --x; System.out.println("x = " + x); System.out.println("y = " + y); } }
What will be the output when the main method is executed?
x = 5, y = 36x = 6, y = 36
x = 5, y = 35
x = 6, y = 35
Q. Given code:
package com.javainuse.ocp; import java.util.*; public class Test { public static void main(String[] args) { Set<Integer> set = new TreeSet<>(Arrays.asList(10, null, 5, null, 15)); long count = set.stream().count(); System.out.println(count); } }
What will be the result when the main method is executed?
53
Runtime Exception
0
Q. Given code:
package com.javainuse.ocp; class Circle { private double radius; Copypublic Circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public double getArea() { return Math.PI * radius * radius; } } public class TestCircle { public static void main(String[] args) { protected double r = 5.0; final double PI = 3.14159; Circle circle = new Circle(r); System.out.println("Radius: " + circle.getRadius() + ", Area: " + circle.getArea()); } }
What will be the result when attempting to compile and run the TestCircle class?
Radius: 5.0, Area: 78.53975Compilation Error
Radius: 0.0, Area: 0.0
Runtime Exception
Q. Consider a module named 'core' with two packages: 'com.javainuse.service' and 'com.javainuse.service.impl'. Which of the following module descriptor files correctly exports both packages while only opening 'com.javainuse.service.impl' for reflection?
module core { exports com.javainuse.service, com.javainuse.service.impl; opens com.javainuse.service.impl; }
open module core { exports com.javainuse.service; exports com.javainuse.service.impl; }
module core { exports com.javainuse.service; exports com.javainuse.service.impl; open com.javainuse.service.impl; }
module core { exports, opens com.javainuse.service, com.javainuse.service.impl; }
module core { exports com.javainuse.service; exports com.javainuse.service.impl; opens com.javainuse.service.impl; }
Q. Which of the following statements is correct about the @FunctionalInterface annotation?
It is mandatory to use @FunctionalInterface for all interfaces with a single abstract method.The @FunctionalInterface annotation can be applied to classes and methods.
An interface marked with @FunctionalInterface can have multiple abstract methods.
The @FunctionalInterface annotation is used at runtime by the JVM to perform special optimizations.
The @FunctionalInterface annotation helps the compiler to verify that the interface has only one abstract method.
Q. Given code:
package com.javainuse.ocp; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add(30); Copy list.remove(Integer.valueOf(20)); System.out.println(list); } }
What will be the output when the main method is executed?
[10, 20, 30][10, 30]
[20, 30]
An exception is thrown at runtime
Compilation error
Q. Given code:
package com.javainuse.ocp; import java.util.*; record Employee(String name, double salary) { public String toString() { return "Employee (" + name + ", " + salary + ")"; } Copypublic static int compareBySalary(Employee e1, Employee e2) { return Double.compare(e2.salary, e1.salary); } } public class Test { public static void main(String[] args) { List<Employee> employees = Arrays.asList( new Employee("Alice", 50000), new Employee("Bob", 60000), new Employee("Charlie", 55000)); employees.sort(Employee::compareBySalary); System.out.println(employees); } }
What will be the output when the main method is executed?
[Employee (Alice, 50000.0), Employee (Charlie, 55000.0), Employee (Bob, 60000.0)][Employee (Bob, 60000.0), Employee (Charlie, 55000.0), Employee (Alice, 50000.0)]
Compilation error
An exception is thrown at runtime
Q. Will the following code compile successfully?
package com.javainuse.ocp; class Outer { enum Color { RED, GREEN, BLUE; Copy private void printColor() { System.out.println(this); } } }Yes
No
Q. Consider the following statements. How many of them will print Hello, World! exactly as shown (with a newline after 'Hello,')?
1. System.out.println(""" Hello, World! """); System.out.println(""" Hello, World! """); System.out.print("Hello, World!"); System.out.println(String.format("%s %s", "Hello,", "World!"));
Select the correct answer:
Only one statementOnly two statements
Only three statements
All four statements
None of the statements
Q. Given 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; import java.util.function.Function; public class Test { public static void main(String[] args) { Function<Integer, Integer> f = x -> x * 2; Function<Integer, Integer> g = y -> y + 3; Copy Function<Integer, Integer> fog = f.andThen(g); //Line n1 System.out.println(fog.apply(5)); } }
Select the correct option:
Function<Integer, Integer> fog = g.compose(f);Function<Integer, Integer> fog = f.compose(g);
Function<Integer, Integer> fog = g.andThen(f);
All of the above
None of the above
Q. Given the code below, what will be the output when the main method is executed?
package com.javainuse.ocp; import java.util.function.IntFunction; import java.util.function.IntUnaryOperator; import java.util.stream.Stream; public class Test { public static void main(String[] args) { int seed = 1; var stream = Stream.iterate(seed, i -> i <= 8, i -> i * 2); //Line n1 IntFunction<IntUnaryOperator> func = m -> n -> n + m; //Line n2 stream.mapToInt(i -> i).map(func.apply(3)).forEach(System.out::print); //Line n3 } }
Select the correct output:
45784811
1357
Compilation error
Runtime exception
Q. Given Question
Which of the following scenarios is best suited for using the CompletableFuture framework in Java?
Select the best option:
Tasks that involve heavy database transactions with multiple table updatesTasks that require sequential processing of large data sets
Tasks that involve long-running network operations that can be executed concurrently
Tasks that require frequent user interaction and input
Q. Given Question
Does the introduction of Java Records improve code conciseness and reduce boilerplate code? Select the correct answer:
NoYes
Q. Given code
package com.javainuse.ocp; import java.time.LocalDateTime; class Outer { private static class Inner { public static LocalDateTime getDateTime() { return LocalDateTime.now(); } } } public class Test { public static void main(String[] args) { System.out.println(Outer.Inner.getDateTime().getDayOfWeek()); } }
Which statement is correct about the output when the main method is executed?
Select the correct statement:
It will print the current day of the week (e.g., MONDAY, TUESDAY, etc.)Code fails to compile
It will print any int value between 1 and 7
Code compiles successfully but throws a Runtime exception
Q. Given code
package com.javainuse.ocp; import java.time.*; public class Test { public static void main(String[] args) { Duration d1 = Duration.ofHours(24); Duration d2 = Duration.ofMinutes(1440); System.out.println(d1.equals(d2) + ":" + d1); } }
What will be printed when the main method is executed?
Select the correct output:
true:PT24Hfalse:PT24H
true:P1D
false:P1D
Q. Given code
package com.javainuse.ocp; public class Test { public static void main(String[] args) { var temperature = 25; // Line n1 var status = "Normal"; // Line n2 if (0 < temperature <= 20) // Line n3 status = "Cold"; else if (20 < temperature <= 30) // Line n4 status = "Comfortable"; else if (temperature > 30) status = "Hot"; System.out.println(status); } }
What will be the output when the main method is executed?
Select the correct output:
NormalCold
Comfortable
Hot
Compilation error
Q. Given code
package com.javainuse.ocp; import java.util.*; public class Test { public static void main(String[] args) { var set = new TreeSet<String>(Set.of("JAVA", "IS", "AWESOME", "AND", "FUN")); //Line n1 set.add("PROGRAMMING"); //Line n2 set.removeIf(s -> s.length() <= 2); //Line n3 set.forEach(System.out::print); //Line n4 } }
What will be the output when the main method is executed?
Select the correct output:
AWESOMEFUNJAVAPROGRAMMINGFUNJAVAISAWESOMEPROGRAMMING
AWESOMEFUNJAVAPROGRAMMINGIS
Compilation error
Q. Given code
package com.javainuse.ocp; public class Test { public static void main(String[] args) { try { try { System.out.print("A-"); throw new IllegalArgumentException(); } catch (RuntimeException e) { System.out.print("B-"); throw new IllegalStateException(); } finally { System.out.print("C-"); } } catch (Exception e) { System.out.print("D-"); } finally { System.out.print("E"); } } }
What will be the output when the main method is executed without any command-line arguments?
Select the correct output:
A-B-C-D-EA-C-D-E
A-B-C-E
A-B-E
Q. Given code
package com.javainuse.ocp; import java.util.function.Function; import java.util.function.UnaryOperator; import java.util.stream.Stream; record Product(String name, double price) {} public class Test { public static void main(String[] args) { Function<Product, Double> extractor = prod -> prod.price(); UnaryOperator<Double> operator = d -> d * 1.1; double total = Stream.of(new Product("Laptop", 999.99), new Product("Phone", 599.99), new Product("Tablet", 399.99)) .map(extractor.andThen(operator)) .reduce(0.0, (a, b) -> a + b); System.out.println(Math.round(total)); } }
What will be the output when the main method is executed?
Select the correct output:
20002199
2200
2201
Q. Given the structure of the EMPLOYEE table:
EMPLOYEE (ID integer, NAME varchar(100), SALARY decimal(10,2), PRIMARY KEY (ID))
And the following code, which of the options can be used to replace /INSERT/ such that there is no compilation error?
package com.javainuse.ocp; import java.sql.*; public class Test { public static void main(String[] args) throws SQLException { var url = "jdbc:mysql://localhost:3306/company"; var user = "admin"; var password = "admin123"; Copy try (var con = DriverManager.getConnection(url, user, password); var stmt = /INSERT/) { } } }
Select all correct options:
con.createStatement("SELECT * FROM EMPLOYEE")con.prepareStatement("SELECT * FROM EMPLOYEE")
con.createStatement()
con.prepareStatement()
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
con.prepareStatement("SELECT * FROM EMPLOYEE", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
Q. Given code
package com.javainuse.ocp; import java.util.*; public class Test { public static void main(String[] args) { List<Integer> list = Arrays.asList(10, null, 20, 30, null); //Line n1 Set<Integer> set = new HashSet<>(list); //Line n2 System.out.println(set.size()); //Line n3 } }
What will be the output when the main method is executed?
Select the correct output:
34
5
NullPointerException is thrown at runtime
Q. Given the code, what will be the output when the main method is executed?
package com.javainuse.ocp; import java.util.*; public class Test { public static void main(String[] args) { List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); ListIterator<Integer> iter = list.listIterator(3); while(iter.hasNext()) { System.out.print(iter.next() + " "); } while(iter.hasPrevious()) { System.out.print(iter.previous() + " "); } } }
Select the correct output:
30 40 50 50 40 30 20 1040 50 50 40 30 20 10
30 40 50 50 40 30
40 50 50 40 30
Q. Given the code snippet:
var set = Set.of(1, 2, 3, 4, 5);
And the following statements:
1. set.forEach(System.out::print); 2. set.stream().forEach(System.out::print); 3. set.stream().sorted().forEach(System.out::print); 4. set.parallelStream().forEachOrdered(System.out::print); 5. System.out.println(set.stream().map(String::valueOf).collect(Collectors.joining()));
How many of the above statements will print the numbers in the order 1, 2, 3, 4, 5?
All five statementsOnly four statements
Only three statements
Only two statements
Only one statement
Q. Given the code:
import java.util.*; import java.util.stream.*; public class Test { /Insert-1/ public static void main(String[] args) { System.out.println(merge(Arrays.asList("A", "B"), Arrays.asList("C", "D"))); } Copy/Insert-2/ public static <T> List<T> merge(List<T>... lists) { return Arrays.stream(lists) .flatMap(List::stream) .collect(Collectors.toList()); } }
Which of the following options will suppress the compiler warning without causing compilation errors?
Replace /Insert-1/ with @SuppressWarningsReplace /Insert-1/ with @SuppressWarnings("unchecked", "rawtypes")
Replace /Insert-2/ with @SuppressWarnings(value="unchecked")
Replace /Insert-2/ with @SafeVarargs
Q. Which of the following are Functional Interfaces in Java?
Select all that apply:
java.util.Observerjava.util.function.Predicate
java.lang.Iterable
java.util.function.Function
java.lang.AutoCloseable
Q. Given that C: is accessible for reading/writing and the directory structure is as follows:
C: ââââProjects
What will be the result of executing the following code?
package com.javainuse.ocp; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Test { public static void main(String[] args) throws IOException { var path = Paths.get("C:\Projects\Java\NewProject"); Files.createDirectories(path); } }
Select the correct answer:
Directories 'Java' and 'NewProject' will be created under 'Projects'Only directory 'Java' will be created under 'Projects'
An exception is thrown at runtime
No directories will be created and no exception will be thrown
Q. Given code
package com.javainuse.ocp; import java.util.*; import java.util.function.Predicate; record Book(String title, int pages, double price) { public String toString() { return title; } } public class Test { public static void main(String[] args) { List<Book> library = new ArrayList<>(); library.add(new Book("Java Basics", 300, 29.99)); library.add(new Book("Advanced Java", 500, 49.99)); library.add(new Book("Java Cookbook", 400, 39.99)); library.add(new Book("Java Puzzles", 250, 24.99)); library.add(new Book("Java Reference", 800, 59.99)); Copy filterAndPrint(library, b -> b.pages() > 300 && b.price() < 50.0); } private static void filterAndPrint(List<Book> books, Predicate<Book> criteria) { for (Book book : books) { if (criteria.test(book)) { System.out.print(book + " "); } } } }
What will be the output when the main method is executed? Select the correct output:
Java Basics Advanced Java Java Cookbook Java Puzzles Java ReferenceAdvanced Java Java Cookbook
Java Basics Java Puzzles
Compilation error
Q. Given code
package com.javainuse.ocp; interface Factory<T, R> { R produce(T t); } class Product { Product() { System.out.println("Default"); } CopyProduct(int id) { System.out.println("ID: " + id); } } public class Test { public static void main(String[] args) { Factory<Integer, Product> obj = Product::new; } }
What will be the result when the main method is executed? Select the correct result:
DefaultID: 0
Compilation error
It executes fine but no output
Q. Can you create a macOS application bundle (.app) using jpackage on a Windows machine?
Select the correct answer:
YesNo
Q. Given the code, which statement is correct about the enum Season?
package com.javainuse.ocp; interface Weather { void getDescription(); } enum Season implements Weather { SPRING, SUMMER, AUTUMN, WINTER; Copypublic void getDescription() { System.out.println("This is " + this.name().toLowerCase()); } public static Season getDefaultSeason() { return SPRING; } } public class Test { public static void main(String[] args) { Season.SUMMER.getDescription(); } }
Select the correct statement:
The enum Season can extend another classThe enum Season can extend another enum
The enum Season implicitly extends java.util.Enum
The enum Season can implement interfaces
Q. Given code:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { int count = 0; for (int i = 0; i < 5) System.out.print(i + " "); i++; System.out.println("\nCount: " + count); } }
What will be the result when the main method is executed?
It will print: 0 1 2 3 4 Count: 0Compilation error
It will go into an infinite loop
It will print: 0 Count: 0
Q. Given code:
package com.javainuse.ocp; import java.util.Set; import java.util.List; public class Test { public static void main(String[] args) { List<String> list = List.of("RED", "GREEN", "BLUE", "GREEN", "YELLOW"); Set<String> set = Set.copyOf(list); System.out.println(set.size()); } }
What will be the result when the main method is executed?
54
Compilation error
NullPointerException is thrown at runtime
IllegalArgumentException is thrown at runtime