Oracle Java 17 1Z0-829 Certification Exam Practice Test 1
Q. Given code:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { int count = 5; if(count++ == ++count) { System.out.println("EQUAL " + count); } else { System.out.println("NOT EQUAL " + count); } } }
What will be the output?
EQUAL 6EQUAL 7
NOT EQUAL 6
NOT EQUAL 7
Q. Given code:
package com.javainuse.ocp; import java.io.*; class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } class Employee extends Person implements Serializable { private String department; public Employee(String name, int age, String department) { super(name, age); this.department = department; } public String getDepartment() { return department; } } public class Test { public static void main(String[] args) throws IOException, ClassNotFoundException { var emp = new Employee("John", 30, "IT"); try (var oos = new ObjectOutputStream( new FileOutputStream("employee.ser")); var ois = new ObjectInputStream( new FileInputStream("employee.ser"))) { oos.writeObject(emp); var e = (Employee) ois.readObject(); System.out.printf("%s, %d, %s", e.getName(), e.getAge(), e.getDepartment()); } } }
What will be the output?
John, 30, ITnull, 0, IT
Runtime Exception
Compilation Error
Q. Given code:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { int count = 5; if(count++ == ++count) { System.out.println("EQUAL " + count); } else { System.out.println("NOT EQUAL " + count); } } }
What will be the output?
EQUAL 6EQUAL 7
NOT EQUAL 6
NOT EQUAL 7
Q. Given code:
package com.javainuse.ocp; abstract class Employee { protected abstract double calculateSalary(); } class Manager extends Employee { public double calculateSalary() { return 5000.0; } } public class Test { public static void main(String[] args) { Employee emp = new Manager(); System.out.println(emp.calculateSalary()); } }
What will be the output?
Compilation ErrorRuntime Error
5000.0
0.0
Q. Given code:
package com.javainuse.ocp; abstract class Employee { abstract void work() throws RuntimeException; } class Developer extends Employee { void work() { //Line n1 System.out.println("DEVELOPER CODES"); } void work(String project) { System.out.println("DEVELOPER CODES ON " + project); } } public class Test { public static void main(String[] args) { Employee employee = new Developer(); ((Developer)employee).work(); //Line n2 ((Developer)employee).work("AI PROJECT"); //Line n3 } }
What will be the output?
Compilation ErrorRuntime Exception
DEVELOPER CODES
DEVELOPER CODES ON AI PROJECT
DEVELOPER CODES
Q. Given code:
package com.javainuse.ocp; class Employee<T implements Comparable> {} public class Test { public static void main(String[] args) { Employee<Integer[]> employee = new Employee<>(); System.out.println(employee); } }
What will be the output?
Compilation ErrorRuntime Exception
An object reference
null
Q. Given code:
package com.javainuse.ocp; import java.io.*; public class Test { public static void main(String[] args) { try(var reader = new BufferedReader(new FileReader("data.txt"))) { reader.close(); reader.readLine(); } catch(IOException e) { System.out.println("IOException"); } } }
What will be the output?
No outputCompilation error
IOException
Runtime error
Q. Given code and the structure of the EMPLOYEE table:
package com.javainuse.ocp; import java.sql.*; import java.util.Properties; public class Test { public static void main(String[] args) throws Exception { var url = "jdbc:mysql://localhost:3306/company"; var prop = new Properties(); prop.put("user", "admin"); prop.put("password", "adminpass"); var query = "SELECT AVG(salary) FROM EMPLOYEE"; try (var con = DriverManager.getConnection(url, prop); var stmt = con.createStatement(); var rs = stmt.executeQuery(query);) { System.out.println(rs.getDouble(1)); } } } // EMPLOYEE table structure: // EMPLOYEE (ID integer, NAME varchar(100), SALARY double, PRIMARY KEY (ID)) // Assume: // - URL is correct and db credentials are: admin/adminpass. // - SQL query is correct and valid. // - The JDBC 4.2 driver jar is configured in the classpath. // - EMPLOYEE table doesn't have any records.
What will be the output?
0.0An exception is thrown at runtime
null
Compilation error
Q. Given code:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { // Statement 1 System.out.println("Hello,\nWorld!"); // Statement 2 System.out.println("""Hello,\nWorld!"""); // Statement 3 System.out.println(""" Hello,\ World!\ """); // Statement 4 System.out.println(""" Hello,\nWorld!"""); } }
Which of the following statements is correct?
Only three statements compile successfullyAll four statements compile successfully
Only one statement compiles successfully
Only two statements compile successfully
Q. Given code snippet:
package com.javainuse.ocp; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { var list = List.of("J", "A", "V", "A"); // Statement 1 list.forEach(System.out::print); // Statement 2 list.stream().forEach(System.out::print); // Statement 3 list.stream().map(Function.identity()).forEach(System.out::print); // Statement 4 list.parallelStream().forEachOrdered(System.out::print); // Statement 5 System.out.println(list.stream().collect(Collectors.joining())); } }
How many of these statements will print JAVA on to the console?
Only one statementOnly two statements
Only three statements
Only four statements
All five statements
Q. Given code and the structure of the EMPLOYEES table:
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 = "adminpass"; var query = "UPDATE EMPLOYEES SET salary = salary * 1.1"; try (var con = new Connection(url, user, password); var stmt = con.createStatement()) { System.out.println(stmt.executeUpdate(query)); } } } // EMPLOYEES table structure: // EMPLOYEES (id INT, name VARCHAR(100), salary DOUBLE) // EMPLOYEES table contains 5 records. // Assume: // - URL is correct and db credentials are: admin/adminpass. // - SQL query is correct and valid. // - The JDBC 4.2 driver jar is configured in the classpath.
What will be the result?
50
An exception is thrown at runtime
Compilation error
Q. Given code:
package com.javainuse.ocp; import java.util.stream.Collectors; import java.util.stream.Stream; public class Test { public static void main(String[] args) { String str = Stream.of("apple", "banana", "cherry", "date", "elderberry") .dropWhile(s -< s.length() < 6) .collect(Collectors.joining(", ")); System.out.println(str); } }
What will be the output?
banana, cherry, date, elderberrycherry, date, elderberry
apple, banana, cherry, date, elderberry
elderberry
Q. Given code:
package com.javainuse.ocp; import java.io.*; public class Test { public static void main(String[] args) throws IOException { var file = new File("C:\\temp\\file1.txt"); var fileWriter = new FileWriter("C:\\temp\\subdir\\file2.txt"); var printWriter = new PrintWriter("C:\\temp\\file3.txt"); } }
How many physical files will be created on the disc?
30
2
1
Q. Given code:
package com.javainuse.ocp; interface Calculable { double PI = 3.14159; // Line n1 } public class Test { public static void main(String[] args) { Calculable[] arr = new Calculable[3]; // Line n2 for(Calculable calc : arr) { System.out.print(calc.PI + " "); // Line n3 } } }
What will be the output?
3.14159 3.14159 3.14159NullPointerException
Compilation error
No output
Q. Given code:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { String vehicle = new String(new char[] {'C', 'a', 'r'}); switch (vehicle) { default: System.out.println("BIKE"); case "Truck": System.out.println("TRUCK"); case "Car": System.out.println("CAR"); case "Bus": System.out.println("BUS"); break; } } }
What will be the output?
CARBUS
BIKE
TRUCK
CAR
BUS
BIKE
CAR
Q. Given code:
package com.javainuse.ocp; import java.io.*; public class Test { public static void main(String[] args) throws IOException { String secretCode = "hceolndceeapltaein"; try (var reader = new StringReader(secretCode)) { while (reader.ready()) { reader.skip(2); System.out.print((char) reader.read()); } } } }
What will be the output?
helicopterdecode
concealed
None of the above
Q. Given code:
package com.javainuse.ocp; public class Test { public static void main(String[] args) { /*INSERT*/ arr[1] = 5; arr[2] = 10; System.out.println("[" + arr[1] + ", " + arr[2] + "]"); } }
Which statements can replace /*INSERT*/ to print [5, 10] on the console?
Only one optionOnly two options
Only three options
Only four options
More than four options
None of the given options
Q. Given code:
package com.javainuse.ocp; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReference; import java.util.Optional; public class Test { public static void main(String[] args) { ModuleFinder finder = ModuleFinder.ofSystem(); Optional<ModuleReference> moduleRef = finder.find("java.base"); if (moduleRef.isPresent()) { ModuleDescriptor descriptor = moduleRef.get().descriptor(); System.out.println("Module name: " + descriptor.name()); System.out.println("Exports: " + descriptor.exports()); System.out.println("Requires: " + descriptor.requires()); } } }
What type of module is java.base?
aggregatorstandard
non-standard
unnamed
Q. Given code:
package com.javainuse.ocp; import java.util.Arrays; import java.util.concurrent.*; public class Test { public static void main(String[] args) throws InterruptedException { Callable<Integer> c = new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(2000); return Thread.currentThread().getName().length(); } }; var es = Executors.newFixedThreadPool(5); var list = Arrays.asList(c, c, c); var futures = es.invokeAll(list); int sum = 0; for(Future<Integer> future : futures) { try { sum += future.get(); } catch(ExecutionException e) {} } System.out.println(sum); es.shutdown(); } }
What will be the output?
The program will print a number less than 45 in approximately 2 secondsThe program will print a number greater than or equal to 45 in approximately 2 seconds
The program will print a number less than 45 in approximately 6 seconds
The program will print a number greater than or equal to 45 in approximately 6 seconds
Q. Given code:
package com.javainuse.ocp; import java.util.Arrays; import java.util.concurrent.*; public class Test { public static void main(String[] args) throws InterruptedException { Callable<String> c = new Callable<String>() { @Override public String call() throws Exception { try { Thread.sleep(3000); } catch (InterruptedException e) { } return "HELLO"; } }; var es = Executors.newFixedThreadPool(10); var list = Arrays.asList(c, c, c, c, c); var futures = es.invokeAll(list); System.out.println(futures.size()); es.shutdown(); } }
What is the output of the given code?
105 in less than 3 seconds
5 in more than or equal to 3 seconds
An exception will be thrown
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.concurrent.*; class Task implements <String> { private String input; public Task(String input) { this.input = input; } public String call() throws Exception { return input.toLowerCase(); } } public class Test { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService es = Executors.newFixedThreadPool(1); Future<String> future = es.submit(new Task("HELLO")); System.out.println(future.get()); es.shutdown(); } }
Which of the following options correctly describes the output of this program?
The program prints:HELLO
The program prints:
hello
The program throws an ExecutionException
The program doesn't terminate and prints nothing
Q. Given the code, which of the following correctly defines the record class Employee with validation for salary and hireDate?
package com.javainuse.ocp; import java.time.LocalDate; // Record class definition goes here
Which of the following options correctly defines the Employee record with proper validation?
record Employee(double salary, LocalDate hireDate) {}
record Employee(double salary, LocalDate hireDate) { Employee { if (salary < 30000 || salary > 150000) { throw new IllegalArgumentException("Invalid salary"); } if (hireDate.isBefore(LocalDate.of(2020, 1, 1)) || hireDate.isAfter(LocalDate.now())) { throw new IllegalArgumentException("Invalid hire date"); } } }
record Employee(double salary, LocalDate hireDate) { Employee(double salary, LocalDate hireDate) { if (salary < 30000 || salary > 150000) { throw new IllegalArgumentException("Invalid salary"); } if (hireDate.isBefore(LocalDate.of(2020, 1, 1)) || hireDate.isAfter(LocalDate.now())) { throw new IllegalArgumentException("Invalid hire date"); } this.salary = salary; this.hireDate = hireDate; } }
record Employee(double salary, LocalDate hireDate) { Employee(double salary, LocalDate hireDate) { if (salary < 30000 || salary > 150000) { throw new IllegalArgumentException("Invalid salary"); } if (hireDate.isBefore(LocalDate.of(2020, 1, 1)) || hireDate.isAfter(LocalDate.now())) { throw new IllegalArgumentException("Invalid hire date"); } } }
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.sql.*; public class Test { public static void main(String[] args) throws Exception { var url = "jdbc:mysql://localhost:3306/testdb"; var user = "root"; var password = "password"; var query = "UPDATE PRODUCT SET PRICE = ? WHERE ID = ?"; try (var con = DriverManager.getConnection(url, user, password); var ps = con.prepareStatement(query); ) { ps.setDouble(1, 199.99); ps.setInt(2, 1001); int rowsAffected = ps.executeUpdate(); System.out.println(rowsAffected); } } }
What will be the output of this program?
01
Compilation error
Runtime exception
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; enum Size { SMALL, MEDIUM, LARGE } record Product(String name, double price, Size size) {} record Summary(Map<Size, List<Product>> bySize, Map<String, List<Product>> byName) {} public class Test { public static void main(String[] args) { var products = Stream.of( new Product("A", 10.0, Size.SMALL), new Product("B", 20.0, Size.MEDIUM), new Product("A", 15.0, Size.MEDIUM), new Product("C", 30.0, Size.LARGE), new Product("B", 25.0, Size.SMALL) ); var result = products.collect( Collectors.teeing( Collectors.groupingBy(Product::size), Collectors.groupingBy(Product::name), Summary::new ) ); System.out.println(result.bySize().size() + result.byName().size()); } }
What will be the output of this program?
35
6
8
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); for(Integer num : numbers) { if(num % 20 == 0) { numbers.remove(num); } } System.out.println(numbers); } }
What will be the output of this program?
[10, 30][10, 30, 40]
Compilation error
An exception is thrown at runtime
Q. Given the code, what will be the output?
package com.javainuse.ocp; class FileHandler implements AutoCloseable { private String name; public FileHandler(String name) { this.name = name; } @Override public void close() { System.out.println("Closing " + name); } } public class Test { public static void main(String[] args) { try (FileHandler f1 = new FileHandler("Log"); FileHandler f2 = new FileHandler("Config")) { System.out.println("Processing files"); } } }
What will be the output of this program?
Processing filesClosing Log
Closing Config
Processing files
Closing Config
Closing Log
Compilation Error
Runtime Exception
Q. Which of the following statements successfully create a DateTimeFormatter instance?
package com.javainuse.ocp; import java.time.format.DateTimeFormatter; public class Test { public static void main(String[] args) { // Statements to be evaluated // ... } }
Select all correct statements:
DateTimeFormatter dtf1 = new DateTimeFormatter();DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter dtf3 = DateTimeFormatter.ISO_LOCAL_DATE;
DateTimeFormatter dtf4 = new DateTimeFormatter("yyyy-MM-dd");
DateTimeFormatter dtf5 = DateTimeFormatter.ofPattern("");
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.Arrays; public class Test { public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {1, 2, 3, 6, 5}; System.out.println(Arrays.________(arr1, arr2)); } }
Which statement correctly describes the output?
Only compare() will print 3Only mismatch() will print 3
Both compare() and mismatch() will print 3
Neither compare() nor mismatch() will print 3
Q. Given the code, what will be the output?
package com.javainuse.ocp; public class Test { public static void main(String[] args) { int count = 0; String result = null; for(int[] arr = {1, 2, 3, 4};; result = String.join("-", String.valueOf(arr[0]), String.valueOf(arr[arr.length-1]))) { if(count++ == 0) continue; else break; } System.out.println(result); } }
What will be the output of this program?
1-4null
Compilation error
Runtime exception
Q. Given the code, what will be the output?
package com.javainuse.ocp; public class Test { public static void main(String[] args) { record Temperature(double celsius) { public Temperature { if (celsius < -273.15) { throw new IllegalArgumentException("Temperature below absolute zero"); } } public double fahrenheit() { return celsius * 9/5 + 32; } } var t1 = new Temperature(100); var t2 = new Temperature(0); System.out.println(new Temperature((t1.celsius() + t2.celsius())/2).fahrenheit()); } }
What will be the output of this program?
68.050.0
An exception is thrown at runtime
Compilation error
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.nio.file.Path; import java.nio.file.Paths; public class Test { public static void main(String[] args) { Path path = Paths.get("/home/user/documents/file.txt"); System.out.println(path.getParent().getParent().getFileName()); } }
What will be the output of this program?
"/home/user""user"
"documents"
NullPointerException is thrown at runtime
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.io.IOException; class Animal { Animal() throws IOException { System.out.print("Wild"); } } class Lion extends Animal { Lion() throws Exception { System.out.print("Roar"); } } public class Test { public static void main(String[] args) throws Exception { new Lion(); } }
What will be the output of this program?
WildRoarRoarWild
Compilation error in Lion class
Compilation error in Animal class
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { List<String> colors = new ArrayList<>(); colors.add("red"); colors.add("blue"); colors.add("green"); colors.add("yellow"); colors.add("purple"); colors.add("green"); if(colors.remove("green")) colors.remove("black"); System.out.println(colors); } }
What will be the output of this program?
[red, blue, yellow, purple, green][red, blue, green, yellow, purple, green]
[red, blue, yellow, purple]
An exception is thrown at runtime
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Test { public static void main(String [] args) { List<String> cities = Arrays.asList("London", "paris", "Tokyo"); Collections.sort(cities, new Comparator<String>() { public int compare(String o1, String o2) { return o2.compareToIgnoreCase(o1); } }); System.out.println(cities); } }
What will be the output of this program?
[London, paris, Tokyo][paris, London, Tokyo]
[Tokyo, paris, London]
[LONDON, PARIS, TOKYO]
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class Test { public static void main(String [] args) { LocalDateTime dt1 = LocalDateTime.parse("2024-03-15T10:15:30"); System.out.println(dt1.plus(3, ChronoUnit.DAYS) .equals(dt1.plusDays(3))); } }
What will be the output of this program?
truefalse
Runtime Exception
Compilation Error
Q. Given the code, what will be the output?
package com.javainuse.ocp; interface Priceable { double getPrice(); default String currency() { return "USD"; } } class Book implements Priceable { public double getPrice() { return 29.99; } public String currency() { return "EUR"; } } public class Test { public static void main(String[] args) { Priceable obj = new Book(); System.out.println(obj.currency() + obj.getPrice()); } }
Which of the following options correctly represents the output?
USD29.99EUR29.99
USD29.990000
EUR29.990000
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.nio.file.Paths; public class Test { public static void main(String[] args) { var path = Paths.get("C:\\Users\\.\\Documents\\..\\Desktop\\file.txt"); System.out.println(path.toAbsolutePath()); } }
Which of the following options correctly represents the output?
C:\Users\Documents\file.txtC:\Users\Desktop\file.txt
C:\Users\.\Documents\..\Desktop\file.txt
NoSuchFileException is thrown at runtime
Q. Given the code, what will be the output?
package com.javainuse.ocp; public class Test { public static void main(String[] args) { final var str = "*"; System.out.println(str.repeat(3).equals("***")); } }
Which of the following options correctly represents the output?
truefalse
***
Runtime Exception
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.sql.*; public class Test { public static void main(String[] args) { try { var con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user", "pass"); var query = "SELECT * FROM PRODUCT"; var stmt = con.createStatement(); var rs = stmt.executeQuery(query); while (rs.next()) { System.out.println("ID: " + rs.getInt("PROD_ID")); System.out.println("Name: " + rs.getString("PRODUCT_NAME")); System.out.println("Price: " + rs.getDouble("PRICE")); } rs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.out.println("Database Error Occurred"); } } }
Which of the following options correctly represents the output?
Database Error OccurredCompilation Error
Code executes successfully without any output
NullPointerException is thrown at runtime
Q. Given the code, what will be the output?
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 src = Paths.get("C:\\Data\\Config\\settings.txt"); var tgt = Paths.get("C:\\Data"); Files.copy(src, tgt); } }
Which of the following options correctly represents the output?
Program terminates successfully without copying 'settings.txt' filejava.nio.file.FileAlreadyExistsException is thrown at runtime
'settings.txt' will be copied successfully to 'C:\Data\' directory
java.io.FileNotFoundException is thrown at runtime
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.nio.file.Path; import java.nio.file.Paths; public class Test { public static void main(String[] args) { var path1 = Paths.get("C:\\Users\\Documents"); var path2 = Paths.get("C:\\Users\\Documents\\Report.pdf"); System.out.println(path1.resolve(path2).equals(path1.resolveSibling(path2))); } }
Which of the following options correctly represents the output?
truefalse
Compilation error
Runtime exception
Q. Given the code, what will be the output?
package com.javainuse.ocp; class Parent { Parent() { this("Hello"); System.out.println("A"); } Parent(String s) { System.out.println("B"); } } class Child extends Parent { Child() { System.out.println("C"); } } public class Test { public static void main(String[] args) { new Child(); } }
Which of the following options correctly represents the output?
A B CB A C
C B A
B A
Q. Given the code, what will be the output?
package com.javainuse.ocp; public class Test { public static void main(String[] args) { for(var i = 0; i < 3; i++) { System.out.print(i + " "); } System.out.println(i); } }
Which of the following options correctly represents the output?
0 1 2 30 1 2 Compilation error
Compilation error
0 1 2 2
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.sql.*; public class Test { public static void main(String[] args) throws SQLException { var url = "jdbc:mysql://localhost:3306/testdb"; var user = "root"; var password = "password"; try (var con = DriverManager.getConnection(url, user, password); var stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ) { con.setAutoCommit(false); stmt.executeUpdate("INSERT INTO ORDERS VALUES(101, 'Laptop')"); var sp101 = con.setSavepoint("101"); stmt.executeUpdate("INSERT INTO ORDERS VALUES(102, 'Mouse')"); var sp102 = con.setSavepoint("102"); con.rollback(sp101); stmt.executeUpdate("INSERT INTO ORDERS VALUES(103, 'Keyboard')"); con.commit(); } } }
Which of the following options correctly represents the output?
Records with IDs 101, 102, and 103 are added to the ORDERS tableOnly records with IDs 101 and 103 are added to the ORDERS table
Only record with ID 103 is added to the ORDERS table
No records are added to the ORDERS table
Q. Given the code and file structure below, what will be the output?
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 src = Paths.get("C:", "TEMP", "config"); var tgt = Paths.get("C:", "TEMP", "Settings", "backup"); Files.copy(src, tgt); System.out.println(Files.isSymbolicLink(src) + ":" + Files.isSymbolicLink(tgt)); } }
File structure:
C:\TEMP\ â config â ââââSettings Configuration.properties
Here, 'config' is a symbolic link to 'C:\TEMP\Settings\Configuration.properties'.
Which of the following options correctly represents the output?
false:falsetrue:true
true:false
false:true
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.stream.Stream; public class Test { public static void main(String[] args) { Stream.of() .map(s -> s.toLowerCase()) .forEach(System.out::println); } }
Which of the following options correctly describes the output?
Program executes successfully but nothing is printed on to the consoleRuntimeException is thrown
NullPointerException is thrown at runtime
Compilation error
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.function.*; record Rectangle(int width, int height) { public boolean equals(Object obj) { if(obj != null && obj instanceof Rectangle) { return this.width == ((Rectangle)obj).height; } return false; } } public class Test { public static void main(String[] args) { Predicate<Rectangle> predicate = Predicate.isEqual(new Rectangle(5, 3)); System.out.println(predicate.test(new Rectangle(/INSERT/))); } }
Which of the following options can replace /INSERT/ to make the output true?
5, 33, 5
5, 5
3, 3
Q. Given the code, which of the following options can replace /INSERT/ such that there are no compilation errors? Choose 2 options.
package com.javainuse.ocp; interface Drawable { void draw(); } public class Test { public static void main(String[] args) { /INSERT/ } }
Select two correct options:
Drawable drawable = new Drawable();Drawable drawable = new Drawable() { public void draw() { System.out.println("Drawing"); } };
var drawable = new Drawable() { public void draw() { System.out.println("Drawing"); } public void erase() { System.out.println("Erasing"); } }; drawable.draw(); drawable.erase();
Drawable drawable = () -> System.out.println("Drawing");
Q. Given the code, what will be the output?
package com.javainuse.ocp; import java.util.List; public class Test { public static void main(String[] args) { var s1 = List.of(1, 2, 3, 4, 5).stream() .reduce(0, Integer::sum); var s2 = List.of(1, 2, 3, 4, 5).parallelStream() .reduce(0, Integer::sum); System.out.println(s1.equals(s2)); } }
What will be the output of this code?
It will always print trueIt will always print false
Output cannot be predicted
Compilation error
Q. Given the code, which of the following options, if used to replace /INSERT/, will compile successfully and on execution will print true on to the console? Choose 2 options.
package com.javainuse.ocp; public class Test { public static void main(String[] args) { String s1 = "Java"; String s2 = "java"; System.out.println(/INSERT/); } }
Select two correct options:
s1.equals(s2)s1.equalsIgnoreCase(s2)
s1.compareTo(s2) == 0
s1.compareToIgnoreCase(s2) == 0
s1.length() == s2.length()
s1 == s2.toUpperCase()
Q. Given the code, which statement when inserted in the main(String []) method will print JAVA IS AWESOME (all characters in upper-case) in the output?
package com.javainuse.ocp; class Outer { private String message = "JAVA IS AWESOME"; public class Inner { public Inner(String s) { if(s != null && !s.isEmpty()) message = s; } public void display() { System.out.println(message); } } } public class Test { public static void main(String[] args) { //Insert statement here } }
Which statement should be inserted in the main method?
new Outer().new Inner().display();new Outer.Inner("").display();
new Outer().new Inner(null).display();
new Outer().new Inner("Java is awesome").display();