0% found this document useful (0 votes)
2K views

Java8 Professional Udamy Practice Test 1

The summary provides the high level information about the practice test results in 3 sentences: This document contains the results of Practice Test 1 which included 9 multiple choice questions covering all knowledge areas. The test taker skipped answering questions 1 through 6 and provided explanations for the answers to questions 7 through 9. Overall the test taker answered 3 out of the 9 questions on the practice test.

Uploaded by

ANISH
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Java8 Professional Udamy Practice Test 1

The summary provides the high level information about the practice test results in 3 sentences: This document contains the results of Practice Test 1 which included 9 multiple choice questions covering all knowledge areas. The test taker skipped answering questions 1 through 6 and provided explanations for the answers to questions 7 through 9. Overall the test taker answered 3 out of the 9 questions on the practice test.

Uploaded by

ANISH
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 575

Practice Test 1 - Results

 Return to review

Attempt 1
All knowledge areas
All questions
Question 1: Skipped
What will be the result of compiling and executing class M?
1. package com.udayan.ocp;
2.  
3. class M {
4. private int num1 = 100;
5. class N {
6. private int num2 = 200;
7. }
8.
9. public static void main(String[] args) {
10. M outer = new M();
11. M.N inner = outer.new N();
12. System.out.println(outer.num1 + inner.num2);
13. }
14. }


100


200


300
(Correct)


Compilation error

Explanation
Outer class (M) code has access to all the members of inner class (N) including
private members, hence inner.num2 doesn't cause any compilation error.
Question 2: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class Printer<String> {
4. private String t;
5. Printer(String t){
6. this.t = t;
7. }
8. }
9.  
10. public class Test {
11. public static void main(String[] args) {
12. Printer<Integer> obj = new Printer<>(100);
13. System.out.println(obj);
14. }
15. }

What will be the result of compiling and executing Test class?



100


Compilation error in Printer class


Some text containing @ symbol
(Correct)


Compilation error in Test class

Explanation
Type parameter should not be a Java keyword & a valid Java identifier. Naming
convention for Type parameter is to use uppercase single character. 

In class Printer<String>, 'String' is a valid Java identifier and hence a valid type
parameter even though it doesn't follow the naming convention of uppercase single
character. 

Printer<Integer> obj = new Printer<>(100); => Type argument is Integer and it


correctly creates an instance of Printer class passing Integer object 100. 

Printer class doesn't override toString() method and hence 'System.out.println(obj);'


prints some text containing @ symbol. 

Question 3: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. try { //outer
6. try { //inner
7. System.out.println(1/0);
8. } catch(ArithmeticException e) {
9. System.out.println("Inner");
10. } finally {
11. System.out.println("Finally 1");
12. }
13. } catch(ArithmeticException e) {
14. System.out.println("Outer");
15. } finally {
16. System.out.println("Finally 2");
17. }
18. }
19. }

What will be the result of compiling and executing Test class?



Inner
Finally 2


Inner
Finally 1


Inner
Finally 1
Finally 2
(Correct)


Outer
Finally 2

Explanation
System.out.println(1/0); throws ArithmeticException, handler is available in inner
catch block, it executes and prints "Inner" to the console.

Once we handled the exception, no other catch block will get executed unless we re-
throw the exception.

Inner finally gets executed and prints "Finally 1" to the console.

Rule is finally block always gets executed, so outer finally gets executed and prints
"Finally 2" to the console. 

Question 4: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date = LocalDate.ofEpochDay(0);
8. System.out.println(date);
9. }
10. }

What will be the result of compiling and executing Test class?



1970-1-1


1970-01-01
(Correct)


Runtime Exception


1970-00-01

Explanation
0th day in epoch is: 1970-01-01, 1st day in epoch is: 1970-01-02 and so on.

as toString() method of LocalDate class prints the LocalDate object in ISO-8601


format: "uuuu-MM-dd". Hence output is: '1970-01-01'.

Question 5: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Set;
4. import java.util.stream.Collectors;
5. import java.util.stream.Stream;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Stream<String> stream = Stream.of("java", "python", "c",
10. "c++", "java", "python");
11. Set<String> set = stream.collect(Collectors.toSet());
12. System.out.println(set.size());
13. }
14. }

What will be the result of compiling and executing Test class?



0

6


4
(Correct)


5

Explanation
Set doesn't allow duplicates, which means generated set will have 4 elements ["java",
"python", "c", "c++] and therefore set.size() will return 4.
Question 6: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream<Integer> stream = Stream.iterate(1, i -> i + 1);
8. System.out.println(stream.anyMatch(i -> i > 1));
9. }
10. }

What will be the result of compiling and executing Test class?



true is printed on to the console and code runs infinitely


Nothing is printed on to the console as code runs infinitely


true
(Correct)


false

Explanation
stream => {1, 2, 3, 4, 5, ... }. It is an infinite stream.

Predicate 'i -> i > 1' returns true for any Integer greater than 1.

As 2 > 1, so true is printed and operation is terminated. Code doesn't run infinitely.
NOTE: 'stream.allMatch(i -> i > 1)' returns false as 1st element of the stream (1)
returns false for the predicate and 'stream.noneMatch(i -> i > 1)' returns false as 2nd
element of the stream (2) returns true for the predicate.

Question 7: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class T {
4. @Override
5. public String toString() {
6. return "T";
7. }
8. }
9.  
10. class Printer<T> {
11. private T t;
12. Printer(T t){
13. this.t = t;
14. }
15. @Override
16. public String toString(){
17. return t.toString();
18. }
19. }
20.  
21. public class Test {
22. public static void main(String[] args) {
23. Printer<T> obj = new Printer<>(new T());
24. System.out.println(obj);
25. }
26. }

What will be the result of compiling and executing Test class?



Compilation error in Printer<T> class


Compilation error in T class


Compilation error in Test class


T
(Correct)

Explanation
T is a valid identifier in Java, hence can be used as class name. toString() method has
been correctly overridden by class T.

No issues with class T. 


Type parameter should not be a Java keyword and naming convention for Type
parameter is to use uppercase single character.

class Printer<T> correctly uses type parameter, T.

When using Generic types in the code, you need to specify the type argument. In
Test class, 'Printer<T> obj' => T refers to class T and not type parameter, T.

System.out.println(obj); => Prints 'T' on to the console.

Question 8: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.NavigableMap;
4. import java.util.TreeMap;
5. import java.util.function.BiConsumer;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. NavigableMap<Integer, String> map = new TreeMap<>();
10. BiConsumer<Integer, String> consumer = map::putIfAbsent;
11. consumer.accept(1, null);
12. consumer.accept(2, "two");
13. consumer.accept(1, "ONE");
14. consumer.accept(2, "TWO");
15.  
16. System.out.println(map);
17. }
18. }

What will be the result of compiling and executing Test class?



{1=ONE, 2=TWO}


{1=null, 2=two}


{1=ONE, 2=two}
(Correct)


{1=null, 2=two}


{1=null, 2=TWO}
Explanation
Though reference variable of NavigableMap is used but putIfAbsent method is from
Map interface. It is a default method added in JDK 8.0.

BiConsumer<T, U> : void accept(T t, U u);

Lambda expression corresponding to 'map::putIfAbsent;' is '(i, s) ->


map.putIfAbsent(i, s)'

This is the case of "Reference to an Instance Method of a Particular Object".

TreeMap sorts the data on the basis of natural order of keys.

consumer.accept(1, null); => {1=null}. 

consumer.accept(2, "two"); => {1=null, 2=two}. 

consumer.accept(1, "ONE"); => {1=ONE, 2=two}. putIfAbsent method replaces null


value with the new value.

consumer.accept(2, "TWO"); => {1=ONE, 2=two}. As value is available against '2',


hence value is not replaced.

Question 9: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. File file = new File("F:\\temp.dat");
8. try(
9. DataOutputStream os = new DataOutputStream(new
FileOutputStream(file));
10. DataInputStream is = new DataInputStream((new
FileInputStream(file)))
11. ) {
12. os.writeChars("JAVA");
13. System.out.println(is.readChar());
14. }
15. }
16. }

What will be the result of compiling and executing Test class?



A


J
(Correct)


V


None of the other options.

Explanation
writeChars(String) is a convenient method to write multiple characters, behind the
scenes it writes 4 characters as 8 bytes of data.

readChar() method returns 2 bytes of data, interpreted as char. Return type is char
and not int.

'J' is displayed in the output.

Question 10: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4. import java.nio.file.Files;
5. import java.nio.file.Paths;
6.  
7. public class Test {
8. public static void main(String[] args) throws IOException {
9. /*INSERT*/
10. }
11. }

F: is accessible for reading and contains 'Book.java' file. 

Which of the following statements, if used to replace /*INSERT*/, will successfully


print contents of 'Book.java' on to the console?
Select 3 options. 


Files.readAllLines(Paths.get("F:\\Book.java")).stream().forEach(System.out
::println);  
(Correct)


Files.lines(Paths.get("F:\\Book.java")).stream().forEach(System.out::print
ln);  


Files.lines(Paths.get("F:\\Book.java")).forEach(System.out::println);  
(Correct)


Files.readAllLines(Paths.get("F:\\Book.java")).forEach(System.out::println
);  
(Correct)

Explanation
Below are the declarations of lines and readAllLines methods from Files class: 

public static Stream<String> lines(Path path) throws IOException {...} 

public static List<String> readAllLines(Path path) throws IOException {...} 

'Files.lines(Paths.get("F:\\Book.java"))' returns Stream<String> object. Hence forEach()


can be invoked but stream() can't be invoked.

'Files.readAllLines(Paths.get("F:\\Book.java"))' returns List<String> object. Hence both


forEach() and stream() methods can be invoked. List has both the methods. But
converting list to stream() and then invoking forEach() method is not required but it
is a legal syntax and prints the file contents.

Question 11: Skipped
Below is the code to Test.java file:
1. package com.udayan.ocp;
2.  
3. enum ShapeType {
4. CIRCLE, SQUARE, RECTANGLE;
5. }
6.  
7. abstract class Shape {
8. private ShapeType type = ShapeType.SQUARE; //default ShapeType
9.  
10. Shape(ShapeType type) {
11. this.type = type;
12. }
13.  
14. public ShapeType getType() {
15. return type;
16. }
17.  
18. abstract void draw();
19. }
20.  
21. public class Test {
22. public static void main(String[] args) {
23. Shape shape = new Shape() {
24. @Override
25. void draw() {
26. System.out.println("Drawing a " + getType());
27. }
28. };
29. shape.draw();
30. }
31. }

What will be the result of compiling and executing Test class?



Drawing a SQUARE


Drawing a RECTANGLE


Compilation error
(Correct)


Drawing a CIRCLE

Explanation
At the time of creating the instance of anonymous inner class, new Shape() is used,
which means it is looking for a no-argument constructor in anonymous inner class
code, which would invoke the no-argument constructor of super class, Shape.

But as parameterized constructor is specified in Shape class, so no-argument


constructor is not provided by the compiler and hence compilation error.

To correct the compilation error, pass the enum constant while instantiating
anonymous inner class. 

Shape shape = new Shape(ShapeType.CIRCLE) {...}; or you can even pass null: Shape
shape = new Shape(null) {...};  OR provide the no-argument constructor in the Shape
class: Shape(){}

Question 12: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.OptionalDouble;
4.  
5. class MyException extends RuntimeException{}
6.  
7. public class Test {
8. public static void main(String[] args) {
9. OptionalDouble optional = OptionalDouble.empty();
10. System.out.println(optional.orElseThrow(MyException::new));
11. }
12. }

What will be the result of compiling and executing Test class?



An instance of MyException is thrown at runtime
(Correct)


An instance of NullPointerException is thrown at runtime


Compilation error


null


An instance of NoSuchElementException is thrown at runtime


An instance of RuntimeException is thrown at runtime

Explanation
orElseThrow throws the instance of provided Exception if optional is empty.

In this case optional is an empty OptionalDouble, hence an instance of MyException


is thrown at runtime.

Question 13: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Comparator;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. String [] arr = {"A5", "B4", "C3", "D2", "E1"};
9. Arrays.sort(arr, Comparator.comparing(s -> s.substring(1)));
10. for(String str : arr) {
11. System.out.print(str + " ");
12. }
13. }
14. }

What will be the result of compiling and executing Test class?



E5 D4 C3 B2 A1


A5 B4 C3 D2 E1


E1 D2 C3 B4 A5
(Correct)


A1 B2 C3 D4 E5

Explanation
Sorting is working on 2nd letter of the array elements, which means 5, 4, 3, 2, 1.

Sorting is in ascending order (1, 2, 3, 4, 5) hence the output is:  E1 D2 C3 B4 A5

Question 14: Skipped
Consider the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class Player {
4. String name;
5. int age;
6.  
7. Player() {
8. this.name = "Yuvraj";
9. this.age = 36;
10. }
11.  
12. public String toString() {
13. return name + ", " + age;
14. }
15.
16. public Class getClass() {
17. return super.getClass();
18. }
19. }
20.  
21. public class Test {
22. public static void main(String[] args) {
23. System.out.println(new Player());
24. }
25. }

What will be the result of compiling and executing Test class?



null, 0

Yuvraj, 36


Compilation error
(Correct)


Text containing @ symbol

Explanation
getClass(), notify(), notifyAll() and overloaded wait methods are final in Object class
and hence cannot be overridden.
Question 15: Skipped
Assume that proper import statements are available, and 'fr' is the language code for
French language. 

And you have the following code snippet:


Locale [] loc = Locale.getAvailableLocales();  

Which of the following statements will print all the supported (by the JVM) French
Language Locale on to the console?
Select 2 options.


Arrays.stream(loc).filter(x ->
x.getLanguage().equals("fr")).forEach(System.out::println);  
(Correct)


Arrays.stream(loc).filter(x ->
x.getLanguage().contains("FR")).forEach(System.out::println);  


Arrays.stream(loc).filter(x ->
x.toString().contains("FR")).forEach(System.out::println);  


Arrays.stream(loc).filter(x ->
x.toString().startsWith("fr")).forEach(System.out::println);  
(Correct)


Arrays.stream(loc).filter(x ->
x.startsWith("fr")).forEach(System.out::println);  
Explanation
'public static Locale[] getAvailableLocales() {...}' returns the Locale [] containing all the
available locales supported by the JVM.

Language codes are stored in lower case, so syntax comparing upper case codes
('FR') is ruled out.

You are left with 3 options [working with lower case language code ('fr')]. 'x' in the
lambda expression is of Locale type and Locale class doesn't have method startsWith,
so 'x -> x.startsWith("fr")' causes compilation failure.

'x -> x.getLanguage().equals("fr")' and 'x -> x.toString().startsWith("fr")' correctly


filters out expected Locale objects.

Question 16: Skipped
F: is accessible for reading/writing and below is the directory structure for F:
1. F:.
2. └───Parent
3. │ a.txt
4. │ b.txt
5. │
6. └───Child
7. c.txt
8. d.txt

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7. import java.nio.file.attribute.BasicFileAttributes;
8. import java.util.function.BiPredicate;
9. import java.util.stream.Stream;
10.  
11. public class Test {
12. public static void main(String[] args) throws IOException {
13. Path root = Paths.get("F:");
14. BiPredicate<Path, BasicFileAttributes> predicate = (p,a) ->
p.toString().endsWith("txt");
15. try(Stream<Path> paths = Files.find(root, 2, predicate))
16. {
17. paths.forEach(System.out::println);
18. }
19. }
20. }

What will be the result of compiling and executing Test class?



Above program executes successfully and prints nothing on to the console.


Above program executes successfully and prints below lines on to the console:
F:Parent\Child\c.txt
F:Parent\Child\d.txt
F:Parent\a.txt
F:Parent\b.txt


Above program executes successfully and prints below lines on to the console:
F:Parent\a.txt
F:Parent\b.txt
(Correct)

Explanation
String class has endsWith method, and the lambda expression '(p,a) ->
p.toString().endsWith("txt")' will return all the paths ending with "txt".

Signature of find method is:

Stream<Path> find(Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes>


matcher, FileVisitOption... options)

and in the code, following syntax is used: Files.find(root, 2, predicate).

root refers to 'F:' and maxDepth is 2. This means look out for all the files under F:
(depth 1) and all the files under the directories whose immediate parent is F: (depth
2).

So in this case, F: and Parent directory are searched for the matching files.
'F:Parent\a.txt' and 'F:Parent\b.txt' are printed on to the console.

Question 17: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Comparator;
5. import java.util.List;
6.  
7. class Person {
8. private String firstName;
9. private String lastName;
10.  
11. public Person(String firstName, String lastName) {
12. this.firstName = firstName;
13. this.lastName = lastName;
14. }
15.  
16. public String getFirstName() {
17. return firstName;
18. }
19.  
20. public String getLastName() {
21. return lastName;
22. }
23.  
24. public String toString() {
25. return "{" + firstName + ", " + lastName + "}";
26. }
27. }
28.  
29. public class Test {
30. public static void main(String[] args) {
31. List<Person> list = Arrays.asList(
32. new Person("Tom", "Riddle"),
33. new Person("Tom", "Hanks"),
34. new Person("Yusuf", "Pathan"));
35. list.stream().sorted(Comparator.comparing(Person::getFirstName).reversed()
36. .thenComparing(Person::getLastName)).forEach(System.out::println);
37. }
38. }

What will be the result of compiling and executing Test class?



{Tom, Riddle}
{Tom, Hanks}
{Yusuf, Pathan}


{Tom, Hanks}
{Tom, Riddle}
{Yusuf, Pathan}


{Yusuf, Pathan}
{Tom, Riddle}
{Tom, Hanks}


{Yusuf, Pathan}
{Tom, Hanks}
{Tom, Riddle}
(Correct)

Explanation
In this case, sorted method accepts an instance of Comparator<Person> type.

Comparator.comparing(Person::getFirstName) => Returns a Comparator for sorting


the records in ascending order of first name. 

Comparator.comparing(Person::getFirstName).reversed() => Returns a Comparator


for sorting the records in descending order of first name. 

Comparator.comparing(Person::getFirstName).reversed().thenComparing(Person::getL
astName) => Returns a Comparator for sorting the records in descending order of
first name and in case first name matches, then ascending order of last name.

So correct answer is:

{Yusuf, Pathan}

{Tom, Hanks}

{Tom, Riddle}

Question 18: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Scanner;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. System.out.print("Enter some text: ");
8. try(Scanner scan = new Scanner(System.in)) {
9. String s = scan.nextLine();
10. System.out.println(s);
11. scan.close();
12. scan.close();
13. }
14. }
15. }

What will be the result of compiling and executing Test class?


User input is: HELLO

On execution program terminates successfully after printing 'HELLO' on to the
console
(Correct)


Compilation error


Runtime Exception

Explanation
Even though Scanner is created in try-with-resources block, calling close() method
explicitly doesn't cause any problem.

Scanner class allows to invoke close() method multiple times. In this case, it will be
called 3 times: twice because of scan.close() and once because of try-with-resources
statement.

'HELLO' is printed on to the console and program terminates successfully.

Question 19: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. interface Printer1 {
4. default void print() {
5. System.out.println("Printer1");
6. }
7. }
8.  
9. class Printer2 {
10. public void print() {
11. System.out.println("Printer2");
12. }
13. }
14.  
15. class Printer extends Printer2 implements Printer1 {
16.  
17. }
18.  
19. public class Test {
20. public static void main(String[] args) {
21. Printer printer = new Printer();
22. printer.print();
23. }
24. }

What will be the result of compiling and executing Test class?



Printer1

Compilation error for Printer


Compilation error for Printer1


Compilation error for Printer2


Printer2
(Correct)

Explanation
print() method is defined in interface Printer1 and class Printer2.

class Printer inherits both the methods but there is no conflict in this case as print()
method defined in Printer2 class is used.

'Printer2' is printed on to the console.

Question 20: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try {
8. Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ocp", "root", "password");
9. String query = "Select * FROM EMPLOYEE";
10. Statement stmt = con.createStatement();
11. ResultSet rs = stmt.executeQuery(query);
12. while (rs.next()) { //Line 12
13. System.out.println("ID: " + rs.getInt("ID"));
14. System.out.println("First Name: " + rs.getString("FIRSTNAME"));
15. System.out.println("Last Name: " + rs.getString("LASTNAME"));
16. System.out.println("Salary: " + rs.getDouble("SALARY"));
17. }
18. rs.close(); //Line 18
19. stmt.close();
20. con.close();
21. } catch (SQLException ex) {
22. ex.printStackTrace();
23. }
24. }
25. }

Also assume: 
URL, username and password are correct.
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 result of compiling and executing Test class?


Line 12 throws an exception at runtime


Code executes fine and prints following on to the console: 
ID: 0
First Name: null
Last Name: null
Salary: 0.0


Code executes fine and doesn't print anything on to the console
(Correct)


Line 18 throws an exception at runtime

Explanation
Even if there are no records in EMPLOYEE table, ResultSet object returned by
'stmt.executeQuery(query);' will never be null.

rs.next() returns false and control doesn't enter while loop. Code executes fine and
doesn't print anything on to the console.

Question 21: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> codes = Arrays.asList("1st", "2nd", "3rd", "4th");
9. System.out.println(codes.stream().filter(
10. s -> s.endsWith("d")).reduce((s1, s2) -> s1 + s2));
11. }
12. }

What will be the result of compiling and executing Test class?



Optional[1st4th]


1st4th


Optional[2nd3rd]
(Correct)


2nd3rd

Explanation
filter method filters all the strings ending with "d".

'stream.reduce((s1, s2) -> s1 + s2)' returns 'Optional<String>' type, whereas


'stream.reduce("", (s1, s2) -> s1 + s2)' returns 'String'.

Question 22: Skipped
Consider the following interface declaration:
1. public interface I1 {
2. void m1() throws java.io.IOException;
3. }

Which of the following incorrectly implements interface I1?



1. public class C4 implements I1 {
2.     public void m1() throws Exception{}
3. }

(Correct)


1. public class C2 implements I1 {
2.     public void m1() throws java.io.FileNotFoundException{}
3. }

1. public class C1 implements I1 {
2. public void m1() {}
3. }

1. public class C3 implements I1 {
2.     public void m1() throws java.io.IOException{}
3. }

Explanation
NOTE: Question is asking for "incorrect" implementation and not "correct"
implementation.

According to overriding rules, if super class / interface method declares to throw a


checked exception, then overriding method of sub class / implementer class has
following options: 

1. May not declare to throw any checked exception, 

2. May declare to throw the same checked exception thrown by super class /
interface method, 

3. May declare to throw the sub class of the exception thrown by super class /
interface method, 

4. Cannot declare to throw the super class of the exception thrown by super class /
interface method.

Question 23: Skipped
Daylight saving time 2018 in United States (US) ends at 4-Nov-2018 2:00 AM. 
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date = LocalDate.of(2018, 11, 4);
8. LocalTime time = LocalTime.of(13, 59, 59);
9. ZonedDateTime dt = ZonedDateTime.of(date, time,
ZoneId.of("America/New_York"));
10. dt = dt.plusSeconds(1);
11. System.out.println(dt.getHour() + ":" + dt.getMinute() + ":" +
dt.getSecond());
12. }
13. }


12:0:0


14:0:0
(Correct)


13:0:0

Explanation
You should be aware of Day light saving mechanism to answer this question. 
Suppose daylight time starts at 2 AM on particular date. 

Current time: 1:59:59 [Normal time]. 

Next second: 3:00:00 [Time is not 2:00:00 rather it is 3:00:00. It is Daylight saving
time]. 

Clock just jumped from 1:59:59 to 3:00:00. 

Now Suppose daylight time ends at 2 AM on particular date. 

Current time: 1:59:59 [Daylight saving time]. 

Next second:  1:00:00 [Time is not 2:00:00 rather it is 1:00:00. Clock switched back to
normal time].

Clock just went back from 1:59:59 to 1:00:00. 

Now let's solve given code:

dt --> {2018-11-04T13:59:59}. Daylight saving time has already ended as it is PM and


not AM. This is acturally a normal time now.

dt.plusSeconds(1) => creates a new ZonedDateTime object {2018-11-04T14:00:00}


and dt refers to it.

dt.getHour() = 14, dt.getMinute() = 0 and dt.getSecond() = 0.

Question 24: Skipped
Consider below code:
1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. Operation o1 = (x, y) -> x + y;
6. System.out.println(o1.operate(5, 10));
7. }
8. }
Which of the following functional interface definitions can be used here, so that the
output of above code is: 15?
Select 3 options.

1. interface Operation {
2. int operate(int x, int y);
3. }

(Correct)


1. interface Operation<T extends Integer> {
2. T operate(T x, T y);
3. }

(Correct)


1. interface Operation<T> {
2. T operate(T x, T y);
3. }

1. interface Operation {
2. long operate(long x, long y);
3. }

(Correct)

Explanation
From the given syntax inside main method, it is clear that interface name is
Operation and it has an abstract method operate which accepts 2 parameters of
numeric type and returns the numeric result (as result of adding 5 and 10 is 15).

So, int and long versions can be easily applied here. 

Operation<T> will not work here as inside main method, raw type is used, which
means x and y will be of Object type and x + y will cause compilation error as +
operator is not defined when both the operands are of Object type. 

For Operation<T extends Integer>, even though main method uses raw type, but x
and y will be of Integer type and hence x + y will not cause any compilation error.

Question 25: Skipped
What is the purpose of below lambda expression?

(x, y) -> x + y;  

It accepts two int arguments, adds them and returns the int value


It accepts two String arguments, concatenates them and returns the String
instance


Not possible to define the purpose
(Correct)


It accepts a String and an int arguments, concatenates them and returns the
String instance

Explanation
Lambda expression doesn't work without target type and target type must be a
functional interface.

In this case as the given lambda expression is not assigned to any target type, hence
its purpose is not clear.

In fact, given lambda expression causes compilation error without its target type.

Question 26: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class MyThread implements Runnable {
6. private String str;
7.  
8. MyThread(String str) {
9. this.str = str;
10. }
11.  
12. public void run() {
13. System.out.println(str.toUpperCase());
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) throws ExecutionException,
InterruptedException{
19. ExecutorService es = Executors.newSingleThreadExecutor();
20. MyThread thread = new MyThread("ocp");
21. Future future = es.submit(thread);
22. Integer tmp = (Integer) future.get(); //Line 22
23. System.out.println(tmp);
24. es.shutdown();
25. }
26. }
What will be the result of compiling and executing Test class?

OCP
OCP


ClassCastException is thrown at runtime by Line 22


OCP
null
(Correct)


Compilation error is caused by Line 22


ocp
null

Explanation
get() method throws 2 checked exceptions: InterruptedException and
ExecutionException. And future.get() returns Object and it can be type-casted to
Integer, so no compilation error.

run() method of MyThread prints 'OCP' on to the console and doesn't return
anything, hence get() method of Future object returns null. null can be easily
assigned to Integer.

Hence 'System.out.println(tmp);' prints null on to the console.

Question 27: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.HashMap;
4. import java.util.Map;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Map<Integer, String> map = new HashMap<>();
9. map.put(1, "ONE");
10. map.put(2, "TWO");
11. map.put(3, "THREE");
12.
13.         System.out.println(map.stream().count());
14. }
15. }
What will be the result of compiling and executing Test class?

Runtime Exception


3


Compilation error
(Correct)


6

Explanation
There is no stream() method available in Map interface and hence map.stream()
causes compilation error.

Though you can first get either entrySet or keySet or values and then invoke stream()
method.

For example, below code prints all the key value pairs available in the map:

map.entrySet().stream().forEach(x -> System.out.println(x.getKey() + ":" +


x.getValue()));

Question 28: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalTime t1 = LocalTime.now();
8. LocalDateTime t2 = LocalDateTime.now();
9. System.out.println(Duration.between(t2, t1));
10. }
11. }

What will be the result of compiling and executing Test class?



Program terminates successfully after displaying the output


Runtime Exception
(Correct)


Compilation error

Explanation
Signature of between method defined in Duration class is: 'Duration
between(Temporal startInclusive, Temporal endExclusive)'.

As both LocalTime and LocalDateTime implement 'Temporal' interface, hence there is


no compilation error.

If the Temporal objects are of different types as in this case, calculation is based on
1st argument and 2nd argument is converted to the type of 1st argument.

1st argument, 't2' is of LocalDateTime and 2nd argument, 't1' is of LocalTime. At


runtime it is not possible to convert LocalTime to LocalDateTime and hence
exception is thrown at runtime.

Question 29: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.sql.SQLException;
4.  
5. public class Test {
6. private static void m() throws SQLException {
7. try {
8. throw new SQLException();
9. } catch (Exception e) {
10. throw e;
11. }
12. }
13.  
14. public static void main(String[] args) {
15. try {
16. m();
17. } catch(SQLException e) {
18. System.out.println("Caught Successfully.");
19. }
20. }
21. }

What will be the result of compiling and executing Test class?



Caught Successfully.
(Correct)


Program ends abruptly.


Method m() causes compilation error.


Method main(String []) causes compilation error.

Explanation
Even though it seems like method m() will not compile successfully, but starting with
JDK 7, it is allowed to use super class reference variable in throw statement referring
to sub class Exception object.

In this case, method m() throws SQLException and compiler knows that variable e
(Exception type) refers to an instance of SQLException only and hence allows it.

Program executes successfully and prints 'Caught Successfully.' on to the console.

Question 30: Skipped
Consider the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class Printer {
4. private static int count = 0;
5. private Printer() {
6. count++;
7. }
8.  
9. static Printer getInstance() {
10. return PrinterCreator.printer;
11. }
12.  
13. static class PrinterCreator {
14. static Printer printer = new Printer();
15. }
16.  
17. static int getCount() {
18. return count;
19. }
20. }
21.  
22. public class Test {
23. public static void main(String[] args) {
24. Printer p1 = Printer.getInstance();
25. Printer p2 = Printer.getInstance();
26. Printer p3 = Printer.getInstance();
27. System.out.println(Printer.getCount());
28. }
29. }

What will be the result of compiling and executing Test class?



3


2


1
(Correct)


0

Explanation
This is an example of Singleton class. static fields are initialize once, when class loads
in the memory.

'printer' is static reference variable defined in PrinterCreator (static nested) class.

Printer p1 = Printer.getInstance(); => getInstance method loads the PrinterCreator


class in the memory causing 'static Printer printer = new Printer();' to get executed.
object of Printer class is created and variable count is incremented by 1.

Later invocation of Printer.getInstance(); method simply returns the reference of


Printer object so Printer class's constructor is not invoked.

Variable count is incremented only once.

Question 31: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.function.Predicate;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<Integer> list = Arrays.asList(-80, 100, -40, 25, 200);
10. Predicate<Integer> predicate = num -> {
11. int ctr = 1;
12. boolean result = num > 0;
13. System.out.print(ctr++ + ".");
14. return result;
15. };
16.
17. list.stream().filter(predicate).findFirst();
18. }
19. }

What will be the result of compiling and executing Test class?



1.1.
(Correct)


1.


1.2.


1.2.3.4.5.


Nothing is printed on to the console.


1.1.1.1.1.

Explanation
findFirst() is terminal operation.

list.stream() => [-80, 100, -40, 25, 200].

filter(predicate) is executed for each element until just one element passes the test.
Because findFirst() will terminate the operation on finding first matching element.

NOTE: a new instance of Predicate is used, hence every time ctr will be initialize to 1.

For -80, Output is '1.' but predicate returns false, hence findFirst() doesn't terminate
the operation.
For 100, '1.' is appended to previous output, so on console you will see '1.1.' and
predicate returns true, hence findFirst() finds an element and terminates the
operation.

Final output is: '1.1.'

Question 32: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.function.ToIntFunction;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String text = "Aa aA aB Ba aC Ca";
8. ToIntFunction<String> func = text::indexOf;
9. System.out.println(func.applyAsInt("a"));
10. }
11. }

What will be the result of compiling and executing Test class?



0


-1


1
(Correct)


Compilation error

Explanation
'text::indexOf' is equivalent to lambda expression 'search -> text.indexOf(search)'. 

ToIntFunction<T> has method: int applyAsInt(T value);.

In this case T is of String type.


func.applyAsInt("a") will invoke text.indexOf("a"), which returns the index of first
occurrence of "a". In the given text, it is 1.

Question 33: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class Resource1 {
4. public void close() {
5. System.out.println("Resource1");
6. }
7. }
8.  
9. class Resource2 {
10. public void close() {
11. System.out.println("Resource2");
12. }
13. }
14.  
15. public class Test {
16. public static void main(String[] args) {
17. try(Resource1 r1 = new Resource1(); Resource2 r2 = new Resource2()) {
18. System.out.println("Test");
19. }
20. }
21. }

What will be the result of compiling and executing Test class?



Test
Resource2
Resource1


Compilation Error
(Correct)


Test
Resource1
Resource2

Explanation
Classes used in try-with-resources statement must implement
java.lang.AutoCloseable or its sub interfaces such as java.io.Closeable.

As Resource1 and Resource2 don't implement AutoCloseable interface, hence try-


with-resources statement causes compilation error.

Question 34: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Optional<Integer> optional = Optional.ofNullable(null);
8. System.out.println(optional);
9. }
10. }

What will be the result of compiling and executing Test class?



Optional[0]


NullPointerException is thrown at runtime


Optional.empty
(Correct)


Optional[null]

Explanation
ofNullable method creates an empty Optional object if passed argument is null.

Optional.empty is printed on to the console for empty Optional.

Question 35: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.BiPredicate;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. BiPredicate<String, String> predicate = String::equalsIgnoreCase;
8. System.out.println(predicate.test("JaVa", "Java"));
9. }
10. }

What will be the result of compiling and executing Test class?



Runtime error


false

true
(Correct)


Compilation error

Explanation
BiPredicate<T, U> : boolean test(T t, U u); 

BiPredicate interface accepts 2 type parameters and these parameters (T,U) are
passed to test method, which returns primitive boolean.

In this case, 'BiPredicate<String, String> predicate' means test method will have
declaration: 'boolean test(String s1, String d2)'.

'String::equalsIgnoreCase' is equivalent to '(s1, s2) -> s1.equalsIgnoreCase(s2)'

This is an example of "Reference to an Instance Method of an Arbitrary Object of a


Particular Type" and not "method reference to static method".

"JaVa".equalsIgnoreCase("Java") => returns true.

Question 36: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.LocalDateTime;
4. import java.time.format.DateTimeFormatter;
5. import java.time.format.FormatStyle;
6.  
7. public class Test {
8. public static void main(String [] args) {
9. LocalDateTime date = LocalDateTime.of(2019, 1, 1, 10, 10);
10. DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
11. System.out.println(formatter.format(date));
12. }
13. }
Will above code display time part on to the console?

No
(Correct)


Yes

Explanation
DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL); statement returns formatter
to format date part.

date is of LocalDateTime type hence it has both date part and time part.

'formatter.format(date)' simply formats the date part and ignores time part.

NOTE: You should aware of other formatter related methods for the OCP exam, such
as: 'ofLocalizedTime' and 'ofLocalizedDateTime'

Question 37: Skipped
Below files are available for your project: 
1. //1. ResourceBundle.properties
2. locale=French/Canada

1. //2. ResourceBundle_CA.properties
2. locale=Canada

1. //3. ResourceBundle_hi.properties
2. locale=Hindi

1. //4. ResourceBundle_IN.properties
2. locale=India

1. //5. Test.java
2. package com.udayan.ocp;
3.  
4. import java.util.Locale;
5. import java.util.ResourceBundle;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Locale.setDefault(new Locale("fr", "CA"));
10. Locale loc = new Locale("en", "IN");
11. ResourceBundle rb = ResourceBundle.getBundle("ResourceBundle", loc);
12. System.out.println(rb.getObject("locale"));
13. }
14. }
Assume that all the *.properties files are included in the CLASSPATH. What will be the
output of compiling and executing Test class?

French/Canada
(Correct)


Hindi


Canada


India


Runtime Exception

Explanation
ResourceBundle.getBundle("ResourceBundle", loc); => Base resource bundle file
name should be 'ResourceBundle'.

Default Locale is: fr_CA and passed Locale to getBundle method is: en_IN

The search order for matching resource bundle is:

ResourceBundle_en_IN.properties [1st: Complete en_IN]. 

ResourceBundle_en.properties [2nd: Only language en]. 

ResourceBundle_fr_CA.properties [3rd: Complete default Locale fr_CA]. 

ResourceBundle_fr.properties [4th: Language of default Locale fr]. 

ResourceBundle.properties [5th: ResourceBundle's name without language or


country]. 

Out of the given resource bundles, 'ResourceBundle.properties' matches.

This resource bundle has key 'locale' and value 'French/Canada'. 


rb.getObject("locale") prints 'French/Canada' on to the console.

Question 38: Skipped
C:\ is accessible for reading/writing and below is the content of 'C:\TEMP' folder:
1. C:\TEMP
2. │ msg
3. │
4. └───Parent
5. └───Child
6. Message.txt

'msg' is a symbolic link file for 'C:\TEMP\Parent\Child\Message.txt'. 

Message.txt contains following text:


Welcome!

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.nio.file.Files;
6. import java.nio.file.Path;
7. import java.nio.file.Paths;
8.  
9. public class Test {
10. public static void main(String[] args) throws IOException {
11. Path path = Paths.get("C:", "TEMP", "msg");
12.  
13. try (BufferedReader reader = Files.newBufferedReader(path)) {
14. String str = null;
15. while ((str = reader.readLine()) != null) {
16. System.out.println(str);
17. }
18. }
19. }
20. }

What will be the result of compiling and executing Test class?



Program executes successfully and prints 'Welcome!' on to the console
(Correct)


Program executes successfully and produces no output


Compilation error


An exception is thrown at runtime

Explanation
First of all I would like to tell you that Windows shortcut and symbolic links are
different. 

Shortcut is just a regular file and symbolic link is a File System object. 

To create symbolic link used in this question, I used below command:

C:\TEMP>mklink msg .\Parent\Child\Message.txt 

And below message was displayed on to the console for the successful creation of
symbolic link 'symbolic link created for msg <<===>> .\Parent\Child\Message.txt'. 

Files class has methods such as newInputStream(...), newOutputStream(...),


newBufferedReader(...) and newBufferedWriter(...) for files reading and writing.

Give code doesn't cause any compilation error.

path refers to 'C\TEMP\msg', which is a symbolic link and hence


Files.newBufferedReader(path) works with 'C:\TEMP\Parent\Child\Message.txt'.

Given code successfully reads the file and prints 'Welcome!' on to the console.

Question 39: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.Arrays;
5. import java.util.List;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
10. list.removeIf(i -> i % 2 == 1);
11. System.out.println(list);
12. }
13. }

What will be the result of compiling and executing Test class?



[2, 4, 6, 8, 10]
(Correct)


Runtime Exception


[1, 3, 5, 7, 9]


Compilation Error

Explanation
Arrays.asList(...) method returns a list backed with array, so items cannot be added to
or removed from the list. 

But if this list is passed to the constructor of ArrayList, then new ArrayList instance is
created which copies the elements of passed list and elements can be added to or
removed from this list. 

List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10)); =>


[1,2,3,4,5,6,7,8,9,10]. 

list.removeIf(i -> i % 2 == 1); => [2,4,6,8,10]. Remove the element for which passed
Predicate is true.

Question 40: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. class Student {
6. private String name;
7. private int age;
8.  
9. Student(String name, int age) {
10. this.name = name;
11. this.age = age;
12. }
13.  
14. public int hashCode() {
15. return name.hashCode() + age;
16. }
17.  
18. public String toString() {
19. return "Student[" + name + ", " + age + "]";
20. }
21.  
22. public boolean equals(Object obj) {
23. if(obj instanceof Student) {
24. Student stud = (Student)obj;
25. return this.name.equals(stud.name) && this.age == stud.age;
26. }
27. return false;
28. }
29.  
30. public String getName() {return name;}
31.  
32. public int getAge() {return age;}
33.  
34. public static int compareByName(Student s1, Student s2) {
35. return s1.getName().compareTo(s2.getName());
36. }
37. }
38.  
39. public class Test {
40. public static void main(String[] args) {
41. Set<Student> students = new TreeSet<>(Student::compareByName);
42. students.add(new Student("James", 20));
43. students.add(new Student("James", 20));
44. students.add(new Student("James", 22));
45.  
46. System.out.println(students.size());
47. }
48. }

What will be the result of compiling and executing Test class?



Runtime Exception


2


3


1
(Correct)

Explanation
TreeSet requires you to provide either Comparable or Comparator. NOTE: To be used
with TreeSet, it is not needed to override equals(Object) and hashCode() methods.

But in real world projects, it is a good practice to override hashCode() and


equals(Object) methods for the classes to be used in Collection framework.

In this case 'new TreeSet<>(Student::compareByName);' provides the instance of


Comparator<Student> type, which compares the names only.
All 3 Student objects have same name and hence only first Student object was added
to this set.

Question 41: Skipped
Imagine below path exists:
1. F:.
2. └───A
3. └───B
4.

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. File dir = new File("F:" + File.separator + "A" + File.separator + "B");
8. System.out.println(dir.getParentFile().getParent());
9. }
10. }

What will be the result of compiling and executing Test class?



F:\A


Compilation error


NullPointerException is thrown at runtime


F:\
(Correct)

Explanation
File class has below 2 methods:

public File getParentFile() {...}

public String getParent() {...}

'dir' refers to File object for abstract path 'F:\A\B'.

dir.getParentFile() => returns a File object for abstract path 'F:\A'


dir.getParentFile().getParent() => returns a String object referring to 'F:\'

Question 42: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. IntStream.rangeClosed(1, 10).parallel()
8. .forEachOrdered(System.out::println);
9. }
10. }

What will be the result of compiling and executing Test class?



It will print numbers form 1 to 10 but not in any specific order


It will print numbers form 1 to 10 in descending order


It will print numbers from 1 to 10 in ascending order
(Correct)

Explanation
IntStream.rangeClosed(1, 10) returns a sequential ordered IntStream but parallel()
method converts it to a parallel stream. 

forEachOrdered() will processes the elements of the stream in the order specified by
its source (Encounter order), regardless of whether the stream is sequential or
parallel, hence given code prints 1 to 10 in ascending order.

Question 43: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
13. ) {
14. ResultSet rs = stmt.executeQuery(query);
15. rs.relative(-3);
16. rs.relative(1);
17. System.out.println(rs.getInt(1));
18. }
19. }
20. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


An exception is thrown at runtime.


104


101
(Correct)


102


103

Explanation
Given query returns below records:

101 John Smith 12000   

102 Sean Smith 15000   

103 Regina Williams 15500   

104 Natasha George 14600   

Initially cursor is just before the 1st record.

'rs.relative(-3);' doesn't throw any exception but keeps the cursor just before the 1st
record. According to javadoc of relative method, "Attempting to move beyond the
first/last row in the result set positions the cursor before/after the first/last row".
Same is true for absolute method as well.

'rs.relative(1);' is identical to 'rs.next()' so it moves the cursor to the 1st record.

'rs.getInt(1)' returns 101.

Question 44: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path path1 = Paths.get("F:\\A\\B\\C");
9. Path path2 = Paths.get("F:\\A");
10. System.out.println(path1.relativize(path2));
11. System.out.println(path2.relativize(path1));
12. }
13. }

What will be the result of compiling and executing Test class?



..\..
B\C
(Correct)


An exception is thrown at runtime


Compilation error


B\C
..\..

Explanation
For 'path1.relativize(path2)' both path1 and path2 should be of same type. Both
should either be relative or absolute.

In this case, path1 refers to 'F:\A\B\C' and path2 refers to 'F:\A'.

To easily tell the resultant path, there is a simple trick. Just remember this for the
exam.

path1.relativize(path2) means how to reach path2 from path1. It is by doing 'cd ..\..'
so, 1st output is '..\..'

path2.relativize(path1) means how to reach path1 from path2. It is by doing 'cd B\C'
so, 2nd output is 'B\C'.

Question 45: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class Printer implements Callable<String> {
6. public String call() {
7. System.out.println("DONE");
8. return null;
9. }
10. }
11.  
12. public class Test {
13. public static void main(String[] args) {
14. ExecutorService es = Executors.newFixedThreadPool(1);
15. es.submit(new Printer());
16. System.out.println("HELLO");
17. es.shutdown();
18. }
19. }

What will be the result of compiling and executing Test class?



HELLO will always be printed before DONE.


DONE will always be printed before HELLO.


HELLO and DONE will be printed but printing order is not fixed.
(Correct)


HELLO will never be printed.

Explanation
'es.submit(new Printer());' is asynchronous call, hence 2 threads(main and thread from
pool) always run in asynchronous mode.

Thread execution depends upon underlying OS/JVM's thread scheduling mechanism.

HELLO and DONE will be printed but their order cannot be predicted.

Question 46: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path path = Paths.get("F:\\A\\B\\C\\Book.java");
9. System.out.println(path.subpath(1,4));
10. }
11. }

What will be the result of compiling and executing Test class?



B\C\Book.java
(Correct)


A\B\C\Book.java

Exception is thrown at runtime


A\B\C

Explanation
Root folder or drive is not considered in count and indexing. In the given path A is at
0th index, B is at 1st index, C is at 2nd index and Book.java is at 3rd index.

In 'subpath(int beginIndex, int endIndex)' method beginIndex in inclusive and


endIndex is exclusive. So, in the given question, starting index is 1 and end index is 3.

So, 'path.subpath(1,4)' returns 'B\C\Book.java'.

Question 47: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.Consumer;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Consumer<Integer> consumer = System.out::print;
8. Integer i = 5;
9. consumer.andThen(consumer).accept(i++); //Line 7
10. }
11. }

What will be the result of compiling and executing Test class?



66


55
(Correct)


56


Compilation error

Explanation
andThen is the default method defined in Consumer interface, so it is invoked on
consumer reference variable. 
Value passed in the argument of accept method is passed to both the consumer
objects. So, for understanding purpose Line 7 can be split into: consumer.accept(5);
consumer.accept(5); So it prints '55' on to the console.

Check the code of andThen method defined in Consumer interface to understand it


better.

Question 48: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.concurrent.*;
6.  
7. public class Test {
8. public static void main(String[] args) throws InterruptedException,
ExecutionException {
9. Callable<String> c = new Callable<String>() {
10. @Override
11. public String call() throws Exception {
12. try {
13. Thread.sleep(3000);
14. } catch(InterruptedException e) {}
15. return "HELLO";
16. }
17. };
18.  
19. ExecutorService es = Executors.newFixedThreadPool(10);
20. List<Callable<String>> list = Arrays.asList(c,c,c,c,c);
21. List<Future<String>> futures = es.invokeAll(list);
22. System.out.println(futures.size());
23. es.shutdown();
24. }
25. }

Which of the following statement is correct about above code?



As each Thread sleeps for 3 secs, so program will take at least 15 secs. to print 5.


Program will print 5 in less than 3 secs.


Program will print 5 in any time greater than or equal to 3 secs.
(Correct)


Program will always print 5 in exactly 3 secs.
Explanation
There is a fixed thread pool of 10 threads, this means 10 threads can run in parallel.

invokeAll() method causes the current thread (main) to wait, until all the Callable
instances finish their execution.

This means 'System.out.println(futures.size());' will execute once all the 5 tasks are
complete.

Important point to note here is that all the Callable instances are executed in parallel.
Even if all the tasks start at one instant, there will always be some overhead for
sleeping thread to become running.

In most of the cases it will be in nanoseconds/milliseconds. Hence overall time will be


slightly greater than 3 secs.

Question 49: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String [] cities = {"Seoul", "Tokyo", "Paris", "London",
8. "Hong Kong", "Singapore"};
9. Arrays.stream(cities).sorted((s1,s2) -> s2.compareTo(s1))
10. .forEach(System.out::println);
11. }
12. }

What will be the result of compiling and executing Test class?



Tokyo
Singapore
Seoul
Paris
London
Hong Kong
(Correct)


Hong Kong
London
Paris
Seoul
Singapore
Tokyo


Seoul
Tokyo
Paris
London
Hong Kong
Singapore


Compilation error

Explanation
Arrays class has overloaded stream(...) method to convert arrays to Stream.

sorted(...) method of Stream interface is also overloaded:

sorted() => sorts on natural order

and

sorted(Comparator) => sorts on passed Comparator.

sorted((s1,s2) -> s2.compareTo(s1)) => sorts on descending order. 

forEach(System.out::println); => Prints all the Stream data.

Question 50: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. class Point {
7. int x;
8. int y;
9. Point(int x, int y) {
10. this.x = x;
11. this.y = y;
12. }
13.
14. public String toString() {
15. return "Point(" + x + ", " + y + ")";
16. }
17.
18. boolean filter() {
19. return this.x == this.y;
20. }
21.
22. }
23. public class Test {
24. public static void main(String[] args) {
25. List<Point> list = new ArrayList<>();
26. list.add(new Point(0, 0));
27. list.add(new Point(1, 2));
28. list.add(new Point(-1, -1));
29.
30. list.stream().filter(Point::filter).forEach(System.out::println); //Line n1
31. }
32. }

What will be the result of compiling and executing Test class?



Line n1 causes compilation error


Point(0, 0)
Point(-1, -1)
(Correct)


Point(1, 2)


Point(0, 0)
Point(1, 2)
Point(-1, -1)

Explanation
'Point::filter' is an example of "Reference to an Instance Method of an Arbitrary
Object of a Particular Type". Equivalent lambda expression is: '(Point p) -> p.filter()'.

As filter(...) method accepts Predicate<? super Point> instance as an argument, hence


given method reference syntax is the correct implementation of the Predicate. Line
n1 compiles successfully.

Result of filtration is the Stream<Point> instance containing Point objects whose x


== y. Therefore, this stream contains Point(0, 0) and Point(-1, -1).

forEach(System.out::println) prints Point(0, 0) and Point(-1, -1) on to the console.

Question 51: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.atomic.AtomicInteger;
4.  
5. class Counter implements Runnable {
6. private static AtomicInteger ai = new AtomicInteger(3);
7.  
8. public void run() {
9. System.out.print(ai.getAndDecrement());
10. }
11. }
12.  
13. public class Test {
14. public static void main(String[] args) {
15. Thread t1 = new Thread(new Counter());
16. Thread t2 = new Thread(new Counter());
17. Thread t3 = new Thread(new Counter());
18. Thread[] threads = {t1, t2, t3};
19. for(Thread thread : threads) {
20. thread.start();
21. }
22. }
23. }

What will be the result of compiling and executing Test class?



None of the other options


It will print three digits 210 but order can be different


It will always print 321


It will print three digits 321 but order can be different
(Correct)


It will always print 210

Explanation
AtomicInteger's getAndDecrement() method will first retrieve the value and then
decrement and it happens atomically.

So during the execution of getAndDecrement() method, another thread cannot


execute getAndDecrement() method. This means output will have 3 digits 3, 2 and 1.

But execution of threads depend on OS/JVM implementation, hence order of output


can be different.

Question 52: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Instant instant = Instant.now();
8. LocalDateTime obj = null; //Line n1
9. }
10. }

Which of the following statements will replace null at Line n1 such that Instant object
referred by 'instant' is converted to LocalDateTime object?

instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
(Correct)


instant.toLocalDateTime();


LocalDateTime.of(instant);


(LocalDateTime)instant;

Explanation
Instant class doesn't have any method to convert to LocalDate, LocalDateTime or
LocalTime and vice-versa. Hence, 'instant.toLocalDateTime();' and
'LocalDateTime.of(instant);' cause compilation error.

'(LocalDateTime)instant' also causes compilation failure as LocalDateTime and Instant


are not related in multilevel inheritance.

Hence, the only option left is:


'instant.atZone(ZoneId.systemDefault()).toLocalDateTime();'.

Let us understand what is happening with above statement:

ZonedDateTime class has methods to convert to LocalDate, LocalDateTime and


LocalTime instances. So, object of Instant is first converted to ZonedDateTime.

An Instant object doesn't store any information about the time zone, so to convert it
to ZonedDateTime, the default zone (ZoneId.systemDefault()) is passed to atZone
method.
'instant.atZone(ZoneId.systemDefault())' returns an instance of ZonedDateTime and
toLocalDateTime() method returns the corresponding instance of LocalDateTime.

Question 53: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. int res = 1;
8. IntStream stream = IntStream.rangeClosed(1, 5);
9. /*INSERT*/
10. }
11. }

Which of the following options can replace /*INSERT*/ such that on executing Test
class, 120 is printed in the output?
NOTE: 120 is the multiplication of numbers from 1 to 5.

Select 2 options. 


System.out.println(stream.reduce(res, (i, j) -> i * j));  
(Correct)


System.out.println(stream.reduce(1, (i, j) -> i * j));  
(Correct)


System.out.println(stream.reduce(0, Integer::multiply));  


System.out.println(stream.reduce(1, Integer::multiply));  


System.out.println(stream.reduce(0, (i, j) -> i * j));  

Explanation
Integer class doesn't have 'multiply' method, hence options containing
'Integer::multiply' will cause compilation failure.

To understand, 'stream.reduce(1, (i, j) -> i * j)' can be written as:

int result = 1;
for (int element : stream) {
result = op.applyAsInt(result, element);
}
return result;

Above code is just for understanding purpose, you can't iterate a stream using given
loop.

Note: 'op' in above code is of IntBinaryOperator and target type of given lambda
expression.

Check IntPipeline class which implements IntStream for the details of reduce method.

If 1st argument of reduce is 0, then overall result will be zero.

'stream.reduce(1, (i, j) -> i * j)' and 'stream.reduce(res, (i, j) -> i * j)' are correct
options.

Question 54: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.Map;
4. import java.util.TreeMap;
5.  
6. public class Test {
7. public static void main(String[] args) throws Exception {
8. Map<Integer, String> map = new TreeMap<>();
9. map.put(1, "one");
10. map.put(2, "two");
11. map.put(3, "three");
12. map.put(null, "null");
13. map.forEach((key, value) -> System.out.println("{" + key + ": " + value +
"}"));
14. }
15. }

What will be the result of compiling and executing Test class?



{1: one}
{2: two}
{3: three}


{1: one}
{2: two}
{3: three}
{null: null}


{null: null}
{1: one}
{2: two}
{3: three}


NullPointerException is thrown at runtime
(Correct)

Explanation
TreeMap cannot contain null keys.

Hence, 'map.put(null, "null");' throws NullPointerException.

Question 55: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.SQLException;
6. import java.sql.Statement;
7.  
8. public class Test {
9. public static void main(String[] args) throws SQLException {
10. Connection connection = null;
11. try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ocp", "root",
"password");)
12. {
13. connection = con;
14. }
15. Statement stmt = connection.createStatement();
16. stmt.executeUpdate("INSERT INTO EMPLOYEE VALUES(101, 'John', 'Smith',
12000)");
17. stmt.close();
18. connection.close();
19. }
20. }

Also assume: 
URL, username and password are correct.
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 result of compiling and executing Test class?


The program executes successfully but no record is inserted in the EMPLOYEE
table


An exception is thrown at runtime
(Correct)


Compilation error


The program executes successfully and one record is inserted in the EMPLOYEE
table

Explanation
Connection object is created inside try-with-resources statement. Both 'connection'
and 'con' refer to the same Connection object.

con.close() method is invoked implicitly just before the closing bracket of try-with-
resources statement.

connection.createStatement(); throws exception at runtime as no operations are


allowed on closed Connection.

Question 56: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. IntStream stream = "OCP".chars();
8. stream.forEach(c -> System.out.print((char)c));
9. System.out.println(stream.count()); //Line 9
10. }
11. }

What will be the result of compiling and executing Test class?



Runtime exception
(Correct)


None of the other options


Compilation error


OCP3

Explanation
forEach, count, toArray, reduce, collect, findFirst, findAny, anyMatch, allMatch, sum,
min, max, average etc. are considered as terminal operations.

Once the terminal operation is complete, all the elements of the stream are
considered as used.

Any attempt to use the stream again causes IllegalStateException.

In this example, count() is used after using forEach() method and hence
IllegalStateException is thrown.

Question 57: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<? super String> list = new ArrayList<>();
9. list.add("A");
10. list.add("B");
11. for(String str : list) {
12. System.out.print(str);
13. }
14. }
15. }

What will be the result of compiling and executing Test class?



AB


Compilation error
(Correct)


Runtime exception

Explanation
For 'List<? super String>' type of read objects is 'Object' and type of write objects is
'String' and its subclasses (no subclass of String as String is final).

'for(String str : list)' causes compilation failure.

Correct syntax should be: 'for(Object str : list)'

Question 58: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.LocalTime;
4. import java.time.temporal.ChronoUnit;
5.  
6. public class Test {
7. public static void main(String [] args) {
8. LocalTime t1 = LocalTime.parse("11:03:15.987");
9. System.out.println(t1.plus(22, ChronoUnit.HOURS)
10. .equals(t1.plusHours(22)));
11. }
12. }

What will be the result of compiling and executing Test class?



false


true
(Correct)


Runtime Exception

Explanation
Definition of plus method is: 'public LocalDate plus(long amountToAdd,
TemporalUnit unit) {...}'.   

TemporalUnit is mentioned in exam objectives and it is being used as method


parameters in date time API. enum ChronoUnit implements this interface and it is
used at various places in the API.

One such use as an argument in plus and minus methods of LocalDate,


LocalDateTime and LocalTime classes.

t1.plus(22, ChronoUnit.HOURS) is same as t1.plusHours(22).

If you check the code of plus(long, TemporalUnit), you will find that it calls
plusSeconds, plusMinutes, plusHours etc based on the passed enum value.
'ChronoUnit.HOURS' is passed in this case, hence t1.plus(22, ChronoUnit.HOURS)
invokes t1.plusHours(22).

Question 59: Skipped
Below is the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class Outer {
4. abstract static class Animal { //Line 2
5. abstract void eat();
6. }
7.
8. static class Dog extends Animal { //Line 6
9. void eat() { //Line 7
10. System.out.println("Dog eats biscuits");
11. }
12. }
13. }
14.  
15. public class Test {
16. public static void main(String[] args) {
17. Outer.Animal animal = new Outer.Dog(); //Line 15
18. animal.eat();
19. }
20. }

What will be the result of compiling and executing Test class?



Compilation error at Line 7

Compilation error at Line 2


Compilation error at Line 15


Compilation error at Line 6


Dog eats biscuits
(Correct)

Explanation
A class can have multiple static nested classes. static nested class can use all 4 access
modifiers (public, protected, default and private) and 2 non-access modifiers (final
and abstract). No issues at Line 2.

static nested class can extend from a class and can implement multiple interfaces so
Line 6 compiles fine. No overriding rules were broken while overriding eat() method,
so no issues at Line 7.

Test class is outside the boundary of class Outer. So Animal can be referred by
Outer.Animal and Dog can be referred by Outer.Dog.

Polymorphism is working in this case, super class (Outer.Animal) reference variable is


referring to the instance of sub class (Outer.Dog). So, no issues at Line 15 as well.

Test class compiles and executes successfully and prints "Dog eats biscuits" on to the
console.

Question 60: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4. import java.time.LocalDate;
5. import java.util.Optional;
6.  
7. public class Test {
8. public static void main(String[] args) throws IOException,
ClassNotFoundException {
9. Optional<LocalDate> optional = Optional.of(LocalDate.of(2018, 12, 1));
10. try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(("F:\\date.ser")));
11. ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("F:\\date.ser")))
12. {
13. oos.writeObject(optional);
14.  
15. Optional<?> object = (Optional<?>)ois.readObject();
16. System.out.println(object.get());
17. }
18. }
19. }

F: is accessible for reading/writing and currently doesn't contain any files/directories. 

What will be the result of compiling and executing Test class?


01-12-2018


2018-12-01


Runtime Exception
(Correct)


Compilation error

Explanation
There is no compilation error in this code.

Optional class doesn't implement Serializable interface, hence


'oos.writeObject(optional);' throws exception at runtime.

Question 61: Skipped
Given:
1. package com.udayan.ocp;
2.  
3. import java.util.function.Supplier;
4.  
5. class Document {
6. void printAuthor() {
7. System.out.println("Document-Author");
8. }
9. }
10.  
11. class RFP extends Document {
12. @Override
13. void printAuthor() {
14. System.out.println("RFP-Author");
15. }
16. }
17.  
18. public class Test {
19. public static void main(String[] args) {
20. check(Document::new);
21. check(RFP::new);
22. }
23.
24. private static void check(______________ supplier) {
25. supplier.get().printAuthor();
26. }
27. }

Given options to fill the blanks:

1. Supplier<Document>
2. Supplier<? extends Document>
3. Supplier<? super Document>
4. Supplier<RFP>
5. Supplier<? extends RFP>
6. Supplier<? super RFP>
7. Supplier

How many of the above options can fill the blank space, such that output is:

Document-Author

RFP-Author


Only three options


More than three options


Only two options
(Correct)


Only one option

Explanation
Blank space of check(______________ supplier) method needs to be filled such that
check(...) method compiles, two statements invoking check(...) method compile and
output is:

Document-Author

RFP-Author
'Document::new' is same as '() -> {return new Document();}' and 'RFP::new' is same as
'() -> {return new RFP();}' and as these are the implementations of get method of
Supplier interface, hence let's check all the options one by one:

1. Supplier<Document>:- Method parameter will be initialized as:

Supplier<Document> supplier = () -> {return new Document();};

or

Supplier<Document> supplier = () -> {return new RFP();};

No issues as get() method either returns Document or RFP instance.

2. Supplier<? extends Document>:- Method parameter will be initialize as:

Supplier<? extends Document> supplier = () -> {return new Document();};

or

Supplier<? extends Document> supplier = () -> {return new RFP();};

If target type is a wildcard-parameterized functional interface, then type inference of


lambda expression is based on following from the JLS:

If T is a wildcard-parameterized functional interface type and the lambda expression


is implicitly typed, then the ground target type is the non-wildcard parameterization
of T.

Based on above JLS statement, ground target type of above lambda expression will
be: Supplier<Document> and this means above expression is equivalent to:

Supplier<? extends Document> supplier = (Supplier<Document>)() -> {return new


Document();};

or

Supplier<? extends Document> supplier = (Supplier<Document>)() -> {return new


RFP();};
No issues as get() method either returns Document or RFP instance.

3. Supplier<? super Document>:- Method parameter will be initialize as:

Supplier<? super Document> supplier = () -> {return new Document();};

or

Supplier<? super Document> supplier = () -> {return new RFP();};

Based on above JLS statement, ground target type of above lambda expression will
be: Supplier<Document> and this means above expression is equivalent to:

Supplier<? super Document> supplier = (Supplier<Document>)() -> {return new


Document();};

or

Supplier<? super Document> supplier = (Supplier<Document>)() -> {return new


RFP();};

There is no issue with lambda expressions (method invocation) but get() method
would return an Object type and invoking printAuthor() method on Object type is
not possible. Hence compilation error.

4. Supplier<RFP>:- Method parameter will be initialized as:

Supplier<RFP> supplier = () -> {return new Document();};

or

Supplier<RFP> supplier = () -> {return new RFP();};

1st statement causes compilation failure.

5. Supplier<? extends RFP>:- Method parameter will be initialized as:

Supplier<? extends RFP> supplier = () -> {return new Document();};

or
Supplier<? extends RFP> supplier = () -> {return new RFP();};

Based on above JLS statement, ground target type of above lambda expression will
be: Supplier<RFP> and this means above expression is equivalent to:

Supplier<? extends RFP> supplier = (Supplier<RFP>)() -> {return new Document();};

or

Supplier<? extends RFP> supplier = (Supplier<RFP>)() -> {return new RFP();};

2nd statement compiles successfully but 1st statement fails to compile.

6. Supplier<? super RFP>:- Method parameter will be initialized as:

Supplier<? super RFP> supplier = () -> {return new Document();};

or

Supplier<? super RFP> supplier = () -> {return new RFP();};

Based on above JLS statement, ground target type of above lambda expression will
be: Supplier<RFP> and this means above expression is equivalent to:

Supplier<? super RFP> supplier = (Supplier<RFP>)() -> {return new Document();};

or

Supplier<? super RFP> supplier = (Supplier<RFP>)() -> {return new RFP();};

1st statement fails to compile. There is no issue with the lambda expression of 2nd
statement (method invocation) but get() method would return an Object type and
invoking printAuthor() method on Object type is not possible. Hence compilation
error.

7. Supplier:- Doesn't compile as raw type's get() method returns Object type, so
printAuthor() method can't be invoked.

Hence out of given 7 options, only two options 'Supplier<Document>' and


'Supplier<? extends Document>' will give the desired output.
Question 62: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.function.BiPredicate;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String [] arr = {"A", "ab", "bab", "Aa", "bb", "baba", "aba", "Abab"};
8. BiPredicate<String, String> predicate = String::startsWith;
9.  
10. for(String str : arr) {
11. if(predicate.negate().test(str, "A"))
12. System.out.println(str);
13. }
14. }
15. }

What will be the result of compiling and executing Test class? 



A
Aa
Abab


ab
aba


ab
bab
bb
baba
aba
(Correct)


bab
bb
baba

Explanation
startsWith is an instance method in String class. 'String::startsWith' corresponds to
'(str1, str2) -> str1.startsWith(str2);'

Given predicate means return true for any text starting with uppercase 'A'.
But inside for loop predicate.negate() means, return true for any text not starting
with uppercase 'A'.

Question 63: Skipped
Given code: 
1. package com.udayan.ocp;
2.  
3. class Outer {
4. private String name = "James Gosling";
5. //Insert inner class definition here
6. }
7.  
8. public class Test {
9. public static void main(String [] args) {
10. new Outer().new Inner().printName();
11. }
12. }

Which of the following Inner class definition inserted in the Outer class, will print
'James Gosling' in the output on executing Test class?

1. class Inner {
2. public void printName() {
3. System.out.println(this.name);
4. }
5. }


1. inner class Inner {
2. public void printName() {
3. System.out.println(name);
4. }
5. }


1. abstract class Inner {
2. public void printName() {
3. System.out.println(name);
4. }
5. }


1. class Inner {
2. public void printName() {
3. System.out.println(name);
4. }
5. }

(Correct)

Explanation
name can be referred either by name or Outer.this.name. There is no keyword with
the name 'inner' in java.

As new Inner() is used in main method, hence cannot declare class Inner as abstract
in this case. But note abstract or final can be used with regular inner classes.
Keyword 'this' inside Inner class refers to currently executing instance of Inner class
and not the Outer class.

To access Outer class variable from within inner class you can use these 2 statements:

System.out.println(name);

OR

System.out.println(Outer.this.name);

Question 64: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class MyException extends RuntimeException {}
4.  
5. class YourException extends RuntimeException {}
6.  
7. public class Test {
8. public static void main(String[] args) {
9. try {
10. throw new YourException();
11. } catch(MyException e1 | YourException e2){
12. System.out.println("Caught");
13. }
14. }
15. }

What will be the result of compiling and executing Test class?



Caught


Runtime Exception


Compilation error
(Correct)

Explanation
Wrong syntax for multi-catch block, only one reference variable is allowed.

Correct syntax of multi-catch statement is: 'catch(MyException | YourException e)'

Question 65: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class Player extends Thread {
6. CyclicBarrier cb;
7.
8. public Player(){
9. super();
10. }
11.  
12. public Player(CyclicBarrier cb) {
13. this.cb = cb;
14. this.start();
15. }
16.  
17. public void run() {
18. try {
19. cb.await();
20. } catch (InterruptedException | BrokenBarrierException e) {}
21. }
22. }
23.  
24. class Match implements Runnable {
25. public void run() {
26. System.out.println("Match is starting...");
27. }
28. }
29.  
30. public class Test {
31. public static void main(String[] args) {
32. Match match = new Match();
33. CyclicBarrier cb = new CyclicBarrier(2, match);
34. Player p1 = new Player(cb);
35. /*INSERT*/
36. }
37. }

Which of the following statement, if used to replace /*INSERT*/, will print 'Match is
starting...' on to the console and will successfully terminate the program?

new Player(cb).start();  


cb.await();  


new Player(cb);  
(Correct)


p1.start();  


new Player();  

Explanation
'new CyclicBarrier(2, match);' means 2 threads must call await() so that Cyclic Barrier
is tripped and barrier action is executed, this means run() method of thread referred
by match is invoked and this will print expected output on to the console. 

'new Player(cb);' assigns passed CyclicBarrier instance to 'cb' property of the Player
class and it also invokes start() method so that this Player thread becomes Runnable.
run() method is invoked later which invokes cb.await() method. 

One more 'cb.await();' call is needed to get the expected output. 

'p1.start();' => Thread referred by p1 is already started in the constructor, calling


start() again throws IllegalThreadStateException. 

'new Player(cb);' => Just like previous statement, it will invoke the await() method on
cb and CyclicBarrier will be tripped. This is correct option. 

'new Player(cb).start();' => 'new Player(cb)' will invoke the await() method on cb and
CyclicBarrier will be tripped. 'Match is starting...' will be printed on to the console. But
calling start() method again throws IllegalThreadStateException and program is not
terminated successfully. 

'cb.await();' => await() method throws 2 checked exceptions: InterruptedException


and BrokenBarrierException and these are not handled in the main method. Hence
this will cause compilation error. If these 2 exceptions are handled inside main, then
this could be one of the correct options.

'new Player();' => No-argument constructor of Player class doesn't assign value to
'cb' and doesn't invoke start() method as well. Hence, it will not have any affect.

Question 66: Skipped
Consider the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. enum Flags {
4. TRUE, FALSE;
5.  
6. Flags() {
7. System.out.println("HELLO");
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. Flags flags = new Flags();
14. }
15. }

What will be the result of compiling and executing Test class?



None of the other options
(Correct)


HELLO is printed once


Exception is thrown at runtime


HELLO is printed twice

Explanation
new Flags() tries to invoke enum constructor but Enum constructor cannot be
invoked.
Question 67: Skipped
Below is the content of 'F:\Message.properties' file:
key1=Good Morning!
key2=Good Evening!

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.FileInputStream;
4. import java.io.IOException;
5. import java.util.Properties;
6.  
7. public class Test {
8. public static void main(String[] args) throws IOException {
9. Properties prop = new Properties ();
10. FileInputStream fis = new FileInputStream ("F:\\Message.properties");
11. prop.load(fis);
12. System.out.println(prop.getProperty("key1"));
13. System.out.println(prop.getProperty("key2", "Good Day!"));
14. System.out.println(prop.getProperty("key3", "Good Day!"));
15. System.out.println(prop.getProperty("key4"));
16. }
17. }

There is full permission to list/create/delete files and directories in F:.


What will be the result of compiling and executing Test class?

Good Morning!
Good Evening!
null
null


Good Morning!
Good Day!
null
null


Good Morning!
Good Evening!
Good Day!
null
(Correct)


Good Morning!
Good Day!
Good Day!
null

Explanation
java.util.Properties extends Hashtable<Object, Object>, which is a map to store key
value pairs.

load method accepts InputStream object and loads the key value pairs (present in
InputStream object) to internal map of Properties class.

There are 2 overloaded versions of getProperty() method:

1. String getProperty(String key) => Returns value of the specified key and null if
value is not found.

2. String getProperty(String key, String defaultValue) => Returns value of the


specified key and defaultValue if value is not found.
'key1' and 'key2' are present in Properties file, so their corresponding values are
returned.

As 'key3' is not present in the Properties file, hence 'prop.getProperty("key3", "Good


Day!")' returns the defaultValue, "Good Day!" and as 'key4' is not present as well,
hence 'prop.getProperty("key4")' returns null.

Question 68: Skipped
Below is the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. interface Flyable {
4. void fly();
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. /*INSERT*/
10. }
11. }

Which of the following options can replace /*INSERT*/ such that there are no
compilation errors?

Flyable flyable = new Flyable(){};  


1. Flyable flyable = new Flyable() {
2. public void fly() {
3. System.out.println("Flying high");
4. }
5. };

(Correct)


1. Flyable flyable = new Flyable() {
2. public void fly() {
3. System.out.println("Flying high");
4. }
5. }


Flyable flyable = new Flyable();  

Explanation
new Flyable(); => Can't instantiate an interface. 

new Flyable(){}; => fly() method is not implemented. 


new Flyable() { public void fly() { System.out.println("Flying high"); } } => semicolon
missing at the end 

new Flyable() { public void fly() { System.out.println("Flying high"); } }; => correct


syntax 

Question 69: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.function.Consumer;
6.  
7. interface StringConsumer extends Consumer<String> {
8. @Override
9. public default void accept(String s) {
10. System.out.println(s.toUpperCase());
11. }
12. }
13.  
14. public class Test {
15. public static void main(String[] args) {
16. StringConsumer consumer = s -> System.out.println(s.toLowerCase());
17. List<String> list = Arrays.asList("Dr", "Mr", "Miss", "Mrs");
18. list.forEach(consumer);
19. }
20. }

What will be the result of compiling and executing Test class?



dr
mr
miss
mrs


Compilation error
(Correct)


DR
MR
MISS
MRS


Runtime exception

Explanation
Target type of lambda expression should be a functional interface.
StringConsumer is not a Functional Interface as it just specifies one default method,
abstract method is not available.

Statement 'StringConsumer consumer = s -> System.out.println(s.toLowerCase());'


causes compilation error.

Question 70: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayDeque;
4. import java.util.Deque;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Deque<Boolean> deque = new ArrayDeque<>();
9. deque.push(new Boolean("abc"));
10. deque.push(new Boolean("tRuE"));
11. deque.push(new Boolean("FALSE"));
12. deque.push(true);
13. System.out.println(deque.pop() + ":" + deque.peek() + ":" + deque.size());
14. }
15. }

What will be the result of compiling and executing Test class?



false:false:3


false:true:3


true:true:3


true:false:3
(Correct)

Explanation
push, pop and peek are Stack's terminology.

push(E) calls addFirst(E), pop() calls removeFirst() and peek() invokes peekFirst(), it
just retrieves the first element (HEAD) but doesn't remove it.

deque.push(new Boolean("abc")); => [*false]. * represents HEAD of the deque. 

deque.push(new Boolean("tRuE")); => [*true, false]. 


deque.push(new Boolean("FALSE")); => [*false, true, false]. 

deque.push(true); => [*true, false, true, false]. 

deque.pop() => removes and returns the HEAD element, true in this case. deque =>
[*false, true, false]. 

deque.peek() => retrieves but doesn't remove the HEAD element, false in this case.
deque => [*false, true, false]. 

deque.size() => 3. 

Hence output is 'true:false:3'.

Question 71: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class Animal {}
4.  
5. class Dog extends Animal {}
6.  
7. class Cat extends Animal {}
8.  
9. class A<T> {
10. T t;
11. void set(T t) {
12. this.t = t;
13. }
14.  
15. T get() {
16. return t;
17. }
18. }
19.  
20. public class Test {
21. public static <T> void print1(A<? extends Animal> obj) {
22. obj.set(new Dog()); //Line 22
23. System.out.println(obj.get().getClass());
24. }
25.  
26. public static <T> void print2(A<? super Dog> obj) {
27. obj.set(new Dog()); //Line 27
28. System.out.println(obj.get().getClass());
29. }
30.  
31. public static void main(String[] args) {
32. A<Dog> obj = new A<>();
33. print1(obj); //Line 33
34. print2(obj); //Line 34
35. }
36. }

What will be the result of compiling and executing Test class?



null
class com.udayan.ocp.Dog


class com.udayan.ocp.Dog
null


Compilation error
(Correct)


Runtime Exception


class com.udayan.ocp.Dog
class com.udayan.ocp.Dog

Explanation
print1(A<? extends Animal> obj) => print1 method can accept arguments of
A<Animal> or A<Dog> or A<Cat> types at runtime.

Suppose you have passed 'new A<Cat>()' as the argument of print1 method. Line 22
will not work in this case.

As compiler is not sure about the data that would come at runtime, hence it doesn't
allow Line 22. Line 22 causes compilation failure.

print2(A<? super Dog> obj) => print2 method can accept arguments of A<Dog> or
A<Animal> or A<Object> types at runtime.

All 3 arguments works with Line 27, hence no issues with Line 27.

Question 72: Skipped
Which of the following statement is correct about java enums?

An enum can extend another class

An enum can implement interfaces
(Correct)


An enum can extend another enum


All java enums implicitly extend from java.util.Enum class

Explanation
Java enums cannot extend from another class or enum but an enum can implement
interfaces.

All java enums implicitly extend from java.lang.Enum class and not from
java.util.Enum class.

Question 73: Skipped
Given structure of MESSAGES table:

MESSAGES (msg1 varchar(100), msg2 varchar(100))  

MESSAGES table contains below records: 


'Happy New Year!', 'Happy Holidays!'

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select msg1 as msg, msg2 as msg FROM MESSAGES";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
13. ResultSet rs = stmt.executeQuery(query);)
14. {
15. rs.absolute(1);
16. System.out.println(rs.getString("msg"));
17. System.out.println(rs.getString("msg"));
18. }
19. }
20. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


Happy New Year!
Happy Holidays!


Happy New Year!
Happy New Year!
(Correct)


An exception is thrown at runtime


Happy Holidays!
Happy Holidays!

Explanation
In the given query, both the column aliases have same name 'msg'.
'rs.getString("msg")' always returns the first matching column.

In case of matching column names, column indexes can be used.

rs.getString(1) would return 'Happy New Year!' and rs.getString(2) would return
'Happy Holidays!'.

Question 74: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 


1. 101 John Smith 12000
2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE WHERE
SALARY > 14900 ORDER BY ID";
11.  
12. try (Connection con = DriverManager.getConnection(url, user, password);
13. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
14. ResultSet rs = stmt.executeQuery(query);) {
15. rs.absolute(2);
16. rs.updateDouble("SALARY", 20000);
17. } catch (SQLException ex) {
18. System.out.println("Error");
19. }
20. }
21. }

Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


'Error' is printed on to the console


Program executes successfully and salary of Regina Williams is updated to 20000


Program executes successfully and salary of Sean Smith is updated to 20000


Program executes successfully but no record is updated in the database
(Correct)

Explanation
Given sql statement returns below records:
102 Sean Smith 15000       

103 Regina Williams 15500

'rs.absolute(2);' moves the cursor pointer to 2nd record.

'rs.updateDouble("SALARY", 20000);' updates the salary of 2nd record to 20000 but


to update the records in the database, 'rs.updateRow();' statement must be invoked.

As 'rs.updateRow()' statement is missing hence no record is updated in the database.

Please note: there is no need to invoke con.commit(); method as by default


Connection object is in auto-commit mode.

Question 75: Skipped
Given structure of MESSAGES table:

MESSAGES (msg1 varchar(100), msg2 varchar(100))  

MESSAGES table contains below records: 


'Happy New Year!', 'Happy Holidays!'

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "DELETE FROM MESSAGES";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt = con.createStatement())
13. {
14. System.out.println(stmt.execute(query));
15. }
16. }
17. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


false
(Correct)


1


true


0

Explanation
execute(String) method of Statement can accept all types of queries. It returns true if
the first result is a ResultSet object; false if it is an update count or there are no
results.

DELETE sql query returns the no. of deleted records, which is not a ResultSet hence
record is deleted from the database and false is returned.

Question 76: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.ListIterator;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<String> list = Arrays.asList("T", "S", "R", "I", "F");
10. ListIterator<String> iter = list.listIterator(2);
11. while(iter.hasNext()) {
12. System.out.print(iter.next());
13. }
14. }
15. }
What will be the result of compiling and executing Test class?

Runtime Exception


IF


RIF
(Correct)

Explanation
listIterator(index); method allows to have the starting point at any index. Allowed
values are between 0 and size of the list.

If next() method is called, then element at 'specified index' is returned and if


previous() method is called, then element at 'specified index - 1' is returned.

Question 77: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class MyResource implements AutoCloseable {
4. @Override
5. public void close() {
6. System.out.println("Closing");
7. }
8. }
9.  
10. public class Test {
11. public static void main(String[] args) {
12. try(AutoCloseable resource = new MyResource()) {
13.  
14. }
15. }
16. }

What will be the result of compiling and executing Test class?



Compilation error in Test class
(Correct)


Closing


Compilation error in MyResource class

Explanation
close() method in AutoCloseable interface has below declaration:
void close() throws Exception;

MyResource class correctly overrides close() method.

try-with-resources statement internally invokes resource.close() method.

resource is of AutoCloseable type, so compiler checks the close() method declaration


of AutoCloseable interface.

close() method in AutoCloseable interface declares to throw Exception (checked


exception) and hence handle or declare rule must be followed.

As main method neither declares to throw Exception nor provides catch block for
Exception type, hence try-with-resources statement causes compilation error.

Question 78: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void convert(String s)
5. throws IllegalArgumentException, RuntimeException, Exception {
6. if(s.length() == 0) {
7. throw new RuntimeException("Length should be greater than 0.");
8. }
9. }
10. public static void main(String [] args) {
11. try {
12. convert("");
13. }
14. catch(IllegalArgumentException | RuntimeException | Exception e) { //Line
14
15. System.out.println(e.getMessage()); //Line 15
16. } //Line 16
17. catch(Exception e) {
18. e.printStackTrace();
19. }
20. }
21. }

Line 14 is giving compilation error. Which of the following changes enables to code
to print 'Length should be greater than 0.'?

Replace Line 14 with  catch(IllegalArgumentException | RuntimeException e) {  


Replace Line 14 with  catch(RuntimeException | Exception e) {  


Comment out Line 14, Line 15 and Line 16


Replace Line 14 with  catch(RuntimeException e) {  
(Correct)


Replace Line 14 with  catch(IllegalArgumentException | Exception e) {  

Explanation
In multi-catch statement, classes with multi-level hierarchical relationship can't be
used.

RuntimeException is subclass of Exception, IllegalArgumentException is indirect


subclass of Exception and IllegalArgumentException is subclass of RuntimeException,
hence these pairs can't be used in multi-catch statement.

Only one option is left to replace Line 14 with 'catch(RuntimeException e) {'.

Commenting out Line 14, Line 15 and Line 16 will resolve the compilation error but it
will print the whole stack trace rather than just printing the message.

Question 79: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. NavigableMap<Integer, String> map = new TreeMap<>();
8. map.put(25, "Pune");
9. map.put(32, "Mumbai");
10. map.put(11, "Sri Nagar");
11. map.put(39, "Chennai");
12.  
13. System.out.println(map.headMap(25, true));
14. }
15. }

{25=Pune, 32=Mumbai, 39=Chennai}


{32=Mumbai, 39=Chennai}


{11=Sri Nagar, 25=Pune}
(Correct)


{11=Sri Nagar}

Explanation
TreeMap is sorted map based on the natural ordering of keys. So, map has entries:
{11=Sri Nagar, 25=Pune, 32=Mumbai, 39=Chennai}. 

headMap(K toKey, boolean inclusive) => returns the map till toKey, if inclusive is
true. Hence the output is: {11=Sri Nagar, 25=Pune}. 

For the exam, you should know some of the methods from NavigableMap map.
Below are the method calls and outputs for the map object used in this example: 

//NavigableMap<K,V> tailMap(K fromKey, boolean inclusive); => Returns a view of


the portion of this map whose keys are greater than (or equal to, if 'inclusive' is true)
fromKey. 

System.out.println(map.tailMap(25, true)); //{25=Pune, 32=Mumbai, 39=Chennai} 

//Map.Entry<K,V> firstEntry(); => Returns a key-value mapping associated with the


least key in this map. 

System.out.println(map.firstEntry()); //11=Sri Nagar 

//Map.Entry<K,V> lastEntry(); => Returns a key-value mapping associated with the


greatest key in this map. 
System.out.println(map.lastEntry()); //39=Chennai 

//NavigableMap<K,V> descendingMap(); => Returns a reverse order view of the


mappings contained in this map. 

System.out.println(map.descendingMap()); //{39=Chennai, 32=Mumbai, 25=Pune,


11=Sri Nagar} 

//K floorKey(K key); => Returns the greatest key less than or equal to the given key. 

System.out.println(map.floorKey(30)); //25 

//K ceilingKey(K key); => Returns the least key greater than or equal to the given
key. 

System.out.println(map.ceilingKey(30)); //32 

Question 80: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. int sum = IntStream.rangeClosed(1,3).map(i -> i * i)
8. .map(i -> i * i).sum();
9. System.out.println(sum);
10. }
11. }

What will be the result of compiling and executing Test class?



98
(Correct)


6


None of the other options


14

Explanation
IntStream.rangeClosed(int start, int end) => Returns a sequential stream from start to
end, both inclusive and with a step of 1.

IntStream.map(IntUnaryOperator) => Returns a stream consisting of the results of


applying the given function to the elements of this stream.

IntStream.rangeClosed(1,3) => [1,2,3]. 

map(i -> i * i) => [1,4,9]. 

map(i -> i * i) => [1,16,81]. 

sum() => 1+16+81 = 98.

Question 81: Skipped
Below files are available for your project:
1. //1. RB.properties
2. key1=one
3. key3=three

1. //2. RB_en.properties
2. key3=THREE

1. //3. RB_en_US.properties
2. key1=ONE
3. key2=TWO

1. //4. Test.java
2. package com.udayan.ocp;
3.  
4. import java.util.Enumeration;
5. import java.util.Locale;
6. import java.util.ResourceBundle;
7.  
8. public class Test {
9. public static void main(String[] args) {
10. Locale loc = new Locale("en", "US");
11. ResourceBundle bundle = ResourceBundle.getBundle("RB", loc);
12. Enumeration<String> enumeration = bundle.getKeys();
13. while (enumeration.hasMoreElements()) {
14. String key = enumeration.nextElement();
15. String val = bundle.getString(key);
16. System.out.println(key + "=" + val);
17. }
18. }
19. }

Assume that all the *.properties files are included in the CLASSPATH. What will be the
output of compiling and executing Test class?

key1=ONE
key2=TWO
key3=THREE
(Correct)


key1=one
key2=TWO
key3=three


key1=ONE
key2=TWO


key1=one
key3=three


key3=THREE

Explanation
If all the files have same keys and locale is en_US, then key-value pair of best match
('RB_en_US.properties') file will be considered.

If the files have different keys and locale is en_US, then key-value pair is searched in
following order:

1. RB_en_US.properties [parent = 'RB_en.properties']

2. RB_en.properties [parent = 'RB.properties']

3. RB.properties [parent = null]


Hence bundle.getKeys(); returns an Enumeration<String> instance containing
("key1", "key2") from 'RB_en_US.properties' file and ("key3") from 'RB_en.properties'
file.

I mentioned parent value abvoe because there is relationship among above 3 files.
RB.properties is the ultimate parent, its child is 'RB_en.properties' and
'RB_en_US.properties is the child of 'RB_en.properties'.

So if I write below codes:

bundle.getString("key1"); value will be taken from 'RB_en_US.properties' file, so it


returns ONE.

bundle.getString("key2"); value will be taken from 'RB_en_US.properties' file, so it


returns ONE.

msgs.getString("key3"); this key is not available in 'RB_en_US.properties' file and


hence it will be searched in its parent 'RB_en.properties'. And because "key3" key is
available in 'RB_en.properties' file, hence it returns THREE.

You can iterate over Enumeration using hasMoreElements() and nextElement()


methods.

Iteration logic prints key-value pair in the order of Enumeration elements ("key1",
"key2", "key3"). Hence output will be:

key1=ONE

key2=TWO

key3=THREE

If you read the javadoc of getKeys(), getString(String) or getObject(String) methods,


then you will find out that these methods work with current resource bundle and its
parent.
Question 82: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. @FunctionalInterface
4. interface I5 {
5. void print();
6. }
7.  
8. public class Test {
9. int i = 100;
10.
11. I5 obj1 = new I5() {
12. int i = 200;
13. public void print() {
14. System.out.println(this.i);
15. }
16. };
17.
18. I5 obj2 = () -> {
19. int i = 300;
20. System.out.println(this.i);
21. };
22.
23. public static void main(String[] args) {
24. Test ques = new Test();
25. ques.obj1.print();
26. ques.obj2.print();
27. }
28. }


100
100


200
100
(Correct)


100
300


200
300

Explanation
Keyword this within anonymous inner class code refers to the instance of anonymous
inner class itself, so this.i in anonymous inner class code is 200. 
Whereas, keyword this within lambda expression refers to the instance of enclosing
class where lambda expression is written, so this.i in lambda expression is 100.

Question 83: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7. import java.util.stream.Stream;
8.  
9. public class Test {
10. public static void main(String[] args) throws IOException {
11. Stream<Path> files =
Files.list(Paths.get(System.getProperty("user.home")));
12. files.forEach(System.out::println);
13. }
14. }

System.getProperty("user.home") returns the HOME directory of the User (Both in


windows and Linux).

What will be the result of compiling and executing Test class?


It will only print the paths of directories and files under HOME directory.
(Correct)


It will only print the paths of files (not directories) under HOME directory.


It will print the paths of files (not directories) under HOME directory and its sub-
directories.


It will print the paths of directories, sub-directories and files under HOME
directory.

Explanation
Files.list(Path) returns the object of Stream<Path> containing all the paths (files and
directories) of current directory. It is not recursive.

For recursive access use overloaded Files.walk() methods.

Question 84: Skipped
Below is the directory structure of "F:/Test" directory:
1. F:.
2. └───Test
3. │ t1.pdf
4. │ t2.pdf
5. │
6. ├───A
7. │ │ a.pdf
8. │ │
9. │ ├───B
10. │ │ │ b.pdf
11. │ │ │
12. │ │ └───M
13. │ │ m.pdf
14. │ │
15. │ ├───C
16. │ │ c.pdf
17. │ │
18. │ └───D
19. │ d.pdf
20. │
21. └───X
22. └───Y
23. │ y.pdf
24. │
25. └───Z
26. z.pdf

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.File;
4. import java.io.IOException;
5.  
6. public class Test {
7. public static void main(String[] args) throws IOException {
8. deleteFiles(new File("F:\\Test"), ".pdf");
9. }
10.  
11. public static void deleteFiles(File dir, String extension) throws IOException {
12. File[] list = dir.listFiles();
13. if (list != null && list.length > 0) {
14. for (File file : list) {
15. if (file.isDirectory()) {
16. deleteFiles(file, extension);
17. } else if (file.getName().endsWith(extension)) {
18. file.delete();
19. }
20. }
21. }
22. }
23. }

There is full permission to list/create/delete files and directories in F:.


What will be the result of compiling and executing Test class?

Only t1.pdf and t2.pdf will get deleted


t1.pdf, t2.pdf and all the pdf files under 'X' and its sub-directories will be deleted
successfully

Only t1.pdf and t2.pdf will not get deleted, other pdf files will be successfully
deleted


All the pdf files in 'Test' directory and its sub-directories will be deleted
successfully
(Correct)


t1.pdf, t2.pdf and all the pdf files under 'A' and its sub-directories will be deleted
successfully

Explanation
File is used to represent both File and Directory.

deleteFiles(new File("F:\\Test"), ".pdf"); => A java file object referring to 'F:\Test' is


created and on method call variable 'dir' refers to it.

dir.listFiles() method returns an File [], this contains the list of immediate files and
directories.

NOTE: listFiles() method returns File[] and list() method returns String [].

In this case, array list will have 4 File objects: [{F:\Test\t1.pdf},{F:\Test\t2.pdf},


{F:\Test\A},{F:\Test\X}].

for loop iterates through each File object and if the File object is a Directory, then it
recursively invokes deleteFiles method.

file.isDirectory() method checks if the file object is a File or Directory?


file.getName() returns the name (not the full path) of the file object (such as 't1.pdf',
't2.pdf', 'A' etc.).

file.delete() deletes the actual file from the disk.

Question 85: Skipped
Given code:
1. package com.udayan.ocp;
2.  
3. class A {
4. public void someMethod(final String name) {
5. /*INSERT*/ {
6. void print() {
7. System.out.println("Hello " + name);
8. }
9. }
10. new B().print();
11.
12. }
13. }
14.  
15. public class Test {
16. public static void main(String[] args) {
17. new A().someMethod("World!");
18. }
19. }

Which of the following options can replace /*INSERT*/ such that on executing Test
class, "Hello World!" is displayed in the output?

Select 2 options.


protected class B


public class B


abstract class B


private class B


class B
(Correct)


final class B
(Correct)
Explanation
Method-local inner classes cannot be defined using explicit access modifiers (public,
protected and private) but non-access modifiers: final and abstract can be used with
method-local inner class.

In this case, abstract is also not possible as new B() is used.

Question 86: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> list = new ArrayList<>();
9. System.out.println(list.stream().anyMatch(s -> s.length() > 0));
10. System.out.println(list.stream().allMatch(s -> s.length() > 0));
11. System.out.println(list.stream().noneMatch(s -> s.length() > 0));
12. }
13. }

What will be the result of compiling and executing Test class?



false
false
false


false
true
true
(Correct)


true
false
false


true
true
true

Explanation
Method signatures:
boolean anyMatch(Predicate<? super T>) : Returns true if any of the stream element
matches the given Predicate. If stream is empty, it returns false and predicate is not
evaluated. 

boolean allMatch(Predicate<? super T>) : Returns true if all the stream elements
match the given Predicate. If stream is empty, it returns true and predicate is not
evaluated. 

boolean noneMatch(Predicate<? super T>) : Returns true if none of the stream


element matches the given Predicate. If stream is empty, it returns true and predicate
is not evaluated. 

In this case, as stream is empty anyMatch returns false, whereas allMatch and
noneMatch both returns true.

Question 87: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.stream.Collectors;
6.  
7. class Book {
8. String title;
9. String author;
10. double price;
11.
12.     public Book(String title, String author, double price) {
13. this.title = title;
14. this.author = author;
15. this.price = price;
16. }
17.
18.     public String getAuthor() {
19. return this.author;
20. }
21.
22.     public String toString() {
23. return "{" + title + "," + author + "," + price + "}";
24. }
25. }
26.
27. public class Test {
28. public static void main(String[] args) {
29. List<Book> books = Arrays.asList(
30. new Book ("Head First Java", "Kathy Sierra", 24.5),
31. new Book ("OCP", "Udayan Khattry", 20.99),
32. new Book ("OCA", "Udayan Khattry", 14.99));
33. books.stream().collect(Collectors.groupingBy(Book::getAuthor))
34. .forEach((a,b) -> System.out.println(a));
35. }
36. }

What will be the result of compiling and executing Test class?



Kathy Sierra
Udayan Khattry
(Correct)


[{Head First Java,Kathy Sierra,24.5}]
[{OCP,Udayan Khattry,20.99}, {OCA,Udayan Khattry,14.99}]


Runtime Exception

Explanation
books --> [{Head First Java,Kathy Sierra,24.5}, {OCP,Udayan Khattry,20.99},
{OCA,Udayan Khattry,14.99}]. Ordered by insertion order. 

books.stream() returns Stream<Book> type: [{Head First Java,Kathy Sierra,24.5},


{OCP,Udayan Khattry,20.99}, {OCA,Udayan Khattry,14.99}]. 

books.stream().collect(Collectors.groupingBy(Book::getAuthor)) returns a
Map<String, List<Book>> type, key is the author name and value is the List of book
objects.

map --> [{Kathy Sierra, {Head First Java,Kathy Sierra,24.5}}, {Udayan Khattry,
{{OCP,Udayan Khattry,20.99}, {OCA,Udayan Khattry,14.99}}}]. 

forEach method accepts a BiConsumer<String, List<Book>> , so first parameter of


accept method is key and 2nd parameter is value. So in the given lambda expression
'a' is key and 'b' is value. 

System.out.println(a) prints keys(author names) to the console. 


Question 88: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void checkStatus() {
5. assert 1 == 2 : 2 == 2;
6. }
7.  
8. public static void main(String[] args) {
9. try {
10. checkStatus();
11. } catch (AssertionError ae) {
12. System.out.println(ae.getCause());
13. }
14. }
15. }

What will be the result of executing Test class with below command? 
java -ea com.udayan.ocp.Test

null
(Correct)


false


true


Compilation error

Explanation
assert 1 == 2 : 2 == 2; => throws AssertionError and as 2 == 2 is true, hence
message is set as true.

This doesn't make any changes to cause, which is still null.

If right side of the expression is an instance of Throwable type, then cause is set to
that type.

main method catches AssertionError (though you are not supposed to handle Error
and its subtype) and 'ae.getCause()' returns null.
Question 89: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.Console;
4. import java.util.Optional;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Optional<Console> optional = Optional.ofNullable(System.console());
9. if(optional.isPresent()) {
10. System.out.println(optional.get());
11. }
12. }
13. }

Which of the following statement are correct regarding above code?



Above code will never throw NullPointerException.
(Correct)


Above code may throw NullPointerException.


Above code will always print some output on to the console.

Explanation
Two cases are possible:

1. If JVM is associated with the Console (such as running above code from command
prompt/window):

System.console() will return the Console object, optional.isPresent() will return true
and System.out.println(optional.get()); will print the Console reference (such as
java.io.Console@48140564).

2. If JVM is not associated with the Console (such as running above code from an IDE
or online):

System.console() will return null and Optional.ofNullable(System.console()); returns


an EMPTY Optional.

For EMPTY optional, optional.isPresent() returns false and


System.out.println(optional.get()); will not get executed. So you may not get any
output in this case.
In both the cases, optional reference will always refer to some Optional object and
will never be null. NullPointerException can't be thrown by calling methods on
optional reference.

Question 90: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. try (FileInputStream fis = new FileInputStream("F:\\orig.png");
8. FileOutputStream fos = new FileOutputStream("F:\\copy.png")) {
9. int res;
10. byte [] arr = new byte[500000]; //Line 10
11. while((res = fis.read(arr)) != -1){ //Line 11
12. fos.write(arr); //Line 12
13. }
14. }
15. }
16. }

F: is accessible for reading/writing and contains 'orig.png' file. 

Will above code create exact copy of 'orig.png' file?


Yes


No
(Correct)

Explanation
It is very interesting question and frequently asked in interviews as well.

Initially length of arr is 500000 and all the elements are initialized with 0.

There are 2 options: 

1. 'orig.png' file's size is way less than 500000, say 100000 bytes only. This means
only 100000 array elements will be replaced and rest will remain 0.

fos.write(arr); => Writes whole array to the stream/file, which means along with
100000 data bytes 400000 extra bytes will also be written. In this case above code
can't produce exact copy. 
2. 'copy.png' file's size is not multiple of 500000, say 700000 bytes only.

1st invocation of 'fis.read(arr)' will populate all 500000 elements with data and
'fos.write(arr);' will correctly write first 500000 bytes to 'copy.png' file.

2nd invocation of 'fis.read(arr)' will replace 200000 elements with remaining data and
leaving 300000 with the data read from previous read operation. This means
'fos.write(arr);' on 2nd invocation will write 300000 extra bytes. So for this case as
well, above code cannot produce exact copy.

Solution is very simple. Use the overloaded version of write method.

res stores the number of bytes read into the arr. So to get exact copy replace line 12
with 'fos.write(arr, 0, res)'.

Practice Test 2 - Results

 Return to review

Attempt 1
All knowledge areas
All questions
Question 1: Skipped
Consider the code of Greet.java file:
1. package com.udayan.ocp;
2.  
3. public final class Greet {
4. private String msg;
5. public Greet(String msg) {
6. this.msg = msg;
7. }
8.  
9. public String getMsg() {
10. return msg;
11. }
12.  
13. public void setMsg(String msg) {
14. this.msg = msg;
15. }
16. }
Is Greet class an immutable class?

Yes


No
(Correct)

Explanation
Immutable class should have private fields and no setters.

In this case it is possible to change the msg after an instance of Greet class is created.
Check below code:

public class Test {


public static void main(String[] args) {
Greet greet = new Greet("Hello"); //msg refers to "Hello"
greet.setMsg("Welcome"); //msg refers to "Welcome"
System.out.println(greet.getMsg()); //Prints "Welcome" on to the
console.
}
}

To make Greet class immutable, delete the setter and add modifier 'final' for variable
msg.

final class Greet {


private final String msg;
public Greet(String msg) {
this.msg = msg;
}

public String getMsg() {


return msg;
}
}

Once value is assigned to msg variable in the constructor, it cannot be changed later.
Question 2: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.function.Consumer;
6.  
7. interface StringConsumer extends Consumer<String> {
8. @Override
9. public default void accept(String s) {
10. System.out.println(s.toUpperCase());
11. }
12. }
13.  
14. public class Test {
15. public static void main(String[] args) {
16. StringConsumer consumer = new StringConsumer() {
17. @Override
18. public void accept(String s) {
19. System.out.println(s.toLowerCase());
20. }
21. };
22. List<String> list = Arrays.asList("Dr", "Mr", "Miss", "Mrs");
23. list.forEach(consumer);
24. }
25. }

What will be the result of compiling and executing Test class?



dr
mr
miss
mrs
(Correct)


Runtime exception


DR
MR
MISS
MRS


Compilation error

Explanation
list is of List<String> type, so list.forEach(...) method can accept argument of
Consumer<String> type.
interface StringConsumer extends Consumer<String>, which means instances of
StringConsumer will also be instances of Consumer<String>.

Note: StringConsumer is not a Functional Interface as it just specifies one default


method. 

Reference variable 'consumer' refers to an instance of anonymous subclass of


StringConsumer and overrides accept(String) method.

list.forEach(consumer); => Prints list elements in lower case as overriding version of


anonymous inner class is used.

Question 3: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.LinkedHashMap;
4. import java.util.Map;
5. import java.util.function.BiConsumer;
6. import java.util.function.BiFunction;
7.  
8. public class Test {
9. public static void main(String[] args) {
10. Map<Integer, Integer> map = new LinkedHashMap<>();
11. map.put(1, 10);
12. map.put(2, 20);
13. BiConsumer<Integer, Integer> consumer = (k, v) -> {
14. System.out.println(k + ":" + v);
15. };
16.
17. BiFunction<Integer, Integer, Integer> function = (k, v) -> {
18. System.out.println(k + ":" + v);
19. return null;
20. };
21. //Line n1
22. }
23. }

Which of the following options will replace //Line n1 such that below output is
printed to the console?

1:10

2:20


map.forEach(consumer);
(Correct)


map.forEachOrdered(function);


map.forEach(function);


map.forEachOrdered(consumer);

Explanation
In JDK 1.8, Map interface had added the default method: "default void
forEach(BiConsumer)".

This method performs the BiConsumer action (passed as an argument) for each entry
in the Map. From the given options, 'map.forEach(consumer);' is the only valid
option.

There is no method with the name 'forEachOrdered' in Map interface.

Question 4: Skipped
Given structure of LOG table: 

LOG (ID integer, MESSAGE varchar(1000), PRIMARY KEY (ID))  

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, MESSAGE FROM LOG";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
13. ) {
14. stmt.executeUpdate("INSERT INTO LOG VALUES(1001, 'Login Successful')");
15. stmt.executeUpdate("INSERT INTO LOG VALUES(1002, 'Login Failure')");
16.  
17. con.setAutoCommit(false);
18.  
19. stmt.executeUpdate("INSERT INTO LOG VALUES(1003, 'Not Authorized')");
20. }
21. }
22. }

Also assume: 
URL, username and password are correct. 
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.
LOG table doesn't have any records.

What will be the result of compiling and executing Test class?


Records for IDs 1001 and 1002 will be successfully inserted in the database table
(Correct)


No records will be inserted in the database table


Records for IDs 1001, 1002 and 1003 will be successfully inserted in the database
table


Records for ID 1003 will be successfully inserted in the database table

Explanation
According to javadoc of java.sql.Connection, "By default a Connection object is in
auto-commit mode, which means that it automatically commits changes after
executing each statement. If auto-commit mode has been disabled, the method
commit must be called explicitly in order to commit changes; otherwise, database
changes will not be saved".

First 2 executeUpdate(...) method invocation inserts the records in the database table.
So records for IDs 1001 and 1002 are available in the database table. 

After that 'con.setAutoCommit(false);' is invoked which disables the auto-commit


mode. The next stmt.executeUpdate(...) statement doesn't commit the row in the
database unless 'con.commit();' OR 'con.setAutoCommit(true);' is invoked.

Record for ID 1003 is not committed to the database table.


Question 5: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> list1 = new ArrayList<>();
9. list1.add("A");
10. list1.add("B");
11.  
12. List<? extends Object> list2 = list1;
13. list2.remove("A"); //Line 13
14. list2.add("C"); //Line 14
15.  
16. System.out.println(list2);
17. }
18. }

What will be the result of compiling and executing Test class?



Runtime exception


Compilation error
(Correct)


ABC


BC

Explanation
list1 is of List<String> type and contains 2 elements "A" and "B". 

list2 is of List<? extends Object> type, which means any List whose type extends
from Object. As String extends Object, hence 'List<? extends Object> list2 = list1;'
works.

list2.remove("A"); => remove is non-generic method. remove(Object) will be invoked


and it will successfully remove "A" from list2.
list2.add("C"); => add is a generic method. add(? extends Object) would be invoked.
This means it can take an instance of any UnknownType (extending from Object
class).

Compiler can never be sure whether passed argument is a subtype of UnknownType


(extending from Object class). Line 14 causes compilation failure.

NOTE: Compiler works with reference types and not instances.

Simple way to remember is that as upper-bounded wildcard is used, hence add


operation is not supported. Line 14 causes compilation failure.

Question 6: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class Resource1 implements AutoCloseable {
4. public void m1() throws Exception {
5. System.out.print("A");
6. throw new Exception("B");
7. }
8.  
9. public void close() {
10. System.out.print("C");
11. }
12. }
13.  
14. class Resource2 implements AutoCloseable {
15. public void m2() {
16. System.out.print("D");
17. }
18.  
19. public void close() throws Exception {
20. System.out.print("E");
21. }
22. }
23.  
24. public class Test {
25. public static void main(String[] args) {
26. try (Resource1 r1 = new Resource1();
27. Resource2 r2 = new Resource2()) {
28. r1.m1();
29. r2.m2();
30. } catch (Exception e) {
31. System.out.print(e.getMessage());
32. }
33. }
34. }

What will be the result of compiling and executing Test class?



ABEC

ABCE


ACEB


Compilation error


AECB
(Correct)

Explanation
AutoCloseable interface has abstract method: void close() throws Exception; 

Both Resource1 and Resource2 implement the close() method correctly and main
method specified handler for Exception type, hence no compilation error.

Resources are always closes, even in case of exceptions. And in case of multiple
resources, these are closed in the reverse order of their declaration. So r2 is closed
first and then r1. Output will have 'EC' together.

r1.m1(); prints 'A' on to the console. An exception (with message 'B') is thrown so
close methods are invoked. 

After close() methods of r2 and r1 are invoked successfully, output will be: 'AEC'. 

Exception is caught in main method and e.getMessage() returns 'B'.

So the overall output will be; 'AECB'.

Question 7: Skipped
Fill in the blanks:
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. public class Task extends _______________ {
6. @Override
7. protected Long compute() {
8. return null;
9. }
10. }

Select 3 options.

RecursiveAction<Object>


RecursiveAction


RecursiveTask
(Correct)


RecursiveTask<Object>
(Correct)


RecursiveAction<Long>


RecursiveTask<Long>
(Correct)

Explanation
RecursiveTask is a generic class which extends from ForkJoinTask<V> class. 

RecursiveTask<V> declares compute() method as: 'protected abstract V compute();' 

In the given code overriding method returns Long, so classes from which class Task
can extend are: RecursiveTask<Long>, RecursiveTask<Object> [co-variant return
type in overriding method] and RecursiveTask [co-variant return type in overriding
method].

RecursiveAction is a non-generic class which extends from ForkJoinTask<Void> class.

RecursiveAction declared compute() method as: 'protected abstract void compute();'

In the given code overriding method returns Long, hence RecursiveAction can't be
used as super class of Task.
Question 8: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. enum TrafficLight {
6. RED, YELLOW, GREEN
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. Map<TrafficLight, String> map = new TreeMap<>();
12. map.put(TrafficLight.GREEN, "GO");
13. map.put(TrafficLight.RED, "STOP");
14. map.put(TrafficLight.YELLOW, "READY TO STOP");
15.  
16. for(String msg : map.values()) {
17. System.out.println(msg);
18. }
19. }
20. }

What will be the result of compiling and executing Test class?



STOP
READY TO STOP
GO
(Correct)


GO
STOP
READY TO STOP


Printing order cannot be predicted.


GO
READY TO STOP
STOP

Explanation
TreeMap is the sorted map on the basis on natural ordering of keys (if comparator is
not provided). 

enum TrafficLight is used as a key for TreeMap.


The natural order for enum elements is the sequence in which they are defined.
Value corresponding to 'RED' is printed first, followed by value corresponding to
'YELLOW' and finally value for 'GREEN' is printed.

Question 9: Skipped
Daylight saving time 2018 in United States (US) ends at 4-Nov-2018 2:00 AM. 
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date = LocalDate.of(2018, 11, 4);
8. LocalTime time = LocalTime.of(1, 59, 59);
9. ZonedDateTime dt = ZonedDateTime.of(date, time,
ZoneId.of("America/New_York"));
10. dt = dt.plusSeconds(1);
11. System.out.println(dt.getHour() + ":" + dt.getMinute() + ":" +
dt.getSecond());
12. }
13. }


1:0:0
(Correct)


2:0:0


3:0:0

Explanation
You should be aware of Day light saving mechanism to answer this question. 

Suppose daylight time starts at 2 AM on particular date. 

Current time: 1:59:59 [Normal time]. 

Next second: 3:00:00 [Time is not 2:00:00 rather it is 3:00:00. It is Daylight saving
time]. 

Clock just jumped from 1:59:59 to 3:00:00. 

Now Suppose daylight time ends at 2 AM on particular date. 

Current time: 1:59:59 [Daylight saving time]. 


Next second:  1:00:00 [Time is not 2:00:00 rather it is 1:00:00. Clock switched back to
normal time].

Clock just went back from 1:59:59 to 1:00:00. 

Now let's solve given code:

dt --> {2018-11-04T01:59:59}. Daylight saving time will end at next second.

dt.plusSeconds(1) => creates a new ZonedDateTime object {2018-11-04T01:00:00}


and dt refers to it.

dt.getHour() = 1, dt.getMinute() = 0 and dt.getSecond() = 0.

Question 10: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5. import java.util.concurrent.CopyOnWriteArrayList;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<String> list1 = new ArrayList<>();
10. list1.add("Melon");
11. list1.add("Apple");
12. list1.add("Banana");
13. list1.add("Mango");
14. List<String> list2 = new CopyOnWriteArrayList<>(list1);
15. for(String s : list2) {
16. if(s.startsWith("M")){
17. list2.remove(s);
18. }
19. }
20. System.out.println(list1);
21. System.out.println(list2);
22. }
23. }

What will be the result of compiling and executing Test class?



[Melon, Apple, Banana, Mango]
[Apple, Banana]
(Correct)


[Melon, Apple, Banana, Mango]
[Melon, Apple, Banana, Mango]


[Apple, Banana]
[Apple, Banana]


An exception is thrown at runtime

Explanation
'new CopyOnWriteArrayList<>(list1);' creates a thread-safe list containing the
elements of list1. list1 and list2 are not linked, hence changes made to one list
doesn't affect other list. 

CopyOnWriteArrayList allows add/set/remove while iterating through the list. On


every modification, a fresh copy of underlying array is created, leaving the iterator
object unchanged.

'Melon' and 'Mango' are deleted from list2. 

list1 refers to [Melon, Apple, Banana, Mango] and list2 refers to [Apple, Banana].

Question 11: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.Map;
6. import java.util.stream.Collectors;
7.  
8. enum Color {
9. RED, YELLOW, GREEN
10. }
11.  
12. class TrafficLight {
13. String msg;
14. Color color;
15.  
16. TrafficLight(String msg, Color color) {
17. this.msg = msg;
18. this.color = color;
19. }
20.  
21. public String getMsg() {
22. return msg;
23. }
24.  
25. public Color getColor() {
26. return color;
27. }
28.  
29. public String toString() {
30. return "{" + color + ", " + msg + "}";
31. }
32. }
33.  
34. public class Test {
35. public static void main(String[] args) {
36. TrafficLight tl1 = new TrafficLight("Go", Color.GREEN);
37. TrafficLight tl2 = new TrafficLight("Go Now!", Color.GREEN);
38. TrafficLight tl3 = new TrafficLight("Ready to stop", Color.YELLOW);
39. TrafficLight tl4 = new TrafficLight("Slow Down", Color.YELLOW);
40. TrafficLight tl5 = new TrafficLight("Stop", Color.RED);
41.  
42. List<TrafficLight> list = Arrays.asList(tl1, tl2, tl3, tl4, tl5);
43.  
44. Map<Color, List<String>> map = list.stream()
45. .collect(Collectors.groupingBy(TrafficLight::getColor,
46. Collectors.mapping(TrafficLight::getMsg,
Collectors.toList())));
47.  
48. System.out.println(map.get(Color.YELLOW));
49. }
50. }

What will be the result of compiling and executing Test class?



Some text containing @ symbol


[Slow Down]


[Ready to stop, Slow Down]
(Correct)


[Ready to stop]

Explanation
Though it looks like very complex code, but it is simple.

TrafficLight class stores the enum Color and text message to be displayed with the
color.

tl1 --> {GREEN, "Go"}. 

tl2 --> {GREEN, "Go Now!"}. 

tl3 --> {YELLOW, "Ready to stop"}. 

tl4 --> {YELLOW, "Slow Down"}. 


tl5 --> {RED, "Stop"}. 

list.stream() --> [{GREEN, "Go"}, {GREEN, "Go Now!"}, {YELLOW, "Ready to stop"},
{YELLOW, "Slow Down"}, {RED, "Stop"}]. 

Collectors.groupingBy(TrafficLight::getColor, Collectors.mapping(TrafficLight::getMsg,
Collectors.toList())); => Group above stream on the basis of Color (key is enum
constant Color: RED, GREEN, YELLOW).

So, intermediate object returned by 'Collectors.groupingBy(TrafficLight::getColor)' is


of Map<Color, List<TrafficLight>> type. But the 2nd argument,
'Collectors.mapping(TrafficLight::getMsg, Collectors.toList())' passed to groupingBy(...)
method converts List<TrafficLight> to List<String> and returns 'Map<Color,
List<String>>'

map --> {GREEN=[Go, Go Now!], YELLOW=[Ready to stop, Slow Down],


RED=[Stop]}. 

System.out.println(map.get(Color.YELLOW)); prints [Ready to stop, Slow Down] on to


the console.

Question 12: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. Period period = null;
8. System.out.println(period);
9. }
10. }

2022 FIFA world cup in Qatar is scheduled to start on 21st Nov 2022. Which of the
following statement, if used to replace null, will tell you the period left for 2022 world
cup? 

Period.between(LocalDate.now(), LocalDate.parse("2022-11-21"))  
(Correct)


Period.between(LocalDateTime.now(), LocalDate.parse("2022-11-21"))  


Period.between(LocalDateTime.now(), LocalDateTime.parse("2022-11-21"))  


Period.between(LocalDate.now(), LocalDateTime.parse("2022-11-21"))  

Explanation
Signature of Period.between method is: Period between(LocalDate startDateInclusive,
LocalDate endDateExclusive) {...}   

Both the parameters are of 'LocalDate' type.

Question 13: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Collections;
5. import java.util.List;
6.  
7. class Name {
8. String first;
9. String last;
10.  
11. public Name(String first, String last) {
12. this.first = first;
13. this.last = last;
14. }
15.  
16. public String getFirst() {
17. return first;
18. }
19.  
20. public String getLast() {
21. return last;
22. }
23.  
24. public String toString() {
25. return first + " " + last;
26. }
27.  
28. }
29.  
30. public class Test {
31. public static void main(String[] args) {
32. List<Name> names = Arrays.asList(new Name("Peter", "Lee"), new Name("John",
"Smith"),
33. new Name("bonita", "smith"));
34.
35. /*INSERT*/
36.  
37. System.out.println(names);
38. }
39. }

Currently on executing Test class, [Peter Lee, John Smith, bonita smith] is displayed in
the output.

Which of the following options can replace /*INSERT*/ such that on executing Test
class, [bonita smith, John Smith, Peter Lee] is displayed in the output? 
The names list must be sorted in ascending order of first name in case-insensitive
manner.

Select 3 options.


Collections.sort(names, (o1, o2) ->
o1.getFirst().compareToIgnoreCase(o2.getFirst()));  
(Correct)


Collections.sort(names, (o1, o2) ->
o1.getFirst().toUpperCase().compareTo(o2.getFirst().toUpperCase()));  
(Correct)


Collections.sort(names, (o1, o2) ->
o1.getFirst().toLowerCase().compareTo(o2.getFirst().toLowerCase()));  
(Correct)


Collections.sort(names, (o1, o2) ->
o1.getFirst().compareTo(o2.getFirst()));  

Explanation
Collections.sort(names, (o1, o2) -> o1.getFirst().compareTo(o2.getFirst())); => It sorts
in the ascending order of first name in case-sensitive manner and displays [John
Smith, Peter Lee, bonita smith] in the output. 

Collections.sort(names, (o1, o2) ->


o1.getFirst().toLowerCase().compareTo(o2.getFirst().toLowerCase())); => At the time
of comparison, first names in lower case are considered, this doesn't change the case
of displayed output. Output is: [bonita smith, John Smith, Peter Lee]. 

Collections.sort(names, (o1, o2) ->


o1.getFirst().toUpperCase().compareTo(o2.getFirst().toUpperCase())); => At the time
of comparison, first names in upper case are considered, this doesn't change the case
of displayed output. Output is: [bonita smith, John Smith, Peter Lee]. 
Collections.sort(names, (o1, o2) -> o1.getFirst().compareToIgnoreCase(o2.getFirst()));
=> compareToIgnoreCase method compares the first names in case-insensitive
manner and displays

[bonita smith, John Smith, Peter Lee] in the output.

Question 14: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\temp.tmp"));
8. try(BufferedWriter writer = bw) { //Line 8
9.  
10. } finally {
11. bw.flush(); //Line 11
12. }
13. }
14. }

What will be the result of compiling and executing Test class?



Line 11 causes Runtime exception
(Correct)


Line 8 causes Runtime exception


Line 11 causes Compilation error


Line 8 causes Compilation error

Explanation
As variable 'bw' is created outside of try-with-resources block, hence it can easily be
accessed in finally block.

There is no issue with 'try(BufferedWriter writer = bw)' as well.

NOTE: writer and bw are referring to the same object.


Just before finishing the try-with-resources block, Java runtime invokes writer.close()
method, which closes the stream referred by writer object.

But as writer and bw are referring to the same object, hence when bw.flush(); is
invoked in finally block, it throws IOException.

Question 15: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class Printer<String> {
4.     private String t;
5.  
6.     Printer(String t){
7.         this.t = t;
8.     }
9.  
10.     public String toString() {
11.         return null;
12.     }
13. }
14.  
15. public class Test {
16.     public static void main(String[] args) {
17.         Printer<Integer> obj = new Printer<>(100);
18.         System.out.println(obj);
19.     }
20. }

What will be the result of compiling and executing Test class?



Compilation error in Printer class
(Correct)


Compilation error in Test class


null


100

Explanation
Type parameter should not be a Java keyword & a valid Java identifier. Naming
convention for Type parameter is to use uppercase single character. 
In class Printer<String>, 'String' is a valid Java identifier and hence a valid type
parameter even though it doesn't follow the naming convention of uppercase single
character.

But within Printer<String> class, 'String' is considered as type parameter and not
java.lang.String class. Return value of toString() method is java.lang.String class and
not type parameter 'String'.

So toString() method caused compilation error in Printer class. 

To resolve the compilation error, you can use below code:

public java.lang.String toString() {


return null;
}

Question 16: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.FileNotFoundException;
4. import java.io.FileReader;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. try(FileReader fr = new FileReader("C:/temp.txt")) {
9.
10. } catch (FileNotFoundException e) {
11. e.printStackTrace();
12. }
13. }
14. }

Does above code compile successfully?



YES


NO
(Correct)

Explanation
close() method of FileReader class throws IOException, which is a checked exception
and hence handle or declare rule applies in this case.
As main method neither declares to throw IOException nor a catch block is available
for IOException, hence code doesn't compile.

Question 17: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> list = Arrays.asList("north", "east", "west", "south");
9. list.replaceAll(s ->
s.substring(0,1).toUpperCase().concat(s.substring(1)));
10.  
11. System.out.println(list);
12. }
13. }

What will be the result of compiling and executing Test class?



[NORTH, EAST, WEST, SOUTH]


[north, east, west, south]


[n, e, w, s]


[North, East, West, South]
(Correct)


[N, E, W, S]

Explanation
replaceAll(UnaryOperator<E> operator) is the default method added in List
interface. 

interface UnaryOperator<T> extends Function<T, T>. 

As List is of String type, this means operator must be of UnaryOperator<String> type


only. Its accept method should have signature: String apply(String s); 
Lambda expression 's -> s.substring(0,1).toUpperCase().concat(s.substring(1))' is
correctly defined for apply method.

The lambda expression is applied for all the elements of the list. Let's check it for first
element "north". 

"north".substring(0,1) => "n", 

"n".toUpperCase() => "N", 

"N".concat("north".substring(1)) => "N".concat("orth") => "North". 

Hence, the output is: [North, East, West, South]

Question 18: Skipped
What will be the result of compiling and executing class Test?
1. package com.udayan.ocp;
2.  
3. class X {
4. class Y {
5. private void m() {
6. System.out.println("INNER");
7. }
8. }
9.
10. public void invokeInner() {
11. Y obj = new Y(); //Line 9
12. obj.m(); //Line 10
13. }
14. }
15.  
16. public class Test {
17. public static void main(String[] args) {
18. new X().invokeInner();
19. }
20. }


Compilation error at Line 10 as private method m() cannot be invoked outside the
body of inner class (Y)


Exception is thrown at runtime


INNER
(Correct)


Compilation error at Line 9 as instance of outer class (X) is needed to create the
instance of inner class (Y)

Explanation
invokeInner() is instance method of outer class, X. So, implicit 'this' reference is
available for this method. this reference refers to the currently executing instance of
outer class, X.

So Java compiler converts Y obj = new Y(); to Y obj = this.new Y(); and hence this
syntax has no issues. So Line 9 is fine.

Because of the special relationship between Outer and inner class, Outer and Inner
class can very easily access each other's private members. Hence, no issues with Line
10 as well.

Given code compiles and executes fine and prints INNER to the console.

Question 19: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Comparator;
5. import java.util.List;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<Integer> list = Arrays.asList(10, 20, 8);
10.
11. System.out.println(list.stream().max(Comparator.comparing(a -> a)).get());
//Line 1
12.  
13. System.out.println(list.stream().max(Integer::compareTo).get()); //Line 2
14.  
15. System.out.println(list.stream().max(Integer::max).get()); //Line 3
16. }
17. }

Which of the following statement is true?



Line 2 and Line 3 print same output


Line 1 and Line 2 print same output
(Correct)


Line 1, Line 2 and Line 3 print same output


Line 1 and Line 3 print same output

Explanation
In Comparator.comparing(a -> a), keyExtractor is not doing anything special, it just
implements Comparator to sort integers in ascending order.

Integer::compareTo is a method reference syntax for the Comparator to sort integers


in ascending order.

NOTE: Comparator implementations must return following:

-1 (if 1st argument is less than 2nd argument),

0 (if both arguments are equal) and

1 (if 1st argument is greater than 2nd argument).

Integer::max accepts 2 arguments and returns int value but in this case as all the 3
elements are positive, so value will always be positive.

Line 3 will print different output as it will not sort the list properly.

Question 20: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> list = Arrays.asList("7 Seven", "Lucky 7", "77", "O7ne");
9. list.stream().filter(str -> str.contains("7"))
10. .forEach(System.out::println);
11. }
12. }

What will be the result of compiling and executing Test class?



7 Seven


7 Seven
Lucky 7
77
O7ne
(Correct)


7 Seven
Lucky 7
O7ne


7 Seven
Lucky 7


7 Seven
Lucky 7
77

Explanation
contains("7") method checks if '7' is available anywhere in the String object.

All 4 String objects contain 7 and hence all 4 String objects are printed on to the
console.

Question 21: Skipped
Given:
1. package com.udayan.ocp;
2.  
3. public class Initializer {
4. static int a = 10000;
5.  
6. static {
7. --a;
8. }
9.  
10. {
11. ++a;
12. }
13.  
14. public static void main(String[] args) {
15. System.out.println(a);
16. }
17. }

What is the result of compiling and executing Initializer class?



9999
(Correct)


java.lang.ExceptionInInitailizerError


10000


Compilation Error

Explanation
You can write statements inside initialization blocks, variable a is of static type so
both static and instance initialization blocks can access it.

Instance of Initializer block is not created in this case, so instance initialization block
is not executed.

Execution of static initialization block decrements the value of a by 1. Hence the


output is 9999.

Question 22: Skipped
Fill in the blanks: 

The states of the threads involved in _________ constantly change with regard to one
another, with no overall progress made.


CyclicBarrier


livelock
(Correct)


deadlock


synchronization

Explanation
In deadlock, threads' state do not change but in livelock threads' state change
constantly. In both cases, process hangs.
Question 23: Skipped
Below files are available for your project: 
1. //1. ResourceBundle.properties
2. locale=French/Canada

1. //2. ResourceBundle_CA.properties
2. locale=Canada

1. //3. ResourceBundle_hi.properties
2. locale=Hindi

1. //4. ResourceBundle_IN.properties
2. locale=India

1. //5. Test.java
2. package com.udayan.ocp;
3.  
4. import java.util.Locale;
5. import java.util.ResourceBundle;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Locale.setDefault(new Locale("fr", "CA"));
10. Locale loc = new Locale("en", "IN");
11. ResourceBundle rb = ResourceBundle.getBundle("MyResourceBundle", loc);
12. System.out.println(rb.getObject("locale"));
13. }
14. }

Assume that all the *.properties files are included in the CLASSPATH. What will be the
output of compiling and executing Test class?

India


Hindi


Runtime Exception
(Correct)


French/Canada


Canada

Explanation
ResourceBundle.getBundle("MyResourceBundle", loc); => Base resource bundle file
name should be 'MyResourceBundle'.

Default Locale is: fr_CA and passed Locale to getBundle method is: en_IN
The search order for matching resource bundle is:

MyResourceBundle_en_IN.properties [1st: Complete en_IN]. 

MyResourceBundle_en.properties [2nd: Only language en]. 

MyResourceBundle_fr_CA.properties [3rd: Complete default Locale fr_CA]. 

MyResourceBundle_fr.properties [4th: Language of default Locale fr]. 

MyResourceBundle.properties [5th: ResourceBundle's name without language or


country]. 

None of the properties files match with above search list, hence
MissingResourceException is thrown at runtime.

Question 24: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.function.BiFunction;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. BiFunction<String, String, String> func = String::concat;
8. System.out.println(func.apply("James", "Gosling"));
9. }
10. }

What will be the result of compiling and executing Test class?



GoslingJames


James Gosling


Gosling


James


Gosling James


JamesGosling
(Correct)

Explanation
BiFunction<String, String, String> interface's apply method signature will be: String
apply(String str1, String str2). 

'String::concat' is equivalent to LAMBDA expression '(str1, str2) -> str1.concat(str2)'. 


concat method returns new String object after concatenation. 

Hence, func.apply("James", "Gosling") returns 'JamesGosling'. 

Question 25: Skipped
Given Code:
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. class ReadTheFile {
6. static void print() { //Line 4
7. throw new IOException(); //Line 5
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) { //Line 10
13. ReadTheFile.print(); //Line 11
14. //Line 12
15. }
16. }

Which 2 changes are necessary so that code compiles successfully?



Replace Line 4 with  static void print() throws Exception {  
(Correct)


Surround Line 11 with below try-catch block:
1. try {
2. ReadTheFile.print();
3. } catch(Exception e) {
4. e.printStackTrace();
5. }

(Correct)


Replace Line 4 with  static void print() throws Throwable {  

Replace Line 10 with  public static void main(String[] args) throws
IOException {  


Surround Line 11 with below try-catch block:
1. try {
2. ReadTheFile.print();
3. } catch(IOException e) {
4. e.printStackTrace();
5. }

Surround Line 11 with below try-catch block:
1. try {
2. ReadTheFile.print();
3. } catch(IOException | Exception e) {
4. e.printStackTrace();
5. }

Explanation
This question is tricky as 2 changes are related and not independent. Let's first check
the reason for compilation error. Line 5 throws a checked exception, IOException but
it is not declared in the throws clause. So, print method should have throws clause
for IOException or the classes in top hierarchy such as Exception or Throwable.

Based on this deduction, Line 4 can be replaced with either "static void print() throws
Exception {" or "static void print() throws Throwable" but we will have to select one
out of these as after replacing Line 4, Line 11 will start giving error as we are not
handling the checked exception at Line 11.

This part is easy, do we have other options, which mention "Throwable"? NO. Then
mark the first option as "Replace Line 4 with static void print() throws Exception {".

As, print() method throws Exception, so main method should handle Exception or its
super type and not it's subtype. Two options working only with IOException can be
ruled out.

Multi-catch statement "catch(IOException | Exception e)" causes compilation error as


IOException and Exception are related to each other in multilevel inheritance. So you
are left with only one option to pair with our 1st choice:
Surround Line 11 with below try-catch block:

try {
ReadTheFile.print();
} catch(Exception e) {
e.printStackTrace();
}

Question 26: Skipped
Which of the following will correctly accept and print the entered password on
to the console?

1. Console console = System.console();
2. char [] pwd = console.readPassword("Enter Password: ");
3. System.out.println(new String(pwd));

(Correct)


1. Console console = new Console(System.in);
2. char [] pwd = console.readPassword("Enter Password: ");
3. System.out.println(new String(pwd));


1. Console console = new Console(System.in);
2. String pwd = console.readPassword("Enter Password: ");
3. System.out.println(pwd);


1. Console console = System.console();
2. String pwd = console.readPassword("Enter Password: ");
3. System.out.println(pwd);

Explanation
new Console(...) causes compilation error as it doesn't have matching constructor. It's
no-argument constructor is private.

Correct way to get Console instance is by System.console(); 

readPassword method is overloaded:

char [] readPassword() {...}

char [] readPassword(String fmtString, Object... args) {...}


console.readPassword("Enter Password: "); => compiles and executes successfully as
there are no format specifier in 1st argument, so it is OK to provide just one
argument to this method.

Return type of readPassword(...) method is char [] and not String.

Question 27: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. System.out.println(Stream.of(10, 0, -10).sorted().findAny().orElse(-1));
8. }
9. }

Which of the following statements are true about the execution of Test class?

Select 2 options.


It will never print -1 on to the console.
(Correct)


It can print any number from the stream.
(Correct)


It will always print -10 on to the console.


It will always print 0 on to the console.


It will always print 10 on to the console.

Explanation
findAny() may return any element from the stream and as stream is not parallel, it will
most likely return first element from the sorted stream, which is -10. But this is not
the guaranteed result.

As this stream has 3 elements, hence -1 will never get printed on to the console.

Question 28: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date1 = LocalDate.of(2019, 1, 2);
8. date1.minus(Period.ofDays(1));
9. LocalDate date2 = LocalDate.of(2018, 12, 31);
10. date2.plus(Period.ofDays(1));
11. System.out.println(date1.equals(date2) + ":" + date1.isEqual(date2));
12. }
13. }

What will be the result of compiling and executing Test class?



true:true


true:false


false:false
(Correct)


false:true

Explanation
Both the methods public "boolean isEqual(ChronoLocalDate)" and "public boolean
equals(Object)" return true if date objects are equal otherwise false. 

NOTE: LocalDate implements ChronoLocalDate.

date1 --> {2019-01-02}

date1.minus(Period.ofDays(1)); As LocalDate is immutable, this statement creates


another instance of LocalDate class. and date1 still refers to previous object.

Similarly date2 refers to {2018-12-31}

and 'date2.plus(Period.ofDays(1));' creates another instance of LocalDate class.

As date1 and date2 are not logically same, equals and isEqual methods return false.
Question 29: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws Exception {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
13. ) {
14. ResultSet rs = stmt.executeQuery(query);
15. rs.afterLast();
16. while (rs.previous()) {
17. rs.updateDouble(4, rs.getDouble(4) + 1000);
18. }
19. rs.updateRow();
20.  
21. rs = stmt.executeQuery(query);
22. while(rs.next()) {
23. System.out.println(rs.getDouble(4));
24. }
25. }
26. }
27. }

Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?



13000.0
16000.0
16500.0
15600.0


12000.0
15000.0
15500.0
15600.0


13000.0
15000.0
15500.0
14600.0


An exception is thrown at runtime
(Correct)


12000.0
15000.0
15500.0
14600.0

Explanation
Method updateRow() must be called after every updated ResultSet row. In this case
updateRow() method was called after updating salary in all 4 rows and hence it
throws an exception at runtime.

NOTE: To update the salary of all the records successfully, move rs.updateRow()
statement inside while loop after rs.updateDouble(...) method call.

Question 30: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.List;
4. import java.util.Map;
5. import java.util.stream.Collectors;
6. import java.util.stream.Stream;
7.  
8. class Certification {
9. String studId;
10. String test;
11. int marks;
12.  
13. Certification(String studId, String test, int marks) {
14. this.studId = studId;
15. this.test = test;
16. this.marks = marks;
17. }
18.  
19. public String toString() {
20. return "{" + studId + ", " + test + ", " + marks + "}";
21. }
22.  
23. public String getStudId() {
24. return studId;
25. }
26.  
27. public String getTest() {
28. return test;
29. }
30.  
31. public int getMarks() {
32. return marks;
33. }
34. }
35.  
36. public class Test {
37. public static void main(String[] args) {
38. Certification c1 = new Certification("S001", "OCA", 87);
39. Certification c2 = new Certification("S002", "OCA", 82);
40. Certification c3 = new Certification("S001", "OCP", 79);
41. Certification c4 = new Certification("S002", "OCP", 89);
42. Certification c5 = new Certification("S003", "OCA", 60);
43. Certification c6 = new Certification("S004", "OCA", 88);
44.  
45. Stream<Certification> stream = Stream.of(c1, c2, c3, c4, c5, c6);
46. Map<Boolean, List<Certification>> map =
47. stream.collect(Collectors.partitioningBy(s -> s.equals("OCA")));
48. System.out.println(map.get(true));
49. }
50. }

What will be the result of compiling and executing Test class?



[{S001, OCP, 79}, {S002, OCP, 89}]


[]
(Correct)


[{S001, OCA, 87}, {S002, OCA, 82}, {S001, OCP, 79}, {S002, OCP, 89}, {S003, OCA,
60}, {S004, OCA, 88}]


[{S001, OCA, 87}, {S002, OCA, 82}, {S003, OCA, 60}, {S004, OCA, 88}]

Explanation
Rest of the code is very simple, let us concentrate on partitioning code.
Collectors.partitioningBy(s -> s.equals("OCA")) => s in this lambda expression is of
Certification type and not String type.

This means predicate 's -> s.equals("OCA")' will return false for "OCA". None of the
certification object will return true and hence no element will be stored against 'true'.

[] will be printed in the output.

Correct predicate will be: 's -> s.getTest().equals("OCA")'.

For above predicate, output for 'System.out.println(map.get(true));' will be:

[{S001, OCA, 87}, {S002, OCA, 82}, {S003, OCA, 60}, {S004, OCA, 88}]

Question 31: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. System.out.println(IntStream.range(10,1).count());
8. }
9. }

What will be the result of compiling and executing Test class?



Runtime Exception


0
(Correct)


9


10

Explanation
IntStream.range(int start, int end) => start is inclusive and end is exclusive and
incremental step is 1.

count() => Returns the count of elements in this stream.

IntStream.range(10,1) => Returns an empty stream as start > end, this means stream
doesn't have any elements. That is why count() returns 0.

Question 32: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path path1 = Paths.get("C:\\A\\B\\C");
9. Path path2 = Paths.get("D:\\A");
10. System.out.println(path1.relativize(path2));
11. System.out.println(path2.relativize(path1));
12. }
13. }

What will be the result of compiling and executing Test class?



An exception is thrown at runtime
(Correct)


B\C
..\..


Compilation error.


..\..
B\C

Explanation
For 'path1.relativize(path2)' both path1 and path2 should be of same type. Both
should either be relative or absolute.
In this case, path1 refers to 'C:\A\B\C' and path2 refers to 'D:\A'.

Even though both paths are absolute but their roots are different, hence
IllegalArgumentException is thrown at runtime.

Question 33: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Set;
4. import java.util.TreeSet;
5.  
6. class Employee implements Comparable<Employee> {
7. private String name;
8. private int age;
9.  
10. Employee(String name, int age) {
11. this.name = name;
12. this.age = age;
13. }
14.  
15. @Override
16. public String toString() {
17. return "{" + name + ", " + age + "}";
18. }
19.  
20. @Override
21. public int compareTo(Employee o) {
22. return o.age - this.age;
23. }
24. }
25.  
26. public class Test {
27. public static void main(String[] args) {
28. Set<Employee> employees = new TreeSet<>();
29. employees.add(new Employee("Udayan", 31));
30. employees.add(new Employee("Neha", 23));
31. employees.add(new Employee("Hou Jian", 42));
32. employees.add(new Employee("Smita", 29));
33.  
34. System.out.println(employees);
35. }
36. }

What will be the result of compiling and executing Test class?



[{Neha, 23}, {Smita, 29}, {Udayan, 31}, {Hou Jian, 42}]


[{Hou Jian, 42}, {Udayan, 31}, {Smita, 29}, {Neha, 23}]
(Correct)


Compilation error

[{Udayan, 31}, {Neha, 23}, {Hou Jian, 42}, {Smita, 29}]

Explanation
Comparable interface has compareTo(...) method and Comparator interface has
compare(...) method.

In this case, class Employee correctly implements Comparable interface.

return o.age - this.age; => This will help to sort the Employee objects in descending
order of age and not in ascending order.

As no Comparator is passed in TreeSet, hence it sorts on the basis of implementation


of Comparable interface, which means Employee objects will be sorted in descending
order of their age.

Question 34: Skipped
Imagine below path exists:
1. F:.
2. └───A
3. └───B

    
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. File dir = new File("F:" + File.separator + "A" + File.separator + "B");
8. System.out.println(/*INSERT*/);
9. }
10. }

Which of the following replaces /*INSERT*/, such that on execution 'F:\' is displayed
on to the console?
Select 2 options.

dir.getParent().getParentFile()  


dir.getParentFile().getParent()  
(Correct)

dir.getParentFile().getParentFile()  
(Correct)


dir.getParent().getParent()  

Explanation
File class has below 2 methods:

public File getParentFile() {...}

public String getParent() {...}

toString() method of File class prints the abstract path of file object on to the
console.

dir.getParentFile() => returns a File object for abstract path 'F:\A'. 

dir.getParentFile().getParentFile() => returns a File object for abstract path 'F:\', when
this file object is passed to println method, its toString() method is invoked and 'F:\'
gets printed on to the console. 

dir.getParentFile().getParent() => Returns a String object containing "F:\".

dir.getParent() returns String and String class doesn't contain getParentFile() and
getParent() methods.

Question 35: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. public class Test {
4. enum TrafficLight {
5. private String message;
6. GREEN("go"), AMBER("slow"), RED("stop");
7.
8. TrafficLight(String message) {
9. this.message = message;
10. }
11.
12. public String getMessage() {
13. return message;
14. }
15. }
16.
17. public static void main(String[] args) {
18. System.out.println(TrafficLight.AMBER.getMessage().toUpperCase());
19. }
20. }


SLOW


slow


Compilation error
(Correct)


NullPointerException is thrown at runtime

Explanation
Enum constant list must be the first item in an enum.

GREEN("go"), AMBER("slow"), RED("stop"); should be the first line inside TrafficLight


enum.

Question 36: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<Integer> list = Arrays.asList(0,2,4,6,8);
9. list.replaceAll(i -> i + 1);
10. System.out.println(list);
11. }
12. }

What will be the result of compiling and executing Test class?



[1, 3, 5, 7, 9]
(Correct)


[0, 2, 4, 6, 8]


Compilation error


Runtime Exception

Explanation
replaceAll(UnaryOperator<E> operator) is a default method available in List interface,
it replaces each element of this list with the result of applying the operator to that
element.

list.replaceAll(i -> i + 1); => Adds 1 to each element of the list. Result is [1, 3, 5, 7, 9].

Question 37: Skipped
F: is accessible for reading/writing and below is the directory structure for F:
1. F:.
2. └───X

Directory X exists under F:.

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7.  
8. public class Test {
9. public static void main(String[] args) throws IOException{
10. Path path = Paths.get("F:\\X\\Y\\Z");
11. Files.createDirectory(path);
12. }
13. }

What will be the result of compiling and executing Test class?



An exception is thrown at runtime.
(Correct)


Only directory Y will be created under X.


Directory Y will be created under X and directory Z will be created under Y.

Explanation
'Files.createDirectory(path);' creates the farthest directory element but all parents
must exist.

In this case, createDirectory method tries to create 'Z' directory under F:\X\Y.

F:\X exists but F:\X\Y doesn't exist and hence NoSuchFileException is thrown at
runtime.

Question 38: Skipped
Consider 'con' refers to a valid Connection instance. Which of the following
successfully creates Statement instance?

Select 2 options.


con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE);  


con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);  
(Correct)


con.createStatement(ResultSet.CONCUR_READ_ONLY);  


con.createStatement();  
(Correct)

Explanation
Method createStatement is overloaded: createStatement(), createStatement(int, int)
and createStatement(int, int, int).
Question 39: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. public class Test {
4. enum STATUS {
5. PASS, FAIL;
6. }
7.  
8. private static boolean checkStatus(STATUS status) {
9. switch(status) {
10. case PASS:
11. return true;
12. case FAIL:
13. return false;
14. default: {
15. assert false : "<<<DANGER ZONE>>>";
16. return false;
17. }
18. }
19. }
20.  
21. public static void main(String[] args) {
22. checkStatus(null);
23. }
24. }

What will be the result of executing Test class with below command? 
java -ea com.udayan.ocp.Test

No output and program terminates successfully


AssertionError is thrown and program ends abruptly


NullPointerException is thrown and program ends abruptly
(Correct)

Explanation
At runtime, first statement inside checkStatus(STATUS) method is switch(status) and
as status is null, NullPointerException is thrown and program ends abruptly.
Question 40: Skipped
Below is the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String [] args) {
5. System.out.println(new Object() {
6. public String toString() {
7. return "Anonymous";
8. }
9. });
10. }
11. }

What will be the result of compiling and executing Test class?



Some text containing @ symbol


Runtime exception


Compilation error


Anonymous
(Correct)

Explanation
System.out.println(new Object()); invokes the toString() method defined in Object
class, which prints fully qualified class name, @ symbol and hexadecimal value of
hash code [Similar to java.lang.Object@15db9742]

In the given code, an instance of anonymous class extending Object class is passed
to System.out.println() method and the anonymous class overrides the toString()
method.

Thus, at runtime overriding method is invoked, which prints "Anonymous" to the


console.

Question 41: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.function.Predicate;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<Integer> list = Arrays.asList(-80, 100, -40, 25, 200);
10. Predicate<Integer> predicate = num -> {
11. int ctr = 1;
12. boolean result = num > 0;
13. System.out.print(ctr++ + ".");
14. return result;
15. };
16.  
17. list.stream().filter(predicate).sorted();
18. }
19. }

What will be the result of compiling and executing Test class?



1.2.3.4.5.


Nothing is printed on to the console
(Correct)


1.1.1.1.1.


1.

1.2.


1.1.

Explanation
Streams are lazily evaluated and as sorted() is an intermediate operation, hence
stream is not evaluated and you don't get any output on to the console.
Question 42: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Stream<Number> stream = Stream.of();
9. Optional<Number> optional = stream.findFirst();
10. System.out.println(optional.orElse(-1));
11. }
12. }

What will be the result of compiling and executing Test class?



null


0


-1
(Correct)


Optional.empty

Explanation
Stream.of() creates an empty stream.

stream.findFirst(); => returns an empty Optional.

Hence, orElse method is executed and prints -1 on to the console.

Question 43: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. interface I9 {
4. void print();
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. int i = 400;
10. I9 obj = () -> System.out.println(i);
11. obj.print();
12. System.out.println(++i);
13. }
14. }


Compilation error
(Correct)


Exception is thrown at runtime


400
401


400
400

Explanation
variable i a is local variable and it is used in the lambda expression. So, it should
either be final or effectively final. 

The last statement inside main(String []) method, increments value of i, which means
it is not effectively final and hence compilation error.

Question 44: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate d1 = LocalDate.now();
8. LocalDateTime d2 = LocalDateTime.now();
9. System.out.println(Duration.between(d1, d2));
10. }
11. }

What will be the result of compiling and executing Test class?



Program terminates successfully after displaying the output


Runtime Exception
(Correct)


Compilation error

Explanation
Signature of between method defined in Duration class is: 'Duration
between(Temporal startInclusive, Temporal endExclusive)'.

As both LocalDate and LocalTime implement 'Temporal' interface, hence there is no


compilation error.

Time part must be available to calculate duration but as LocalDate object referred by
d1 doesn't have time part, hence an exception is thrown at runtime.

Question 45: Skipped
Given code: 
1. package com.udayan.ocp;
2.  
3. abstract class Greetings {
4. abstract void greet();
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Greetings obj = new Greetings() {
10. @Override
11. public void greet() {
12. System.out.println("Hello");
13. }
14. };
15. obj.greet();
16. }
17. }

What will be the result of compiling and executing Test class?



Nothing is printed on to the console


Hello
(Correct)


NullPointerException


Compilation error

Explanation
obj refers to an anonymous inner class instance extending from Greetings class and
the anonymous inner class code correctly overrides greet() method.

Code executes and prints Hello on to the console.

Question 46: Skipped
C:\ is accessible for reading/writing and below is the content of 'C:\TEMP' folder:
1. C:\TEMP
2. │ msg
3. │
4. └───Parent
5. └───Child
6. Message.txt

'msg' is a symbolic link file for 'C:\TEMP\Parent\Child\Message.txt'.

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7.  
8. public class Test {
9. public static void main(String[] args) throws IOException {
10. Path src = Paths.get("C:", "TEMP", "msg");
11.  
12. Path tgt = Paths.get("C:", "TEMP", "Parent", "copy");
13. Files.copy(src, tgt);
14.  
15. System.out.println(Files.isSymbolicLink(src) + ":" +
Files.isSymbolicLink(tgt));
16. }
17. }

What will be the result of compiling and executing Test class?



true:true


false:true


true:false
(Correct)


false:false
Explanation
First of all I would like to tell you that Windows shortcut and symbolic links are
different. 

Shortcut is just a regular file and symbolic link is a File System object. 

To create symbolic link used in this question, I used below command:

C:\TEMP>mklink msg .\Parent\Child\Message.txt 

And below message was displayed on to the console for the successful creation of
symbolic link 'symbolic link created for msg <<===>> .\Parent\Child\Message.txt'. 

When copy() method is used for symbolic link, then by default target file is copied
and not the symbolic link. 

So, 'src' is a symbolic link an 'tgt' is a regular file. 'true:false' is printed on to the
console.

NOTE: For the job, if you want to copy symbolic link, then use 'Files.copy(src, tgt,
LinkOption.NOFOLLOW_LINKS);' but make sure that user should have 'symbolic'
LinkPermission.

Question 47: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> list = Arrays.asList("A", "E", "I", "O");
9. list.add("U");
10. list.forEach(System.out::print);
11. }
12. }

What will be the result of compiling and executing Test class?



UAEIO


AEIO


Compilation error


Runtime exception
(Correct)


AEIOU

Explanation
You cannot add or remove elements form the list returned by Arrays.asList(T...)
method but elements can be re-positioned. 

list.add("U"); throws UnsupportedOperationException at runtime.

Question 48: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. public class Test<T> {
4. private T t;
5.  
6. public T get() {
7. return t;
8. }
9.  
10. public void set(T t) {
11. this.t = t;
12. }
13.  
14. public static void main(String args[]) {
15. Test obj = new Test();
16. obj.set("OCP");
17. obj.set(85);
18. obj.set('%');
19.  
20. System.out.println(obj.get());
21. }
22. }

What will be the result of compiling and executing Test class?



OCP85%

Output contains some text containing @ symbol


Compilation error


Runtime exception


%
(Correct)

Explanation
Test<T> is generic type and Test is raw type. When raw type is used then T is Object,
which means set method will have signature: set(Object t). 

Test obj = new Test(); => Test object is created and obj refers to it.

obj.set("OCP"); => Instance variable t refers to "OCP". 

obj.set(85); => Instance variable t refers to Integer object, 85. Auto-boxing converts
int literal to Integer object.

obj.set('%'); => Instance variable t refers to Character object, %. Auto-boxing


converts char literal to Character object.

obj.get() => this returns Character object as Character class overrides toString()
method, % is printed on to the console.

Question 49: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4. import java.nio.file.Path;
5. import java.nio.file.Paths;
6.  
7. public class Test {
8. public static void main(String[] args) throws IOException {
9. Path path = Paths.get("F:\\A\\B\\C\\");
10. System.out.printf("%d, %s, %s", path.getNameCount(), path.getFileName(),
path.getName(2));
11. }
12. }

F: is accessible for reading/writing but is currently blank. 

What will be the result of compiling and executing Test class?


3, C, C
(Correct)


3, C, B


4, C, B


4, null, B


Runtime Exception

Explanation
Root folder or drive is not considered in count and indexing. In the given path A is at
0th index, B is at 1st index and C is at 2nd index. 

path.getName(2) returns 'C'.

path.getNameCount() returns 3 (A,B,C) and path.getFileName() returns the last name


of the path, which is 'C'.

Given methods doesn't need actual path to physically exist and hence no exception is
thrown at Runtime.

Question 50: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class Resource1 implements AutoCloseable {
4. @Override
5. public void close() {
6. System.out.println("Resource1");
7. }
8. }
9.  
10. class Resource2 implements AutoCloseable {
11. @Override
12. public void close() {
13. System.out.println("Resource2");
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. try(Resource1 r1 = new Resource1(); Resource2 r2 = new Resource2()) {
20. System.out.println("Test");
21. }
22. }
23. }

What will be the result of compiling and executing Test class?



Test
Resource1
Resource2


Test
Resource2
Resource1
(Correct)


Compilation Error

Explanation
Resources are closed in the reverse order of their declaration.

So r2 is closed first and then r1.

Question 51: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.io.PrintWriter;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. try(PrintWriter bw = new PrintWriter("F:\\test.txt"))
9. {
10. bw.close();
11. bw.write(1);
12. } catch(IOException e) {
13. System.out.println("IOException");
14. }
15. }
16. }

F: is accessible for reading/writing purposes.


Which of the following statement is true about above code?


Compilation error


test.txt file will be successfully created and 1 will be written to it


Class Test compiles and executes fine and no output is displayed on to the
console
(Correct)


On execution, IOException is printed on to the console

Explanation
new PrintWriter("F:\\test.txt") creates a blank file 'F:\test.txt'.

new PrintWriter("F:\\test.txt") can throw FileNotFoundException at runtime and given


catch handler can access FileNotFoundException as it extends IOException.

public methods of PrintWriter don't throw IOException. In case of IOException,


internal flag variable, 'trouble' is set to true.

bw.write(1); is invoked after bw.close() and hence nothing is written to the file.

Question 52: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4. import java.util.function.DoublePredicate;
5.  
6. class Employee {
7. private String name;
8. private double salary;
9.  
10. public Employee(String name, double salary) {
11. this.name = name;
12. this.salary = salary;
13. }
14.  
15. public String getName() {
16. return name;
17. }
18.  
19. public double getSalary() {
20. return salary;
21. }
22.  
23. public void setSalary(double salary) {
24. this.salary = salary;
25. }
26.  
27. public String toString() {
28. return "{" + name + ", " + salary + "}";
29. }
30. }
31.  
32. public class Test {
33. public static void main(String[] args) {
34. List<Employee> employees = Arrays.asList(new Employee("Jack", 8000),
35. new Employee("Lucy", 12000));
36. updateSalary(employees, d -> d < 10000);
37. employees.forEach(System.out::println);
38. }
39.  
40. private static void updateSalary(List<Employee> list, DoublePredicate
predicate) {
41. for(Employee e : list) {
42. if(predicate.negate().test(e.getSalary())) {
43. e.setSalary(e.getSalary() + 2000);
44. }
45. }
46. }
47. }

What will be the result of compiling and executing Test class?



{Jack, 8000.0}
{Lucy, 14000.0}
(Correct)


{Jack, 10000.0}
{Lucy, 14000.0}


{Jack, 8000.0}
{Lucy, 12000.0}


{Jack, 10000.0}
{Lucy, 12000.0}

Explanation
There are 3 primitive interfaces corresponding to Predicate interface:

DoublePredicate : boolean test(double value);

IntPredicate : boolean test(int value);


LongPredicate : boolean test(long value);

Lambda expression 'd -> d < 10000' in this case can be easily assigned to
DoublePredicate target type. 'd -> d < 10000' returns true if value is less than 10000.

But note: negate() method is used, which means a new DoublePredicate is returned
which is just opposite of the given DoublePredicate. After negation, the resultant
predicate is 'd -> d >= 10000'.

Salary is incremented only for Lucy and not Jack.

Question 53: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.PrintWriter;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try(PrintWriter writer = new PrintWriter(System.out)) {
8. writer.println("Hello");
9. } catch(Exception ex) {
10. writer.close();
11. }
12. }
13. }

What will be the result of compiling and executing Test class?



Program ends abruptly


Hello


Compilation error
(Correct)

Explanation
Scope of writer variable is with-in the boundary of try-with-resources block.

It is not accessible inside catch block and hence 'writer.close()' causes compilation
failure.
NOTE: PrintWriter constructor and println method don't throw any exception but it is
OK to catch Exception type.

Compiler allows to catch Exception type even if code within try block doesn't throw
any exception.

Question 54: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8. System.out.print("Enter any number between 1 and 10: ");
9. int num = br.read();
10. System.out.println(num);
11. }
12. }

On execution above code prompts user with following message:

Enter any number between 1 and 10: 

Which of the following statement is true if user types 2 and press Enter?


Runtime Exception


2 will not be printed on to the console.
(Correct)


2 will be printed on to the console.

Explanation
InputStreamReader class has a constructor 'public InputStreamReader(InputStream
in)', hence System.in, which is an instance of InputStream can be passed to it.

br.read() reads a single character, so it reads user input as '2' and not 2. ASCII code
for character '2' is not 2. In fact, it is 50.

So, 50 will be shown in the output.


OCP exam doesn't expect you to know exact corresponding ASCII codes but you
should know that read() method returns single character (16-bit: 0 to 65535) but as
return type is int hence it returns the ASCII value in this case.

If you want to retrieve the user input then use below code: 

String s = br.readLine();
int i = Integer.parseInt(s); //In case you want to convert to int.
System.out.println(i);

Question 55: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Stream<Integer> stream = Arrays.asList(1,2,3,4,5).stream();
9. System.out.println(stream.sum());
10. }
11. }

What will be the result of compiling and executing Test class?



15


Runtime Exception


Compilation error
(Correct)

Explanation
Generic Stream<T> interface has following methods:

Optional<T> min(Comparator<? super T> comparator);

Optional<T> max(Comparator<? super T> comparator);


Primitive Stream interfaces (IntStream, LongStream & DoubleStream) has methods
min(), max(), sum(), average() and summaryStatistics(). 

In this case, as stream is a generic interface, hence stream.sum() causes compilation


error.

Question 56: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. class Counter implements Serializable {
6. private static int count = 0;
7. public Counter() {
8. count++;
9. }
10.  
11. public static int getCount() {
12. return count;
13. }
14. }
15.  
16. public class Test {
17. public static void main(String[] args) throws IOException,
ClassNotFoundException {
18. Counter ctr = new Counter();
19. try( ObjectOutputStream oos = new ObjectOutputStream(
20. new FileOutputStream("C:\\Counter.dat")) ){
21. oos.writeObject(ctr);
22. }
23.  
24. new Counter(); new Counter();
25.  
26. try( ObjectInputStream ois = new ObjectInputStream(
27. new FileInputStream("C:\\Counter.dat")) ){
28. ctr = (Counter)ois.readObject();
29. System.out.println(Counter.getCount());
30. }
31. }
32. }

There is full permission to list/create/delete files and directories in C:.

What will be the result of compiling and executing Test class?


3
(Correct)


1


2


Runtime Exception

Explanation
Counter class implements Serializable, hence objects of Counter class can be
serialized using ObjectOutputStream.

State of transient and static fields are not persisted.

While de-serializing, transient fields are initialized to default values (null for reference
type and respective Zeros for primitive types) and static fields refer to current value.

In this case, count is static, so it is not persisted. On de-serializing, current value of


count is used.

new Counter(); simply increments the variable count by 1.

System.out.println(Counter.getCount()); => Prints 3 on to the console.

Question 57: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Locale;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Locale locale = new Locale("temp", "UNKNOWN"); //Line 7
8. System.out.println(locale.getLanguage() + ":" + locale.getCountry());
//Line 8
9. System.out.println(locale); //Line 9
10. }
11. }

What will be the result of compiling and executing Test class?



Line 8 throws exception at runtime

Line 9 throws exception at runtime


temp:UNKNOWN
temp_UNKNOWN
(Correct)


Line 7 throws exception at runtime


Compilation error

Explanation
Locale class has overloaded constructors:

Locale(String language)

Locale(String language, String country)

Locale(String language, String country, String variant)

For the exam, you should know that Locale instance can be created by passing
incorrect country and language and in fact getLanguage(), getCountry() and
toString() method prints the passed strings.

NOTE: It may cause problem later on, when you try to retrieve resource bundle.

Question 58: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.OptionalInt;
4.  
5. class MyException extends Exception{}
6.  
7. public class Test {
8. public static void main(String[] args) {
9. OptionalInt optional = OptionalInt.empty();
10. System.out.println(optional.orElseThrow(MyException::new));
11. }
12. }

What will be the result of compiling and executing Test class?



An instance of MyException is thrown at runtime


An instance of NoSuchElementException is thrown at runtime


null


An instance of NullPointerException is thrown at runtime


An instance of RuntimeException is thrown at runtime


Compilation error
(Correct)

Explanation
MyException is a checked exception, so 'handle or declare' rule must be followed.

'orElseThrow(MyException::new)' can throw checked exception at runtime, so it must


be surrounded by a try-catch block or main method should declare proper throws
clause.

Question 59: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. int res = 1;
8. IntStream stream = IntStream.rangeClosed(1, 4);
9.  
10. System.out.println(stream.reduce(res++, (i, j) -> i * j));
11. }
12. }

What will be the result of compiling and executing Test class?



6


24
(Correct)


48


12


Compilation error as res should be effectively final

Explanation
IntStream.rangeClosed(1, 4); => [1, 2, 3, 4]

To understand, 'stream.reduce(res++, (i, j) -> i * j)' can be somewhat written as:

int result = res++;


for (int element : stream) {
result = accumulator.applyAsInt(result, element);
}
return result;

Above code is just for understanding purpose, you can't iterate a stream using given
loop.

result will be initialized to 1 and after that res will be incremented to 2. But value of
'result' is used and not 'res'.

Hence output will be result of '1 * 1 * 2 * 3 * 4', which is 24.

Question 60: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.sql.SQLException;
4.  
5. public class Test {
6. private static void m() throws SQLException {
7. try {
8. throw new SQLException();
9. } catch (Exception e) {
10. e = new SQLException();
11. throw e;
12. }
13. }
14.  
15. public static void main(String[] args) {
16. try {
17. m();
18. } catch(SQLException e) {
19. System.out.println("Caught Successfully.");
20. }
21. }
22. }

What will be the result of compiling and executing Test class?



Program ends abruptly.


Caught Successfully.


Method m() causes compilation error.
(Correct)


Method main(String []) causes compilation error.

Explanation
If you don't initialize variable e inside catch block using 'e = new SQLException();' and
simply throw e, then code would compile successfully as compiler is certain that e
would refer to an instance of SQLException only.

But the moment compiler finds 'e = new SQLException();', 'throw e;' causes
compilation error as at runtime e may refer to any Exception type.

Question 61: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. class Outer {
4. public void print(int x) {
5. class Inner {
6. public void getX() {
7. System.out.println(++x);
8. }
9. }
10. Inner inner = new Inner();
11. inner.getX();
12. }
13. }
14.  
15. public class Test {
16. public static void main(String[] args) {
17. new Outer().print(100);
18. }
19. }

100


101


Runtime exception


Compilation error
(Correct)

Explanation
class Inner is method local inner class and it is accessing parameter variable x.

Starting with JDK 8, a method local inner class can access local variables and
parameters of the enclosing block that are final or effectively final.

But the statement System.out.println(++x); tries to increment the value of variable x


and hence compilation error.

Question 62: Skipped
F: is accessible for reading and below is the directory structure for F:
1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java

'Book.java' file is available under 'C' directory.

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path file = Paths.get("F:\\A\\B\\Book.java");
9. System.out.println(file.toAbsolutePath());
10. }
11. }
What will be the result of compiling and executing Test class?

F:\A\B\Book.java
(Correct)


Book.java


NoSuchFileException is thrown at runtime.


FileNotFoundException is thrown at runtime.

Explanation
toAbsolutePath() method doesn't care if given path elements are physically available
or not. It just returns the absolute path.

As file already refers to absolute path, hence the same path is printed on to the
console.

Question 63: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select * from EMPLOYEE";
11. Connection con = DriverManager.getConnection(url, user, password);
12. try (Statement stmt = con.createStatement())
13. {
14. ResultSet rs = stmt.executeQuery(query);
15. }
16. }
17. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

Which of the following objects will get closed?

Select 2 options.


Connection object


None of the objects will get closed as close() method is not invoked.


Statement object
(Correct)


ResultSet object
(Correct)

Explanation
Statement object is created inside try-with-resources statement. So, close() method is
invoked on Statement object implicitly.

According to the javadoc of close() method, "When a Statement object is closed, its
current ResultSet object, if one exists, is also closed". Hence, ResultSet object is also
closed.

Connection object is created outside of try-with-resources statement, hence close()


method of Connection object is not invoked implicitly.

Question 64: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4. import java.util.Date;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Date date = new Date();
9. LocalDate localDate = null; //Line n1
10. }
11. }

Which of the following two statements will replace null at Line n1 such that Date
object referred by 'date' is converted to LocalDate object?

Select 2 options.


date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
(Correct)


LocalDate.of(date);


Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLoca
lDate();
(Correct)


date.toLocalDate();


(LocalDate)date;

Explanation
java.util.Date class doesn't have any method to convert to LocalDate, LocalDateTime
or LocalTime and vice-versa. Hence, 'date.toLocalDate();' and 'LocalDate.of(date);'
cause compilation error.

'(LocalDate)date' also causes compilation failure as LocalDate and Date are not
related in multilevel inheritance.

Hence, two correct options left are:


'date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();' and
'Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();'.
Let us understand what is happening with above statements:

java.util.Date class has toInstant() method which converts java.util.Date object to


java.time.Instant object. If you check the code of toInstant() method, you will find
below one statement inside it:

'return Instant.ofEpochMilli(getTime());'

This means 'date.toInstant()' is same as 'Instant.ofEpochMilli(date.getTime())'. Both


statements return the object of Instant class.

ZonedDateTime class has methods to convert to LocalDate, LocalDateTime and


LocalTime instances. So, object of Instant is first converted to ZonedDateTime.

An Instant object doesn't store any information about the time zone, so to convert it
to ZonedDateTime, the default zone (ZoneId.systemDefault()) is passed to atZone
method.

'instant.atZone(ZoneId.systemDefault())' returns an instance of ZonedDateTime and


toLocalDate() method returns the corresponding instance of LocalDate.

Question 65: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.BiFunction;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. BiFunction<Integer, Integer, Character> compFunc = (i, j) -> i + j;
8. System.out.println(compFunc.apply(0, 65));
9. }
10. }

NOTE: ASCII value of A is 65.

What will be the result of compiling and executing Test class?


A


Compilation error
(Correct)


65
Explanation
BiFunction<T, U, R> : R apply(T t, U u);

BiFunction interface accepts 3 type parameters, first 2 parameters (T,U) are passed to
apply method and 3rd type parameter is the return type of apply method.

In this case, 'BiFunction<Integer, Integer, Character>' means apply method will have
declaration: 'Character apply(Integer d1, Integer d2)'.

Lambda expression should accept 2 Integer type parameters and must return
Character object.

Lambda expression is:

'(i, j) -> i + j', i + j returns an int type and int cannot be implicitly casted to Character
and this causes compilation error.

Question 66: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5. import java.util.concurrent.*;
6.  
7. class Accumulator {
8. private List<Integer> list = new ArrayList<>();
9.  
10. public synchronized void accumulate(int i) {
11. list.add(i);
12. }
13.  
14. public List<Integer> getList() {
15. return list;
16. }
17. }
18.  
19. public class Test {
20. public static void main(String [] args) {
21. ExecutorService s = Executors.newFixedThreadPool(1000);
22. Accumulator a = new Accumulator();
23. for(int i=1; i<=1000; i++) {
24. int x = i;
25. s.execute(() -> a.accumulate(x));
26. }
27. s.shutdown();
28. System.out.println(a.getList().size());
29. }
30. }
What will be the result of compiling and executing Test class?

It can print any number between 0 and 1000
(Correct)


It will always print 1000 on to the console


The program will wait indefinitely

Explanation
As 'list.add(i);' is invoked inside synchronized method, hence adding to list is thread-
safe.

shutdown() doesn't wait for previously submitted tasks to complete execution and as
all submitted tasks execute in parallel hence list can contain any number of elements
between 1 and 1000.

It will be a rare case when none of the tasks were completed and shutdown() invoked
before that, but still that's a chance and if it happens then list will have no elements.

Question 67: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. interface Printer1 {
4. default void print() {
5. System.out.println("Printer1");
6. }
7. }
8.  
9. interface Printer2 {
10. default void print() {
11. System.out.println("Printer2");
12. }
13. }
14.  
15. class Printer implements Printer1, Printer2 {
16.  
17. }
18.  
19. public class Test {
20. public static void main(String[] args) {
21. Printer printer = new Printer();
22. printer.print();
23. }
24. }

What will be the result of compiling and executing Test class?



Compilation error for Printer
(Correct)


Printer2


Compilation error for Printer1


Compilation error for Printer2


Printer1

Explanation
Starting with JDK 8, a Java interface can have default and static methods. So, no
issues in Printer1 and Printer2 interfaces.

Printer class inherits both the default methods and hence compilation error.

To resolve this error, override the print() method in Printer class:

public void print() {


System.out.println("Printer");
}

To invoke print() method of Parent interfaces from within the overriding method, you
can use below syntax:

public void print() {


System.out.println("Printer");
Printer1.super.print();
Printer2.super.print();
}

Question 68: Skipped
Which of the 4 interfaces must be implemented by a JDBC driver?

java.sql.Date


java.sql.DriverManager


java.sql.Driver
(Correct)


java.sql.Connection
(Correct)


java.sql.ResultSet
(Correct)


java.sql.Statement
(Correct)

Explanation
DriverManager and Date are classes and hence not correct options.

A JDBC drive must provide implementation for Driver, Statement,


PreparedStatement, CallableStatement, ResultSet and Connection interfaces.

Question 69: Skipped
Given structure of EMPLOYEE table:

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))

EMPLOYEE table contains below records:

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws Exception {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
13. ) {
14. ResultSet rs = stmt.executeQuery(query);
15.
16. rs.absolute(3);
17. rs.updateString(3, "Gales");
18. rs.updateRow();
19. rs.refreshRow();
20. System.out.println(rs.getString(2) + " " + rs.getString(3));
21. }
22. }
23. }

Also assume:

URL is correct and db credentials are: root/password.

SQL query is correct and valid.

The JDBC 4.2 driver jar is configured in the classpath.

Updates on EMPLOYEE table are being done by Test.java code only.

What will be the result of compiling and executing Test class?


John Smith


Natasha George


Regina Williams


Regina Gales
(Correct)
Explanation
Given query returns below records:

101 John    Smith   12000   

102 Sean    Smith   15000   

103 Regina  Williams    15500   

104 Natasha George  14600   

'rs.absolute(3);' moves the cursor to the 3rd row.

'rs.updateString(3, "Gales");' updates LASTNAME field of 3rd row from 'Williams' to


'Gales'.

'rs.updateRow();' commits the changes to the database.

'rs.refreshRow();' It refreshes the current row (which is 3rd now) with its most recent
value in the database. There is no change to the cursor position.

System.out.println(rs.getString(2) + " " + rs.getString(3)); prints the 2nd and 3rd


column values of 3rd row, which are 'Regina' and 'Gales'.

Question 70: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.sql.SQLException;
5.  
6. class MyResource implements AutoCloseable {
7. @Override
8. public void close() throws IOException{
9. throw new IOException("IOException");
10. }
11.  
12. public void execute() throws SQLException {
13. throw new SQLException("SQLException");
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. try(MyResource resource = new MyResource()) {
20. resource.execute();
21. } catch(Exception e) {
22. System.out.println(e.getMessage());
23. }
24. }
25. }
What will be the result of compiling and executing Test class?

IOException


SQLException
(Correct)


Compilation error

Explanation
execute() method throws an instance of SQLException.

Just before finding the matching handler, Java runtime executes close() method. This
method throws an instance of IOException but it gets suppressed and an instance of
SQLException is thrown.

e.getMessage() prints SQLException on to the console.

NOTE: e.getSuppressed() returns Throwable [] and this helps to get all the
suppressed exceptions.

Question 71: Skipped
Below is the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class Outer {
4. static class Inner {
5. static void greetings(String s) {
6. System.out.println(s);
7. }
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. /*INSERT*/
14. }
15. }

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

Outer.Inner.greetings("HELLO!");  
(Correct)


Inner.greetings("HELLO!");  


1. Outer.Inner inner1 = new Outer().new Inner();
2. inner1.greetings("HELLO!");


1. Outer.Inner inner2 = new Outer.Inner();
2. inner2.greetings("HELLO!");

(Correct)

Explanation
Outside of top-level class, Outer, static nested class can be referred by using TOP-
LEVEL-CLASS.STATIC-NESTED-CLASS. So, in this case correct way to refer static
nested class is Outer.Inner.

greetings(String) is a static method, so it can be invoked by using the class name,


which is by the statement: Outer.Inner.greetings("...");

Even though it is not preferred to invoke static method in non-static manner, but you
can use the instance of class to invoke its static method.

To Create the instance of static nested class, syntax is: new TOP-LEVEL-
CLASS.STATIC-NESTED-CLASS(...);

in this case, new Outer.Inner();

Question 72: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Set<String> set = new TreeSet<>(Arrays.asList(null,null,null));
8. long count = set.stream().count();
9. System.out.println(count);
10. }
11. }

What will be the result of compiling and executing Test class?



3

Runtime Exception
(Correct)


1


0

Explanation
TreeSet cannot contain null values.

Hence, 'new TreeSet<>(Arrays.asList(null,null,null));' throws NullPointerException.

Question 73: Skipped
For the given code:
1. package com.udayan.ocp;
2.  
3. interface Operator {
4. int operate(int i, int j);
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Operator opr = new Operator() {
10. public int operate(int i, int j) {
11. return i + j;
12. }
13. };
14. System.out.println(opr.operate(10, 20));
15. }
16. }

Which of the following options successfully replace anonymous inner class code with
lambda expression code?

Select 3 options.


Operator opr = (x, y) -> { return x + y; };  
(Correct)


Operator opr = (int x, int y) -> { return x + y; };  
(Correct)


Operator opr = (x, y) -> x + y;  
(Correct)


Operator opr = x, y -> x + y;  


Operator opr = (x, y) -> return x + y;  

Explanation
Operator opr = (int x, int y) -> { return x + y; }; => Correct, operate(int, int) method
accepts two int type parameters and returns the addition of passed parameters. 

Operator opr = (x, y) -> { return x + y; }; => Correct, type is removed from left part,
type inference handles it. 

Operator opr = (x, y) ->  return x + y; => Compilation error, if there is only one
statement in the right side then semicolon inside the body, curly brackets and return
statement(if available) can be removed. But all should be removed. You can't just
remove one and leave others. 

Operator opr = (x, y) ->  x + y; => Correct, semicolon inside the body, curly brackets
and return statement, all 3 are removed from right side. 

Operator opr = x, y ->  x + y;  => Compilation error, if there are no parameters or
more than one parameter available, then round brackets cannot be removed from
left side.

Question 74: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Locale;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Locale loc = new Locale("it", "IT"); //Line 7
8. loc.setDefault(loc); //Line 8
9. System.out.println(Locale.getDefault());
10. }
11. }

Which of the following statement is correct about above code?



Line 8 causes compilation failure.

Code compiles and executes successfully and prints it_IT on to the console.
(Correct)


Code compiles and execute successfully but may print text other than it_IT.

Explanation
setDefault(Locale) is a static method defined inside Locale class but static method
can be invoked using instance reference as well.

Compiler changes 'loc.setDefault(loc);' to 'Locale.setDefault(loc);'.

Line 8 doesn't cause any compilation error and on execution it sets the default locale
to it_IT.

Hence, Locale.getDefault() will always return it_IT.

Question 75: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.Date;
4. import java.util.function.*;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. /*INSERT*/ obj = Date::new;//Constructor reference for Date() constructor
9. Date date = obj.get(); //Creates an instance of Date class.
10. System.out.println(date);
11. }
12. }

Which of the following options can replace /*INSERT*/ such that on executing Test
class, current date and time is displayed in the output?

Supplier<Date>
(Correct)


Supplier


Function<Date>

Function


Function<Object>


Supplier<Object>

Explanation
Date date = obj.get(); means get() method of the interface is invoked. get() method is
declared in Supplier interface. All options of Function interface are incorrect.

Supplier interface's declaration is: public interface Supplier<T> { T get(); }. 

Note: No parameters are specified in get() method, this means no-argument


constructor of Date class is invoked by Date::new.

Supplier<Date> can replace /*INSERT*/. 

If you use raw type, Supplier or parameterized type Supplier<Object>, then obj.get()
method would return Object type.

So Date date = obj.get(); will have to be converted to Date date = (Date)obj.get(); but
you are allowed to replace /*INSERT*/ only, hence Supplier and Supplier<Object>
are incorrect options.

Question 76: Skipped
Consider below codes: 
1. package com.udayan.ocp;
2.  
3. class A<T extends String> {
4.
5. }
6.  
7. class B<T super String> {
8.
9. }

Which of the following statement is correct?



Only class A compiles successfully
(Correct)


Both class A and B compiles successfully


Only class B compiles successfully

Explanation
super is used with wildcard (?) only.
Question 77: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. class Rope {
7. int length;
8. String color;
9.
10. Rope(int length, String color) {
11. this.length = length;
12. this.color = color;
13. }
14.
15. public String toString() {
16. return "Rope [" + color + ", " + length + "]";
17. }
18.
19. static class RedRopeFilter {
20. boolean filter(Rope rope) {
21. return rope.color.equalsIgnoreCase("Red");
22. }
23. }
24. }
25.  
26. public class Test {
27. public static void main(String[] args) {
28. List<Rope> list = new ArrayList<>();
29. list.add(new Rope(5, "red"));
30. list.add(new Rope(10, "Red"));
31. list.add(new Rope(7, "RED"));
32. list.add(new Rope(10, "green"));
33. list.add(new Rope(7, "Blue"));
34.
35. list.stream().filter(new
Rope.RedRopeFilter()::filter).forEach(System.out::println); //Line n1
36. }
37. }

What will be the result of compiling and executing Test class?



Line n1 causes compilation error


Rope [Red, 10]


Rope [green, 10]
Rope [Blue, 7]

Rope [red, 5]
Rope [Red, 10]
Rope [RED, 7]
(Correct)


Rope [red, 5]
Rope [Red, 10]
Rope [RED, 7]
Rope [green, 10]
Rope [Blue, 7]

Explanation
'new Rope.RedRopeFilter()::filter' is an example of "Reference to an Instance Method
of a Particular Object".

Equivalent lambda expression is: '(Rope r) -> new Rope.RedRopeFilter().filter(r)'.

As filter(...) method accepts Predicate<? super Point> instance as an argument, hence


given method reference syntax is the correct implementation of the Predicate. Line
n1 compiles successfully.

Result of filtration is the Stream<Rope> instance containing Rope objects of 'red'


color. Please note string 'red' can be in any case(upper, lower or mixed) Therefore,
this stream contains Rope [red, 5], Rope [Red, 10] and Rope [RED, 7].

forEach(System.out::println) prints Rope [red, 5], Rope [Red, 10] and Rope [RED, 7])
on to the console.

If 'filter(Rope)' is declared as static, then to achieve same output, you will have to
change the method reference syntax to: 'filter(Rope.RedRopeFilter::filter)'.

Question 78: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date = LocalDate.ofEpochDay(1);
8. System.out.println(date);
9. }
10. }

What will be the result of compiling and executing Test class?



1970-1-1


1970-01-02
(Correct)


1970-1-2


1970-01-01

Explanation
0th day in epoch is: 1970-01-01, 1st day in epoch is: 1970-01-02 and so on.

As toString() method of LocalDate class prints the LocalDate object in ISO-8601


format: "uuuu-MM-dd". Hence output is: '1970-01-02'.

Question 79: Skipped
Consider the code of Test.java file:
1. //Test.java
2. package com.udayan.ocp;
3.  
4. class Player {
5. String name;
6. int age;
7. Player() {
8. this.name = "Virat";
9. this.age = 29;
10. }
11.
12.     public int hashCode() {
13. return 100;
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. System.out.println(new Player());
20. }
21. }

Hexadecimal representation of 100 is 64.

Which of the following option is correct?


None of the other options


Code doesn't compile successfully


Code compiles successfully but throws an exception on executing it


Code compiles successfully and on execution always prints
"com.udayan.ocp.Player@64" on to the console
(Correct)

Explanation
If toString() method is not overridden, then Object class's version is invoked.

The toString() method in Object class has below definition:

public String toString() {


return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So, in the output you get: fully-qualified-name-of-the-class@hexadecimal-


representation-of-hash-code. NOTE: hashCode() method is called for that.

Player class overrides the hashCode() method so, toString() method calls this
overriding hashCode() method. Output string will always contain 64.

Question 80: Skipped
F: is accessible for reading and below is the directory structure for F:
1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java

Given code of Test.java file: 

package com.udayan.ocp;

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7. import java.io.File;
8.  
9. public class Test {
10. public static void main(String[] args) throws IOException{
11. Path path = Paths.get("F:\\A\\B");
12. /*INSERT*/
13. }
14. }

Which of the following statements, if used to replace /*INSERT*/, will successfully


print 'true' on to the console?
Select 3 options. 

System.out.println(Files.getAttribute(path, "isDirectory"));  
(Correct)


System.out.println(File.isDirectory(path));  


System.out.println(path.toFile().isDirectory());  
(Correct)


System.out.println(Files.isDirectory(path));  
(Correct)


System.out.println(new File(path).isDirectory());  

Explanation
'B' is a directory.

java.nio.file.Files (not java.io.File) class has static method isDirectory(Path) to check if


the farthest element of given path is directory or not. 'Files.isDirectory(path)' returns
true.

Interface Path has toFile() method to return the java.io.File object representing this
path. And java.io.File class has isDirectory() method to check if given File object is
directory or not. 'path.toFile().isDirectory()' returns true.

Files.getAttribute(Path path, String attribute, LinkOption... options) returns the value


corresponding to passed attribute. IllegalArgumentException is thrown if attribute is
not spelled correctly.
Files.getAttribute(path, "isDirectory") returns true.

There is no static method, isDirectory(Path) in java.io.File class, hence


'File.isDirectory(path)' causes compilation error.

There is no constructor of File class accepting Path, hence new File(path) causes
compilation error.

Question 81: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. class MyString {
7. String str;
8. MyString(String str) {
9. this.str = str;
10. }
11. }
12.  
13. public class Test {
14. public static void main(String[] args) {
15. List<MyString> list = new ArrayList<>();
16. list.add(new MyString("Y"));
17. list.add(new MyString("E"));
18. list.add(new MyString("S"));
19.
20. list.stream().map(s -> s).forEach(System.out::print);
21. }
22. }

Which of the following statements are correct?



Above code causes compilation error


Above code terminates successfully without printing anything on to the console


On execution, above code prints "YES" on to the console


Above code terminates successfully after printing text other than "YES" on to the
console
(Correct)

Explanation
MyString class doesn't override toString() method, hence when instance of MyString
class passed to System.out.print(...) method, it prints <fully-qualified-class-
name>@<hex-value-of-hashcode>.

list.stream() returns an object of Stream<MyString> and this stream object has 3


instances of MyString class.

map(s -> s) returns the Stream<MyString> object containing exactly same 3


instances of MyString class.

forEach(System.out::print) prints text in the format <fully-qualified-class-


name>@<hex-value-of-hashcode> for all the 3 instances.

Text in above format is printed for the 3 elements of the stream and program
terminates successfully.

Hence correct option is: 'Above code terminates successfully after printing text other
than "YES" on to the console'

To print "YES" on to the console, change the last statement to: list.stream().map(s ->
s.str).forEach(System.out::print);

's' represents the instance of MyString class and as MyString class is defined within
the same package, hence instance variable 'str' can be accessed using dot operator.

Question 82: Skipped
Given code: 
1. package com.udayan.ocp;
2.  
3. public class Test {
4. class A {
5. void m() {
6. System.out.println("INNER");
7. }
8. }
9.
10. public static void main(String [] args) {
11. //Insert statement here
12. }
13. }

Which statement when inserted in the main(String []) method will print "INNER" in
the output?

Select 2 options.


1. Test.A a4 = this.new A();
2. a4.m();


1. Test.A a2 = new Test().new A();
2. a2.m();

(Correct)


1. A a1 = new Test().new A();
2. a1.m();

(Correct)


1. A a3 = this.new A();
2. a3.m();

Explanation
There are 2 parts: 1st one is referring the name of inner class, A and 2nd one is
creating the instance of inner class, A. 

main method is inside Test class only, so inner class can be referred by 2 ways: A or
Test.A. 

As, A is Regular inner class, so instance of outer class is needed for creating the
instance of inner class. As keyword 'this' is not allowed inside main method, so
instance of outer class, Test can only be obtained by new Test(). Instance of inner
class can be created by: new Test().new A(); 

Also note, keyword 'this' is not allowed static main method.

Question 83: Skipped
Consider the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. enum Flags {
4. TRUE, FALSE;
5.  
6. Flags() {
7. System.out.println("HELLO");
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. Flags flags = Flags.TRUE;
14. }
15. }
What will be the result of compiling and executing Test class?

HELLO is printed twice
(Correct)


Exception is thrown at runtime


None of the other options


HELLO is printed once

Explanation
Enum constructor is invoked once for every constant.

For 'Flags.TRUE', enum constructor is invoked for TRUE as well as FALSE.

Question 84: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayDeque;
4. import java.util.Deque;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Deque<Character> chars = new ArrayDeque<>();
9. chars.add('A');
10. chars.remove();
11. chars.remove();
12.  
13. System.out.println(chars);
14. }
15. }

What will be the result of compiling and executing Test class?



[A]


[]


Runtime Exception
(Correct)

Explanation
Deque's add() method invokes addLast(E) method and remove() method invokes
removeFirst() method.

chars.add('A'); => [A], 

chars.remove(); => [], 

chars.remove(); => No elements left to remove() and hence


java.util.NoSuchElementException is thrown at runtime.

Question 85: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class Printer implements Runnable {
6. public void run() {
7. System.out.println("Printing");
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. ExecutorService es = Executors.newFixedThreadPool(1);
14. /*INSERT*/
15. es.shutdown();
16. }
17. }

Which of the following statements, if used to replace /*INSERT*/, will print 'Printing'
on to the console?

Select 2 options.


es.start(new Printer());  


es.execute(new Printer());  
(Correct)


es.submit(new Printer());  
(Correct)


es.run(new Printer());  
Explanation
ExecutorService interface has following methods:

Future<?> submit(Runnable task);   

<T> Future<T> submit(Runnable task, T result);   

<T> Future<T> submit(Callable<T> task);   

Hence, 'es.submit(new Printer());' is one of the correct options. 

ExecutorService interface extends Executor interface and it has 'void


execute(Runnable command);' method. Hence, 'es.execute(new Printer());' is the 2nd
correct option.

Question 86: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class Player extends Thread {
6. CyclicBarrier cb;
7.  
8. public Player(CyclicBarrier cb) {
9. this.cb = cb;
10. }
11.  
12. public void run() {
13. try {
14. cb.await();
15. } catch (InterruptedException | BrokenBarrierException e) {}
16. }
17. }
18.  
19. class Match implements Runnable {
20. public void run() {
21. System.out.println("Match is starting...");
22. }
23. }
24.  
25. public class Test {
26. public static void main(String[] args) {
27. Match match = new Match();
28. CyclicBarrier cb = new CyclicBarrier(2, match);
29. ExecutorService es = Executors.newFixedThreadPool(1);
30. es.execute(new Player(cb));
31. es.execute(new Player(cb));
32. es.shutdown();
33. }
34. }
What will be the result of compiling and executing Test class?

'Match is starting...' is never printed on to the console and program waits
indefinitely.
(Correct)


'Match is starting...' is printed on to the console and program doesn't terminate.


'Match is starting...' is printed on to the console and program terminates
successfully.

Explanation
ExecutorService can handle 1 thread, but 2 threads are submitted. The first thread
calls await() and wait endlessly. 

CyclicBarrier needs 2 threads to call await() method but as this is not going to
happen, hence the program waits endlessly.

'Match is starting...' is never printed on to the console and program waits


indefinitely. 

NOTE: To trip the CyclicBarrier, replace 'Executors.newFixedThreadPool(1);' with


'Executors.newFixedThreadPool(2);'.

Question 87: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600
Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4. import java.util.Properties;
5.  
6. public class Test {
7. public static void main(String[] args) throws SQLException {
8. String url = "jdbc:mysql://localhost:3306/ocp";
9. Properties prop = new Properties();
10. prop.put("username", "root");
11. prop.put("password", "password");
12. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
13.  
14. try (Connection con = DriverManager.getConnection(url, prop);
15. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
16. ResultSet rs = stmt.executeQuery(query);) {
17. rs.relative(1);
18. System.out.println(rs.getString(2));
19. }
20. }
21. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


Sean


An exception is thrown at runtime.
(Correct)


John


Smith

Explanation
As credentials are passed as java.util.Properties so user name should be passed as
"user" property and password should be passed as "password" property.
In the given code, 'prop.put("username", "root");' name of property is 'username' and
not 'user' and that is why SQLException is thrown at runtime.

Question 88: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. int ref = 10;
9. List<Integer> list = new ArrayList<>();
10. list.stream().anyMatch(i -> {
11. System.out.println("HELLO");
12. return i > ref;
13. });
14. }
15. }

What will be the result of compiling and executing Test class?



HELLO


Compilation error


Program executes successfully but nothing is printed on to the console
(Correct)

Explanation
Method signature for anyMatch method:

boolean anyMatch(Predicate<? super T>) : Returns true if any of the stream element
matches the given Predicate.

If stream is empty, it returns false and predicate is not evaluated.

As given stream is empty, hence predicate is not evaluated and nothing is printed on
to the console.

Question 89: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Scanner;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try(Scanner scanner = new Scanner(System.in)) {
8. int i = scanner.nextInt();
9. if(i % 2 != 0) {
10. assert false;
11. }
12. } catch(Exception ex) {
13. System.out.println("ONE");
14. } catch(Error ex) {
15. System.out.println("TWO");
16. }
17. }
18. }

What will be the result of compiling and executing Test class?


User input: 1

TWO


Program ends abruptly


ONE


No output and program terminates successfully
(Correct)

Explanation
Assertions are disabled by default, so assert false; statement is not executed.

No output is shown and program terminates successfully.

If above program is run with -ea option, the 'TWO' will be printed on to the console
as AssertionError extends Error.

NOTE: It is not a good programming practice to validate user input using assertion.

Question 90: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class MyCallable implements Callable<Integer> {
6. private Integer i;
7.  
8. public MyCallable(Integer i) {
9. this.i = i;
10. }
11.  
12. public Integer call() throws Exception {
13. return --i;
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) throws InterruptedException,
ExecutionException {
19. ExecutorService es = Executors.newSingleThreadExecutor();
20. MyCallable callable = new MyCallable(100);
21. System.out.println(es.submit(callable).get());
22. System.out.println(es.submit(callable).get());
23. es.shutdown();
24. }
25. }

What will be the result of compiling and executing Test class?



99
98
(Correct)


98
98


99
99


100
99


100
100

Explanation
'Executors.newSingleThreadExecutor();' creates an Executor that uses a single worker
thread.

'new MyCallable(100);' creates MyCallable object and initializes its property i to 100.
'es.submit(callable)' invokes the call method and returns a Future object containing
Integer value 99. get() method prints this value on to the console.

'es.submit(callable)' is invoked again for the same MyCallable instance, call method
returns a Future object containing Integer value 98. get() method prints this value on
to the console.

Practice Test 3 - Results

 Return to review

Attempt 1
All knowledge areas

All questions

Question 1: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Set;
4. import java.util.TreeSet;
5. import java.util.stream.Collectors;
6. import java.util.stream.Stream;
7.  
8. public class Test {
9. public static void main(String[] args) {
10. Stream<String> stream = Stream.of("java", "python", "c",
11. "c++", "java", "python");
12. Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));
13. System.out.println(set);
14. }
15. }
What will be the result of compiling and executing Test class?

[java, python, c, c++]


[c++, c, java, python]

Order of elements can't be predicted in the output.


[c, c++, java, python]
(Correct)

Explanation
'TreeSet::new' is same as '() -> new TreeSet()'

TreeSet contains unique elements and in sorted order, in this case natural order.

Output will always be: [c, c++, java, python]

Question 2: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. try {
6. main(args);
7. } catch (Exception ex) {
8. System.out.println("CATCH-");
9. }
10. System.out.println("OUT");
11. }
12. }
What will be the result of compiling and executing Test class?

OUT


Compilation error


CATCH-OUT


None of the System.out.println statements are executed
(Correct)

Explanation
main(args) method is invoked recursively without specifying any exit condition, so
this code ultimately throws java.lang.StackOverflowError. StackOverflowError is a
subclass of Error type and not Exception type, hence it is not handled. Stack trace is
printed to the console and program ends abruptly.

Java doesn't allow to catch specific checked exceptions if these are not thrown by the
statements inside try block. 

catch(java.io.FileNotFoundException ex) {} will cause compilation error in this case as


main(args); will never throw FileNotFoundException. But Java allows to catch
Exception type, hence catch (Exception ex) {} doesn't cause any compilation error.

Question 3: Skipped

Given structure of MESSAGES table:


MESSAGES (msg1 varchar(100), msg2 varchar(100))  

MESSAGES table contains below records: 


'Happy New Year!', 'Happy Holidays!'

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "DELETE FROM MESSAGES";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt = con.createStatement();
13. ResultSet rs = stmt.executeQuery(query);)
14. {
15. rs.next();
16. System.out.println(rs.getInt(1));
17. }
18. }
19. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


Compilation error

1


0


An exception is thrown at runtime
(Correct)

Explanation
stmt.executeQurey(String) method can accept any String and it returns ResultSet
instance, hence no compilation error. 

But stmt.executeQuery(String) method cannot issue INSERT, UPDATE and DELETE


statements. Hence, 'stmt.executeQuery(query)' throws SQLException at runtime. 

To issue INSERT, UPDATE or DELETE statements either use stmt.execute(String)


method OR stmt.executeUpdate(String) method. 

try (Connection con = DriverManager.getConnection(url, user, password);


Statement stmt = con.createStatement();)
{
boolean res = stmt.execute(query);
System.out.println(stmt.getUpdateCount());
}

OR

try (Connection con = DriverManager.getConnection(url, user, password);


Statement stmt = con.createStatement();)
{
System.out.println(stmt.executeUpdate(query));
}

Question 4: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4. import java.time.format.DateTimeFormatter;
5.  
6. public class Test {
7. public static void main(String [] args) {
8. LocalDate date = LocalDate.of(2018, 11, 4);
9. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
10. System.out.println(formatter.format(date).equals(date.format(formatter)));
11. }
12. }
What will be the result of compiling and executing Test class?

Compilation Error


false


true
(Correct)

Explanation
DateTimeFormatter.ofPattern(String) accepts String argument. Format string is also
correct. 

d represents day-of-month, M represents month-of-year and u represents year.   

New Date/Time API has format method in DateTimeFormatter as well as LocalDate,


LocalTime, LocalDateTime, ZonedDateTime classes.

formatter.format(date) returns "04-11-2018" and date.format(formatter) returns "04-


11-2018" and hence 'true' is printed on to the console.

Question 5: Skipped

Given structure of EMPLOYEE table: 


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 


1. 101 John Smith 12000
2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4. import java.util.Properties;
5.  
6. public class Test {
7. public static void main(String[] args) throws Exception {
8. String url = "jdbc:mysql://localhost:3306/ocp";
9. Properties prop = new Properties();
10. prop.put("user", "root");
11. prop.put("password", "password");
12. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
13. try (Connection con = DriverManager.getConnection(url, prop);
14. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
15. ResultSet rs = stmt.executeQuery(query);)
16. {
17. rs.afterLast();
18. rs.relative(-1);
19. rs.previous();
20. System.out.println(rs.getInt(1));
21. }
22. }
23. }

Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class? 


102


104


103
(Correct)


101
Explanation
As credentials are passed as java.util.Properties so user name should be passed as
"user" property and password should be passed as "password" property.

In the given code, correct property names 'user' and 'password' are used. As URL and
DB credentials are correct, hence no issues in connecting the database. 

Given query returns below records:

101 John Smith 12000   

102 Sean Smith 15000   

103 Regina Williams 15500   

104 Natasha George 14600   

'rs.afterLast();' moves the cursor after 4th record. 

'rs.relative(-1);' moves the cursor to the 4th record. 

'rs.previous()' moves the cursor to the 3rd record.

'rs.getInt(1)' returns 103.

Question 6: Skipped

Which of the following statements successfully create a Locale instance?

Select 3 options.


Locale loc5 = new Locale("", "", "");  
(Correct)


Locale loc3 = new Locale("");  
(Correct)


Locale loc2 = new Locale(loc1);  

Locale loc4 = new Locale("", "");  
(Correct)


Locale loc1 = new Locale();  
Explanation
Question only talks about successful creation of Locale instance.

Locale class has 3 public overloaded constructors:

Locale(String language)

Locale(String language, String country)

Locale(String language, String country, String variant)

But constructor with no-argument and constructor that accepts another Locale
instance are not available. Hence 'new Locale();' and 'new Locale(loc1);' causes
compilation error. 

Passing blank string is OK and Locale objects are successfully created.

NOTE: If you pass null as argument to any of the overloaded constructors, then
NullPointerException will be thrown and Locale objects will not be successfully
created in that case.

Question 7: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<Integer> list = Arrays.asList(10, 100, 1000);
9. list.replaceAll(i -> -i++);
10.  
11. System.out.println(list);
12. }
13. }
What will be the result of compiling and executing Test class? 

[-9, -99, -999]


Compilation error


[10, 100, 1000]


[-11, -101, -1001]


[-10, -100, -1000]
(Correct)

Explanation
replaceAll(UnaryOperator<E> operator) is the default method added in List
interface. 

interface UnaryOperator<T> extends Function<T, T>. 

As List is of Integer type, this means operator must be of UnaryOperator<Integer>


type only. Its accept method should have signature: Integer apply(Integer s); 

Lambda expression 'i -> -i++' is correctly defined for apply method.

Unary post increment(++) operator has higher precedence than unary minus(-)
operator.

i -> -i++ = i -> -(i++). NO COMPILATION ERROR here.

Post increment operator is applied after the value is used, which means in this case
list elements are replaced with -10, -100 and -1000.
Question 8: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Player {
4. String name;
5. int age;
6.  
7. Player(String name, int age) {
8. this.name = name;
9. this.age = age;
10. }
11.  
12. public String toString() {
13. return name + ", " + age;
14. }
15.  
16. public boolean equals(Player player) {
17. if(player != null && this.name.equals(player.name)
18. && this.age == player.age) {
19. return true;
20. }
21. return false;
22. }
23. }
24.  
25. public class Test {
26. public static void main(String[] args) {
27. Object p1 = new Player("Sachin", 44);
28. Object p2 = new Player("Sachin", 44);
29. System.out.println(p1.equals(p2));
30. }
31. }
What will be the result of compiling and executing Test class?

false
(Correct)


Compilation error in Test class


true


Compilation error in Player class

Explanation
Object class contains:
public boolean equals(Object obj) {
return (this == obj);
}
Class Player doesn't override equals(Object) method rather it overloads the equals
method: equals(Player).

As p2 is of Object type, p1.equals(p2) invokes the equals(Object) method defined in


Object class and as this method compares the reference (memory address), hence it
returns false in this case.

Below code will correctly override equals(Object) method in the Player class:

public boolean equals(Object player) {


if(player instanceof Player) {
Player p = (Player)player;
if(this.name.equals(p.name) && this.age == p.age)
return true;
}
return false;
}

Question 9: Skipped

Given structure of EMPLOYEE table: 


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4. import java.util.Properties;
5.  
6. public class Test {
7. public static void main(String[] args) throws SQLException {
8. String url = "jdbc:mysql://localhost:3306/ocp";
9. Properties prop = new Properties();
10. prop.put("user", "root");
11. prop.put("password", "password");
12. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
13.  
14. try (Connection con = DriverManager.getConnection(url, prop);
15. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
16. ResultSet rs = stmt.executeQuery(query);) {
17. rs.relative(1);
18. System.out.println(rs.getString(2));
19. }
20. }
21. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


John
(Correct)


Smith


An exception is thrown at runtime

Sean

Explanation
As credentials are passed as java.util.Properties so user name should be passed as
"user" property and password should be passed as "password" property.

In the given code, correct property names 'user' and 'password' are used. As URL and
DB credentials are correct, hence no issues in connecting the database. 

Given sql query returns below records:

101 John Smith 12000

102 Sean Smith 15000


103 Regina Williams 15500

104 Natasha George 14600

Initially the cursor stays just before the first record. 

'rs.relative(1);' moves the cursor to the first record. 

Column index starts with 1 and not 0, so 'rs.getString(2)' returns 'John'.

Question 10: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. interface Printer1 {
4. default void print() {
5. System.out.println("Printer1");
6. }
7. }
8.  
9. interface Printer2 {
10. public static void print() {
11. System.out.println("Printer2");
12. }
13. }
14.  
15. class Printer implements Printer1, Printer2 {
16.  
17. }
18.  
19. public class Test {
20. public static void main(String[] args) {
21. Printer printer = new Printer();
22. printer.print();
23. }
24. }
What will be the result of compiling and executing Test class?

Compilation error for Printer1


Compilation error for Printer


Printer1
(Correct)

Compilation error for Printer2


Printer2

Explanation
Starting with JDK 8, a Java interface can have default and static methods. So, no
issues in Printer1 and Printer2 interfaces.

Printer class implements both the interfaces: Printer1 and Printer 2. static method
cannot be overridden, hence doesn't conflict with default method.

No compilation error anywhere. On execution default method is invoked and


'Printer1' is printed on to the console.

If you want to invoke static method defined in Printer2 interface, then use:
Printer2.print();

Question 11: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.sql.SQLException;
5.  
6. class MyResource implements AutoCloseable {
7. @Override
8. public void close() throws IOException{
9. throw new IOException("IOException");
10. }
11.  
12. public void execute() throws SQLException {
13. throw new SQLException("SQLException");
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. try(MyResource resource = new MyResource()) {
20. resource.execute();
21. } catch(Exception e) {
22. System.out.println(e.getSuppressed()[0].getMessage());
23. }
24. }
25. }
What will be the result of compiling and executing Test class?

Compilation error


IOException
(Correct)


SQLException

Explanation
execute() method throws an instance of SQLException.

Just before finding the matching handler, Java runtime executes close() method. This
method throws an instance of IOException but it gets suppressed and an instance of
SQLException is thrown.

e.getSuppressed() returns Throwable [] whose 1st element is the instance of


suppressed exception, IOException.

'e.getSuppressed()[0].getMessage()' prints IOException on to the console.

Question 12: Skipped

F: is accessible for reading and below is the directory structure for F:


1. F:.
2. └───process
3. file.txt
4. file.docx
5. file.pdf
Above 3 files contain HELLO as the only word in the files. "file.txt" is a text file,
"file.docx" is a Microsoft Word document and "file.pdf" is a PDF file.
        
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7. import java.util.stream.Stream;
8.  
9. public class Test {
10. public static void main(String[] args) throws IOException {
11. Stream<Path> paths = Files.walk(Paths.get("F:\\process"));
12. paths.filter(path -> !Files.isDirectory(path)).forEach(
13. path -> {
14. try {
15. Files.readAllLines(path).stream()
16. .forEach(System.out::println);
17. } catch (IOException e) {
18. System.out.println("FAILED");
19. }
20. }
21. );
22. }
23. }
What will be the result of compiling and executing Test class?

HELLO will be printed twice and FAILED will be printed once

HELLO will be printed thrice on to the console

FAILED will be printed thrice

HELLO will be printed once and FAILED will be printed twice
(Correct)

Explanation
Files.walk(Paths.get("F:\\process")) returns the object of Stream<Path> containing
"F:\\process", "F:\\process\file.txt", "F:\\process\file.docx" and "F:\\process\file.pdf". 

paths.filter(path -> !Files.isDirectory(path)) filters out the directory "F:\\process" and


process the 3 files.

Files.readAllLines method reads all the lines from the files using
StandardCharsets.UTF_8 but as pdf and docx files use different Charset, hence
exception is thrown for reading these files.

FAILED will be printed twice for pdf and docx files. And HELLO (content of file.txt) will
be printed once.

Files.readAllLines(path, StandardCharsets.ISO_8859_1) may allow you to read all the 3


files without Exception but these files store lots of other information font, formatting
etc. so output may not make any sense.

Question 13: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date = LocalDate.of(2019, 1, 1);
8. LocalTime time = LocalTime.of(0, 0);
9. ZoneId india = ZoneId.of("Asia/Kolkata");
10. ZonedDateTime zIndia = ZonedDateTime.of(date, time, india);
11.  
12. ZoneId us = ZoneId.of("America/Los_Angeles");
13. ZonedDateTime zUS = /*INSERT*/;
14.  
15. System.out.println(Duration.between(zIndia, zUS)); //Line 15
16. }
17. }
Current time in India is: 2019-01-01T00:00. Indians have started celebrating New
Year. 
Line 15 prints the duration for which Los Angeles citizens have to wait to celebrate
the new year. 
Which of the following statement replace /*INSERT*/ such that Line 15 prints the
correct duration?

zIndia.withZoneSameInstant(us)  


zIndia.withZoneSameLocal(us)  
(Correct)


Cannot be achieved by just replacing /*INSERT*/

Explanation
zIndia --> {2019-01-01T00:00+05:30[Asia/Kolkata]}. 

zIndia.withZoneSameLocal(us) => {2019-01-01T00:00-08:00[America/Los_Angeles]}.


It just changes the Zone but keeps the date and time same and this is what zUS
supposed to refer to. 

Duration.between(zIndia, zUS) returns 'PT13H30M' in this case. So, people of Los


Angeles have to wait for 13 hours 30 minutes to celebrate the new year.

zIndia.withZoneSameInstant(us) => {2018-12-31T10:30-08:00[America/Los_Angeles]}.


It just converts India time to Los Angeles time.
As both zIndia and zUS will refer to same instance of time, hence
'Duration.between(zIndia, zUS)' would return 'PT0S'. And this is not expected.

NOTE: If you intend to use 'zIndia.withZoneSameInstant(us);', then Line 15 should be


changed as below:

System.out.println(Duration.between(zUS.toLocalDateTime(),
zIndia.toLocalDateTime())); // would print 'PT13H30M'.   

To get positive duration value, first parameter should be earlier date/time.

Question 14: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. class Counter implements Runnable {
4. private static int i = 3;
5.  
6. public void run() {
7. System.out.print(i--);
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. Thread t1 = new Thread(new Counter());
14. Thread t2 = new Thread(new Counter());
15. Thread t3 = new Thread(new Counter());
16. Thread[] threads = {t1, t2, t3};
17. for(Thread thread : threads) {
18. thread.start();
19. }
20. }
21. }
What will be the result of compiling and executing Test class?

It will print three digits 321 but order can be different


It will print three digits 210 but order can be different


It will always print 210


It will always print 321

None of the other options
(Correct)

Explanation
Given program will print 3 digits but all 3 digits can be different or same as variable i is not
accessed in synchronized manner.

Question 15: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.text.*;
4. import java.time.format.DateTimeFormatter;
5. import java.util.Locale;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-
uuuu"); //Line n1
10. System.out.println(dateFormatter.parse("10-5-2019")); //Line n2
11. NumberFormat currFormatter = NumberFormat.getCurrencyInstance(Locale.US);
//Line n3
12. System.out.println(currFormatter.parse("$7.00")); //Line n4
13. }
14. }
What will be the result of compiling and executing Test class?

Line n4 causes compilation failure
(Correct)


Line n2 causes compilation failure

Code compiles successfully and on execution an exception is raised by Line n2

Code compiles successfully and on execution an exception is thrown by Line n4

Code compiles successfully and on execution no exception is thrown at runtime
Explanation
parse(...) method defined in new Date/Time API such as LocalDate, LocalTime,
LocalDateTime and DateTimeFormatter can throw java.time.DateTimeException
(which is a RuntimeException) but parse(...) method defined in NumberFormat class
declares to throw java.text.ParseException (which is a checked exception) and hence
needs to follow declare or handle rule.

As main(...) method doesn't provide try-catch block around Lind n4 and also it
doesn't declares to throw ParseException, so Line n4 causes compilation failure.
Question 16: Skipped

Consider below code: 


1. //Child.java
2. package com.udayan.ocp;
3.  
4. class Parent {
5. public void m() {
6. System.out.println("Parent");
7. }
8. }
9.  
10. public abstract class Child extends Parent { //Line 9
11. public static void main(String [] args) { //Line 10
12. new Parent().m(); //Line 11
13. }
14. }
What will be the result of compiling and executing Child class?

Compilation error at Line 11


Parent
(Correct)


Compilation error at Line 10


Compilation error at Line 9

Explanation
Parent is a concrete class.

In java it is possible for abstract class to not have any abstract methods.

Class Child is abstract, it extends Parent and doesn't contain any abstract method. It
contains special main method, so JVM can invoke this method.

Rest of the code is normal java code. new Parent().m(); creates an instance of Parent
class and invokes method m() on that instance. "Parent" is printed on to the console.

Question 17: Skipped

Does below code compile successfully?


1. class GenericPrinter<T> {}
2. abstract class AbstractGenericPrinter<X,Y,T> extends GenericPrinter<T>{}


No

Yes
(Correct)

Explanation
'GenericPrinter<T>' is generic type and is defined correctly. 

'AbstractGenericPrinter<X,Y,T>' is also a generic type and extends another generic


type 'GenericPrinter<T>'. 

NOTE: If a class extends from generic type, then it must pass type arguments to its
super class. Third type parameter, 'T' in 'AbstractGenericPrinter<X,Y,T>' correctly
passed type argument to super class, 'GenericPrinter<T>'. 

Below codes will not compile:

abstract class AbstractGenericPrinter<X,Y> extends GenericPrinter<T>{} => No way


to pass type argument to the type parameter, T of super class.

abstract class AbstractGenericPrinter extends GenericPrinter<T>{} => No way to pass


type argument to the type parameter, T of super class.

But below codes will compile successfully:

abstract class AbstractGenericPrinter<X,Y> extends GenericPrinter<String>{} =>


Type argument, 'String' is passed to the type parameter, T of super class.

abstract class AbstractGenericPrinter extends GenericPrinter<String>{} => Type


argument, 'String' is passed to the type parameter, T of super class.

Question 18: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.Instant;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. System.out.println(Instant.EPOCH);
8. }
9. }
What will be the result of compiling and executing Test class?

1970-01-01T00:00:00


1970-01-01T00:00:00Z
(Correct)


1970-01-01T00:00:00.000Z


1970-01-01T00:00:00.000

Explanation
DateTimeFormatter.ISO_INSTANT is used by the toString() method of Instant class
and it formats or parses an instant in UTC, such as '2018-10-01T15:02:01.231Z'.

EPOCH instant is: 1970-01-01T00:00:00Z and it is printed to the console.

NOTE: nano portion is 0 in EPOCH instant, hence it is ignored by toString() method.

Question 19: Skipped

Below is the code of Test.java file:


1. public class Test {
2. enum TrafficLight {
3. RED, YELLOW, GREEN;
4. }
5.
6. public static void main(String[] args) {
7. TrafficLight tl = TrafficLight.valueOf(args[1]);
8. switch(tl) {
9. case TrafficLight.RED:
10. System.out.println("STOP");
11. break;
12. case TrafficLight.YELLOW:
13. System.out.println("SLOW");
14. break;
15. case TrafficLight.GREEN:
16. System.out.println("GO");
17. break;
18. }
19. }
20. }
What will be the result of compiling and executing Test class by using the
commands: 
javac Test.java
java Test RED AMBER

No output


None of the other options
(Correct)


IllegalArgumentException is thrown


STOP

Explanation
case labels accept constant names only.

case TrafficLight.RED:, case TrafficLight.YELLOW: and case TrafficLight.GREEN: cause


compilation error.

Correct case labels should be:

case RED:, case YELLOW: and case GREEN:

Question 20: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. class MyException extends RuntimeException {
4. public void log() {
5. System.out.println("Logging MyException");
6. }
7. }
8.  
9. class YourException extends RuntimeException {
10. public void log() {
11. System.out.println("Logging YourException");
12. }
13. }
14.  
15. public class Test {
16. public static void main(String[] args) {
17. try {
18. throw new MyException();
19. } catch(MyException | YourException ex){
20. ex.log();
21. }
22. }
23. }
What will be the result of compiling and executing Test class?

Logging MyException


Compilation error
(Correct)


Runtime Exception


Logging YourException

Explanation
In a multi-catch block, type of reference variable (ex in this case) is the common base
class of all the Exception types mentioned, 'MyException' and 'YourException'.

This means ex is of RuntimeException. Method log() is not available in


RuntimeException or its super classes.

ex.log(); causes compilation failure.

Question 21: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. try {
6. try {
7. System.out.println(1/0);
8. } catch(ArithmeticException e) {
9. System.out.println("Inner");
10. throw e;
11. } finally {
12. System.out.println("Finally 1");
13. }
14. } catch(ArithmeticException e) {
15. System.out.println("Outer");
16. }
17. }
18. }
What will be the result of compiling and executing Test class?

Inner
Finally 1

Inner
Finally 1
Outer
(Correct)


Compilation Error

Inner
Outer
Finally 1
Explanation
System.out.println(1/0); throws ArithmeticException, handler is available in inner
catch block, it executes and prints "Inner" to the console. 

throw e; re-throws the exception. 

But before exception instance is forwarded to outer catch block, inner finally gets
executed and prints "Finally 1" to the console. 

In outer try-catch block, handler for ArithmeticException is available, so outer catch


block gets executed and prints "Outer" to the console.

Question 22: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. List<? extends String> list = new ArrayList<>(Arrays.asList("A", "E", "I",
"O")); //Line 8
8. list.add("U"); //Line 9
9. list.forEach(System.out::print);
10. }
11. }
What will be the result of compiling and executing Test class?

Line 8 causes compilation error


Line 9 causes compilation error
(Correct)


AEIO


Runtime exception


AEIOU

Explanation
Line 8 is a valid syntax but as upper-bounded wildcard is used, hence add operation
is not supported.

Line 9 causes compilation failure.

Question 23: Skipped

F: is accessible for reading/writing and below is the directory structure for F:


1. F:.
2. └───X
Directory X exists under F:.

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7.  
8. public class Test {
9. public static void main(String[] args) throws IOException{
10. Path path = Paths.get("F:\\X\\Y\\Z");
11. Files.createDirectories(path);
12. }
13. }

What will be the result of compiling and executing Test class?


An exception is thrown at runtime

Only directory Y will be created under X

Directory Y will be created under X and directory Z will be created under Y
(Correct)

Explanation
'Files.createDirectories(path);' creates a directory by creating all nonexistent parent
directories first.

So this method first creates directory Y under X and then directory Z under Y.

Question 24: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.ArrayDeque;
4. import java.util.Arrays;
5. import java.util.Deque;
6. import java.util.List;
7.  
8. public class Test {
9. public static void main(String[] args) throws Exception {
10. List<String> list = Arrays.asList("oca", null, "ocp", "java", "null");
//Line n1
11. Deque<String> deque = new ArrayDeque<String>(list); //Line n2
12. System.out.println(deque.size()); //Line n3
13. }
14. }
What will be the result of compiling and executing Test class?

NullPointerException is thrown at runtime
(Correct)


4

5

3
Explanation
ArrayDeque cannot store null, hence Line n2 throws NullPointerException exception.

ArrayDeque doesn't store null because its poll() method returns null in case
ArrayDeque is empty. If null element was allowed, then it would be not possible to
find out whether poll() method is returning null element or ArrayDeque is empty.

Question 25: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Collections;
5. import java.util.Comparator;
6. import java.util.List;
7.  
8. public class Test {
9. public static void main(String[] args) {
10. List<String> emails = Arrays.asList("[email protected]",
"[email protected]", "[email protected]",
11. "[email protected]");
12. Collections.sort(emails, Comparator.comparing(str ->
str.substring(str.indexOf("@") + 1)));
13. for(String email : emails) {
14. System.out.println(email);
15. }
16. }
17. }
What will be the result of compiling and executing Test class?

[email protected]
[email protected]
[email protected]
[email protected]

[email protected]
[email protected]
[email protected]
[email protected]

[email protected]
[email protected]
[email protected]
[email protected]
(Correct)


[email protected]
[email protected]
[email protected]
[email protected]
Explanation
Comparator is comparing on the basis of email domain: gmail.com and outlook.com.

Insertion order is:

[email protected]

[email protected]

[email protected]

[email protected]
gmail records should appear before outlook records. So sorting order is:

[email protected]

[email protected]

[email protected]

[email protected]

NOTE: It is not specified, what to do in case email domain is matching. So, for
matching email domain, records are left at insertion order.

Question 26: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. enum TrafficLight {
6. RED, YELLOW, GREEN
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. Map<TrafficLight, String> map = new TreeMap<>();
12. map.put(TrafficLight.GREEN, "GO");
13. map.put(TrafficLight.RED, "STOP");
14. map.put(TrafficLight.YELLOW, "STOP IN 3 Seconds");
15. map.put(TrafficLight.YELLOW, "READY TO STOP");
16.  
17. for(String msg : map.values()) {
18. System.out.println(msg);
19. }
20. }
21. }
What will be the result of compiling and executing Test class?

Printing order cannot be predicted.


STOP
READY TO STOP
GO
(Correct)


STOP
READY TO STOP
STOP IN 3 Seconds
GO

STOP
STOP IN 3 Seconds
READY TO STOP
GO

STOP
STOP IN 3 Seconds
GO
Explanation
TreeMap is the sorted map on the basis on natural ordering of keys (if comparator is
not provided). 

enum TrafficLight is used as a key for TreeMap. The natural order for enum elements
is the sequence in which they are defined.

A map doesn't allow duplicate keys. 'map.put(TrafficLight.YELLOW, "READY TO


STOP");' replaces the previous value corresponding to 'TrafficLight.YELLOW' with the
new value 'READY TO STOP'.

Value corresponding to 'RED' is printed first, followed by value corresponding to


'YELLOW' and finally value for 'GREEN' is printed.

Question 27: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. System.out.println(Duration.ofDays(-2));
8. }
9. }
What will be the result of compiling and executing Test class?

P-2D


PT48H

PT-48H
(Correct)


P2D

Explanation
As Period is expressed in terms of Years, Months and Days, Duration is expressed in
terms of Hours, Minutes and Seconds.

String representation of Period starts with "P" whereas String representation of


Duration starts with "PT". 

You should be aware of following 'of' methods for the exam:

Duration.ofDays(long days) => Returns a Duration instance with specified number of


days converted to hours. -2 days equals to -48 hours. 

Duration.ofHours(long hours) => Returns a Duration instance with specified number


of hours. 

Duration.ofMinutes(long minutes) => Returns a Duration instance with specified


number of minutes.

Duration.ofSeconds(long seconds) => Returns a Duration instance with specified


number of seconds, nanos field is set to 0. NOTE: if nanos field is 0, toString ignores
it. 

Duration.ofMillis(long millis) => Returns a Duration instance with passed value


converted to seconds and nano seconds. 

Duration.ofNanos(long nanos) => Returns a Duration instacne with passed value


converted to seconds and nono seconds.

Question 28: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Stream<String> stream = Arrays.asList("One", "Two", "Three").stream();
9. System.out.println(stream.reduce(null, (s1, s2) -> s1 + s2));
10. }
11. }
What will be the result of compiling and executing Test class?

nullOneTwoThree
(Correct)


OneTwoThreenull


NullPointerException is thrown at runtime


OneTwoThree

Explanation
Given reduce method concatenates null + "One" + "Two" + "Three" and hence the
output is: 'nullOneTwoThree'.

To concatenate just the stream contents, use below code:

stream.reduce("", (s1, s2) -> s1 + s2) 

OR 

stream.reduce((s1, s2) -> s1 + s2).get()

Question 29: Skipped

Below is the content of 'F:\message.txt': 


sdaleteftdeagncedk  

message.txt file contains secret message received. 

Below code is for decoding the secret message. 

1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. try (InputStreamReader reader =
8. new InputStreamReader(new FileInputStream("F:\\message.txt")))
{
9. while (reader.ready()) {
10. reader.skip(1);
11. reader.skip(1);
12. System.out.print((char) reader.read());
13. }
14. }
15. }
16. }
What will be the result of compiling and executing Test class?

sledge


None of the other options


defend


attack
(Correct)

Explanation
reader.ready() => Returns true if input buffer is not empty or if bytes are available to
be read from the underlying byte stream, otherwise false. 

reader.skip(long n) => This method is inherited from Reader class and skips the
passed n characters. 

Let's check how the file contents are processed. Initially available stream:
"sdaleteftdeagncedk". 

reader.ready() => returns true. 

reader.skip(1); => skips 's'. Available Stream: "daleteftdeagncedk". 

reader.skip(1); => skips 'd'. Available Stream: "aleteftdeagncedk". 

reader.read(); => Reads 'a' and prints it. Available Stream: "leteftdeagncedk". 

reader.ready() => returns true. 


reader.skip(1); => skips 'l'. Available Stream: "eteftdeagncedk". 

reader.skip(1); => skips 'e'. Available Stream: "teftdeagncedk". 

reader.read(); => Reads 't' and prints it. Available Stream: "eftdeagncedk". 

And so on, until whole stream is exhausted.

'attack' will be printed on to the console.

Question 30: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. int res = IntStream.rangeClosed(1, 1000).parallel()
8. .filter( i -> i > 50).findFirst().getAsInt();
9. System.out.println(res);
10. }
11. }
What will be the result of compiling and executing Test class?

It will always print 51
(Correct)


It will print any number between 51 and 1000

It will always print 50

It will print any number between 1 and 50
Explanation
First element that matches the filter is 51.

In this case, base stream is sequential ordered IntStream (it has specific Encounter
Order), hence findFirst() method will always return 51 regardless of whether the
stream is sequential or parallel.

Question 31: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws InterruptedException,
ExecutionException {
7. ExecutorService es = Executors.newSingleThreadExecutor();
8. Future<String> f = es.submit(() -> "HELLO");
9. System.out.println(f.get());
10. es.shutdown();
11. }
12. }
What will be the result of compiling and executing Test class?

HELLO
(Correct)


null


Compilation error


An exception is thrown at runtime

Explanation
submit method of ExecutorService interface is overloaded: submit(Runnable) and
submit(Callable). Both Runnable and Callable are Functional interfaces.

Given lambda expression '() -> "HELLO"', it accepts no parameter and returns a
String, hence it matches with the call() method implementation of Callable interface.

f.get() would return 'HELLO'.

Notice, get() method throws 2 checked exceptions InterruptedException and


ExecutionException and main method declares to throw these exceptions, hence no
compilation error.

Question 32: Skipped

Given Code: 
1. package com.udayan.ocp;
2.  
3. class Outer {
4. public static void sayHello() {}
5. static {
6. class Inner {
7. /*INSERT*/
8. }
9. new Inner();
10. }
11. }
12.  
13. public class TestOuter {
14. public static void main(String[] args) {
15. Outer.sayHello();
16. }
17. }
Which of the following options can replace /*INSERT*/ such that on executing
TestOuter class, "HELLO" is printed in the output?

Select 2 options.


1. static {
2. System.out.println("HELLO");
3. }


1. Inner(String s) {
2. System.out.println(s);
3. }


1. {
2. System.out.println("HELLO");
3. }
(Correct)


1. Inner() {
2. System.out.println("HELLO");
3. }
(Correct)

Explanation
static initialization block defined inside Outer class is invoked when static method
sayHello is invoked.

Method-local inner class can be defined inside methods(static and non-static) and
initialization blocks(static and non-static).

But like Regular inner class,  method-local inner class cannot define anything static,
except static final variables.
new Inner(); invokes the no-argument constructor of Inner class. So,
System.out.println("HELLO") can either be provided inside no-argument constructor
or instance initialization block.

Question 33: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Locale;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Locale loc = new Locale("it", "IT");
8. System.out.println(loc.getDisplayCountry()); //Line 8
9. System.out.println(loc.getDisplayCountry(Locale.CHINA)); //Line 9
10. System.out.println(loc.getDisplayLanguage()); //Line 10
11. System.out.println(loc.getDisplayLanguage(Locale.CHINA)); //Line 11
12. }
13. }
Which of the following statement is correct about above code?

Line 9 and Line 11 cause compilation error

Given code compiles successfully
(Correct)


Line 8 and Line 10 cause compilation error
Explanation
getDisplayCountry() and getDisplayLanguage() methods are overloaded to accept
Locale type.

Given Test class compiles successfully.

Question 34: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.ListIterator;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<String> list = Arrays.asList("T", "S", "R", "I", "F");
10. ListIterator<String> iter = list.listIterator(5);
11. while(iter.hasPrevious()) {
12. System.out.print(iter.previous());
13. }
14. }
15. }
What will be the result of compiling and executing Test class?

FIRST
(Correct)


TSRIF


IRST


Runtime Exception

Explanation
listIterator(index); method allows to have the starting point at any index. Allowed
values are between 0 and size of the list.

ListIterater extends Iterator and can be used to iterate in both the directions. If you
want to iterate backward then pass the no. of elements in the list to listIterator(index)
method. In this case, 'list.listIterator(5);'. 

To iterate backward, use hasPrevious() and previous() methods.

Question 35: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. BufferedOutputStream bos = new BufferedOutputStream(
8. new FileOutputStream("F:\\file.tmp"));
9. bos.write(2);
10. bos.close();
11. }
12. }
Which of the following statement regarding above code is true?

There is a chance of resource leak
(Correct)


There is no chance of resource leak

Above code causes compilation error
Explanation
main method declares to throw IOException, hence given code compiles successfully.

Even though, bos.close(); method is invoked but it is not invoked in finally block. If
statements before bos.close(); throw any exception, then bos.close() will not execute
and this will result in resource leak.

To avoid resource leak, either use try-with-resources statement or provide try-finally


block.

Question 36: Skipped

Given structure of EMPLOYEE table: 


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String query = "Select * FROM EMPLOYEE";
8. try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ocp", "root", "password");
9. Statement stmt = con.createStatement();
10. ResultSet rs = stmt.executeQuery(query);) {
11. System.out.println(rs.getMetaData().getColumnCount()); //Line 11
12. }
13. }
14. }

Also assume: 
URL, username and password are correct.
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 result of compiling and executing Test class?


Code executes successfully and prints 4 on to the console
(Correct)

Compilation error


NullPointerException is thrown at Line 11


SQLException is thrown at Line 11

Explanation
Even if there are no records in EMPLOYEE table, ResultSet object returned by
'stmt.executeQuery(query);' will never be null.

rs.getMetaData().getColumnCount() returns number of columns of EMPLOYEE table,


hence 4 is printed on to the console.

Question 37: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. public class Test {
4. enum JobStatus {
5. SUCCESS, FAIL; //Line 3
6. }
7.
8. enum TestResult {
9. PASS, FAIL; //Line 7
10. }
11.
12. public static void main(String[] args) {
13. JobStatus js = JobStatus.FAIL;
14. TestResult tr = TestResult.FAIL;
15.
16. System.out.println(js.equals(tr)); //Line 14
17. System.out.println(js == tr); //Line 15
18. }
19. }

Compilation error at Line 14


true
true

false
false

Compilation error at Line 15
(Correct)
Explanation
enums JobStatus and TestResult are siblings as both implicitly extend from
java.lang.Enum class.

Siblings cannot be compared using double equals operator (==).

equals(Object) method accepts any instance which Object can refer to, which means
all the instances.

Question 38: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. System.out.format("A%nB%nC");
6. }
7. }
What will be the result of compiling and executing Test class?

ABC


A
B
C
(Correct)


Runtime Exception


A

Explanation
Format specifier, 'n' is for newline.

NOTE: System.out.printf(...) is same as  System.out.format(...).

Question 39: Skipped

Given structure of EMPLOYEE table: 


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  
EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. try (Connection con = DriverManager.getConnection(url, user, password);
11. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
12. ) {
13. ResultSet res1 = stmt.executeQuery("SELECT * FROM EMPLOYEE ORDER BY
ID");
14. ResultSet res2 = stmt.executeQuery("SELECT * FROM EMPLOYEE ORDER BY ID
DESC");
15. res1.next();
16. System.out.println(res1.getInt(1));
17. res2.next();
18. System.out.println(res2.getInt(1));
19. }
20. }
21. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


104
101

An exception is thrown at runtime
(Correct)


None of the other options

101
104
Explanation
executeQuery method closes the previously opened ResultSet object on the same
Statement object.

ResultSet object referred by res1 gets closed when 2nd executeQuery method is
executed. So 'res1.next()' throws SQLException at runtime.

Question 40: Skipped

Given structure of EMPLOYEE table: 


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws Exception {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
13. ) {
14. ResultSet rs = stmt.executeQuery(query);
15. rs.afterLast();
16. while (rs.previous()) {
17. rs.updateDouble(4, rs.getDouble(4) + 1000);
18. rs.updateRow();
19. }
20.  
21. rs = stmt.executeQuery(query);
22. while(rs.next()) {
23. System.out.println(rs.getDouble(4));
24. }
25. }
26. }
27. }

Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class? 


13000.0
16000.0
16500.0
15600.0
(Correct)


12000.0
15000.0
15500.0
14600.0

12000.0
15000.0
15500.0
15600.0

15600.0
16500.0
16000.0
13000.0

13000.0
15000.0
15500.0
14600.0
Explanation
Given query returns below records:

101 John Smith 12000   

102 Sean Smith 15000   

103 Regina Williams 15500   


104 Natasha George 14600   

'rs.afterLast();' moves the cursor just after the last record. 

'rs.previous()' inside while loop moves the cursor from last to first and the codes
inside while loop increment the salary of each record by 1000. 

'rs.updateRow();' makes sure that salary is updated in the database.

Next while loop simply prints the updated salaries on to the console.

Question 41: Skipped

Below is the directory structure for F:


1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7.  
8. public class Test {
9. public static void main(String[] args) throws IOException {
10. Path src = Paths.get("F:\\A\\B\\C\\Book.java");
11. Path tgt = Paths.get("F:\\A\\B");
12. Files.copy(src, tgt);
13. }
14. }

What will be the result of compiling and executing Test class?


Program terminates successfully without copying 'Book.java' file

java.io.FileNotFoundException is thrown at runtime

'Book.java' will be copied successfully to 'F:\A\B\' directory

java.nio.file.FileAlreadyExistsException is thrown at runtime
(Correct)

Explanation
Path is an abstract path and farthest element can be a file or directory. 

src refers to Path object, F:\\A\\B\\C\\Book.java and its farthest element, 'Book.java' is
a file (and it exists).   

tgt refers to Path object, F:\\A\\B and its farthest element, 'B' is a directory (and it
exists). 

Files.copy(src, tgt) copies the farthest element. 'Book.java' can't be copied to 'B' as it
is a directory and it is not allowed to have file and directory of same name to be
present at same location. Hence, java.nio.file.FileAlreadyExistsException is thrown at
runtime. 

If you change tgt to Paths.get("F:\\A\\C\\"); then 'Files.copy(src, tgt);' will successfully


copy 'Book.java' to 'C' ('C' will be a file in that case, containing the contents from
'Book.java' file).

Question 42: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static String msg = "Hello";
5.  
6. private static String changeMsg(String m) {
7. msg = m;
8. return null;
9. }
10.  
11. public static void main(String[] args) {
12. if(args.length == 0) {
13. assert false : changeMsg("Bye");
14. }
15. System.out.println(msg);
16. }
17. }
What will be the result of executing Test class with below command? 
java -ea com.udayan.ocp.Test

AssertionError is thrown at runtime and program terminates abruptly
(Correct)


Hello


Bye

Explanation
On execution, 'args.length == 0' returns true and 'assert false : changeMsg("Bye");' is
executed.

'changeMsg("Bye")' method makes msg to refer to "Bye" and null is returned.

An instance of AssertionError is thrown with message null.

Remaining statements are ignored and program terminates abruptly.

NOTE: Though this class compiles successfully but Assertion mechanism is not
implemented appropriately. There are 2 issues:

1. Assertion mechanism is used to validate the arguments of public method and 

2. changeMsg("Bye") method causes side effect as it changes the class variable, 'msg'.

Question 43: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.function.Predicate;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<Integer> list = Arrays.asList(-80, 100, -40, 25, 200);
10. Predicate<Integer> predicate = num -> {
11. int ctr = 1;
12. boolean result = num > 0;
13. System.out.print(ctr++ + ".");
14. return result;
15. };
16.  
17. list.stream().filter(predicate).count();
18. }
19. }
What will be the result of compiling and executing Test class?

1.1.1.


1.1.1.1.1.
(Correct)


1.2.3.


1.2.3.4.5.


2.4.5.

Explanation
count() is terminal operation and it needs all the elements of the stream to return the
result. So, all the stream elements will be processed.

list.stream() => [-80, 100, -40, 25, 200].

NOTE: a new instance of Predicate is used, hence every time ctr will be initialize to 1.

For -80, Output is '1.' but predicate returns false, hence element is not included.

For 100, '1.' is appended to previous output, so on console you will see '1.1.' and
predicate returns true, hence element is included.
You don't have to count the filtered elements as result of count() is not printed.

As 5 elements in the stream so final output will be: '1.1.1.1.1.'

Question 44: Skipped

F: is accessible for reading and below is the directory structure for F:


1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java
'Book.java' file is available under 'C' directory.

Given code of Test.java file: 

1. import java.nio.file.Path;
2. import java.nio.file.Paths;
3.  
4. public class Test {
5. public static void main(String[] args) {
6. Path file = Paths.get("Book.java");
7. System.out.println(file.toAbsolutePath());
8. }
9. }

Actual path of generated class file is: "C:\classes\Test.class".

What will be the result of compiling and executing Test class?


NoSuchFileException is thrown at runtime.


F:\A\B\Book.java


FileNotFoundException is thrown at runtime.


C:\classes\Book.java
(Correct)

Explanation
Paths.get("Book.java"); represents a relative path. This means relative to current
directory. 
'Test.class' file is available under "C:\classes" directory, hence path of 'Book.java' is
calculated relative to C:\classes. 

file.toAbsolutePath() returns 'C:\classes\Book.java'. 

NOTE: toAbsolutePath() method doesn't care if given path elements are physically
available or not. It just returns the absolute path.

Question 45: Skipped

Which of the following code will create/return a Locale object for the JVM, on which
your code is running?


Locale.getLocale();  


System.getDefault();  


Locale.getDefaultLocale();  


Locale.getDefault();  
(Correct)

Explanation
Locale.getDefault(); returns the default Locale for the currently running instance of JVM and
getDefault() method is from Locale class and not from System class.

Question 46: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static boolean isDirection(int ch) {
5. switch(ch) {
6. case 'N':
7. case 'E':
8. case 'W':
9. case 'S':
10. return true;
11. }
12. return false;
13. }
14.  
15. public static void main(String[] args) {
16. String str = "North East West South";
17. str.chars().filter(Test::isDirection)
18. .forEach(c -> System.out.print((char)c));
19. }
20. }
What will be the result of compiling and executing Test class?

NEWS


NEWS
(Correct)


None of the other options


orth ast est outh

Explanation
chars() method in String class returns IntStream, all the elements in this stream are
stored as int value of corresponding char.

filter(Test::isDirection) => Returns the stream consisting of int (char) for which
isDirection method returns true.

isDirection method returns true for 'N', 'E', 'W' and 'S' only for other characters
(including whitespace character) it returns false.

forEach(c -> System.out.print((char)c)); => forEach method typecast int value to char
and hence NEWS is printed on to the console.

Question 47: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. int ref = 10;
9. List<Integer> list = new ArrayList<>();
10. list.stream().anyMatch(i -> {
11. System.out.println("HELLO");
12. return i > ++ref;
13. });
14. }
15. }
What will be the result of compiling and executing Test class?

Program executes successfully but nothing is printed on to the console

HELLO


Compilation error
(Correct)

Explanation
Method signature for anyMatch method:

boolean anyMatch(Predicate<? super T>) : Returns true if any of the stream element
matches the given Predicate. If stream is empty, it returns false and predicate is not
evaluated. 

ref is a local variable and it is used within lambda expression.

++ref causes compilation failure as variable ref should be effectively final.

Question 48: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. class P {
4. private int var = 100;
5. class Q {
6. String var = "Java";
7. void print() {
8. System.out.println(var);
9. }
10. }
11. }
12.  
13. public class Test {
14. public static void main(String[] args) {
15. new P().new Q().print();
16. }
17. }


100


Compilation error


Java
(Correct)


Exception is thrown at runtime

Explanation
In this example, inner class's variable var shadows the outer class's variable var. So
output is Java.

Few points to note here: 

1. If inner class shadows the variable of outer class, then Java compiler prepends
'this.' to the variable. System.out.println(var); is replaced by
System.out.println(this.var);

2. If inner class does not shadow the variable of outer class, then Java compiler
prepends "outer_class.this." to the variable. So, if class Q doesn't override the variable
of class P, then System.out.println(var); would be replaced by
System.out.println(P.this.var);

In the given example, if you provide System.out.println(P.this.var); inside print()


method, then output would be 100.

Question 49: Skipped

For the given code:


1. package com.udayan.ocp;
2.  
3. interface Operator<T> {
4. public abstract T operation(T t1, T t2);
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. System.out.println(new Operator<String>() {
10. public String operation(String s1, String s2) {
11. return s1 + s2;
12. }
13. });
14. }
15. }
Which of the following options successfully replace anonymous inner class code with
lambda expression code?

System.out.println((String s1, String s2) -> s1 + s2);  


System.out.println((s1, s2) -> s1 + s2);  


None of the other options
(Correct)


System.out.println((s1, s2) -> { return s1 + s2; });  
Explanation
Reference variable to which lambda expression is assigned is known as target type.
Target type can be a static variable, instance variable, local variable, method
parameter or return type. Lambda expression doesn't work without target type and
target type must be a functional interface. 

In this case, println(Object) method is invoked but Object is a class and not a
functional interface, hence no lambda expression can be passed directly to println
method. 

But you can first assign lambda expression to target type and then pass the target
type reference variable to println(Object) method:

Operator<String> operator = (s1, s2) -> s1 + s2; 

System.out.println(operator);

Or you can typecast lambda expression to target type. e.g. following works:

System.out.println((Operator<String>)(String s1, String s2) -> s1 + s2);

System.out.println((Operator<String>)(s1, s2) -> s1 + s2);

System.out.println((Operator<String>)(s1, s2) -> { return s1 + s2; });

Question 50: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.sql.SQLException;
4.  
5. public class Test {
6. private static void m() throws SQLException {
7. try {
8. throw new SQLException();
9. } catch (Exception e) {
10. throw null; //Line 10
11. }
12. }
13.  
14. public static void main(String[] args) {
15. try {
16. m(); //Line 16
17. } catch(SQLException e) {
18. System.out.println("Caught Successfully.");
19. }
20. }
21. }
What will be the result of compiling and executing Test class?

Line 10 causes compilation failure

Caught Successfully

Program ends abruptly
(Correct)


Line 16 causes compilation failure
Explanation
Classes in Exception framework are normal java classes, hence null can be used
wherever instances of Exception classes are used, so Line 10 compiles successfully.

No issues with Line 16 as method m() declares to throw SQLException and main
method code correctly handles it.

Program compiles successfully but on execution, NullPointerException is thrown,


stack trace is printed on to the console and program ends abruptly.

If you debug the code, you would find that internal routine for throwing null
exception causes NullPointerException.

Question 51: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Stream<Integer> stream = Arrays.asList(1,2,3,4,5).stream();
9. System.out.println(stream.mapToInt(i -> i).average().getAsInt());
10. }
11. }
What will be the result of compiling and executing Test class?

Compilation error
(Correct)


3


Runtime Exception

Explanation
stream.mapToInt(i -> i) => returns an instance of IntStream. 

average() method of all the 3 primitive streams (IntStream, LongStream &


DoubleStream) return an instance of OptionalDouble.

OptionalDouble has getAsDouble() method and not getAsInt() method.

Question 52: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4.  
5. class Message {
6. private String msg = "Good Morning!";
7. public Message(String msg) {
8. this.msg = msg;
9. }
10.
11. public Message() {super();}
12.  
13. public String getMsg() {
14. return msg;
15. }
16.
17. public String toString() {
18. return msg;
19. }
20. }
21.  
22. public class Test {
23. public static void main(String[] args) {
24. Message message = null;
25. Optional<Message> optional = Optional.ofNullable(message);
26. System.out.println(optional.isPresent() ? optional.get().getMsg() : new
Message());
27. }
28. }
What will be the result of compiling and executing Test class?

NullPointerException is thrown at runtime


null


Good Morning!
(Correct)


Text containing @ symbol

Explanation
optional --> [null]

optional.isPresent() returns false, hence Message object is returned.

'msg' filed of this object refers to "Good Morning!", which is returned by toString()
method.

Question 53: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date = LocalDate.ofEpochDay(-1);
8. System.out.println(date);
9. }
10. }
What will be the result of compiling and executing Test class?

Runtime Exception


1969-12-31
(Correct)


1970-01-01

Explanation
0th day in epoch is: 1970-01-01, 1st day in epoch is: 1970-01-02 and so on.

And if you pass a negative number, then it represents earlier days.


LocalDate.ofEpochDay(-1); --> {1969-12-31}.

Question 54: Skipped

Below is the code of TestSellable.java file:


1. package com.udayan.ocp;
2.  
3. interface Sellable {
4. double getPrice();
5. }
6.  
7. public class TestSellable {
8. private static void printPrice(Sellable sellable) {
9. System.out.println(sellable.getPrice());
10. }
11.  
12. public static void main(String[] args) {
13. /*INSERT*/
14. }
15. }
Which of the following options can replace /*INSERT*/ such that there are no
compilation errors?

Select 2 options.


1. printPrice(new Sellable() {
2.  
3. });

printPrice(null);  
(Correct)


1. printPrice(new Sellable() {
2.     @Override
3.     public double getPrice() {
4.         return 45.34;
5.     }
6. });
(Correct)


printPrice(new Sellable());  
Explanation
Instance of anonymous inner class can be assigned to static variable, instance
variable, local variable, method parameter and return value.

In this question, anonymous inner class instance is assigned to method parameter.


printPrice(null); => No compilation error as asked in the question but it would throw
NullPointerException at runtime.

printPrice(new Sellable()); => Cannot create an instance of Sellable type.

printPrice(new Sellable() {}); => getPrice() method is not implemented.

Question 55: Skipped

Will below code compile successfully?


1. package com.udayan.ocp;
2.  
3. interface I1 {
4. void m1();
5.  
6. interface I2 {
7. void m2();
8. }
9.  
10. abstract class A1 {
11. public abstract void m3();
12. }
13.  
14. class A2 {
15. public void m4() {
16. System.out.println(4);
17. }
18. }
19. }


No


Yes
(Correct)

Explanation
interface I2 is implicitly public and static (Nested interface).

Class A1 is implicitly public and static (Nested class).

Class A2 is implicitly public and static (Nested class).

You cannot explicitly specify protected, default and private for nested classes and
nested interfaces inside an interface.

Question 56: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class MyCallable implements Callable<Integer> {
6. private Integer i;
7.  
8. public MyCallable(Integer i) {
9. this.i = i;
10. }
11.  
12. public Integer call() throws Exception {
13. return --i;
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. ExecutorService es = Executors.newSingleThreadExecutor();
20. MyCallable callable = new MyCallable(1);
21. System.out.println(es.submit(callable).get());
22. es.shutdown();
23. }
24. }
What will be the result of compiling and executing Test class?

An exception is thrown at runtime


Compilation error
(Correct)


0


1

Explanation
get() method throws 2 checked exceptions: InterruptedException and
ExecutionException. 

As the given code neither handles these exceptions using catch block nor declares
these exceptions in throws clause, hence call to get() method causes compilation
failure.

Question 57: Skipped

Which of the following is the only Functional interface available for boolean primitive
type?


BooleanPredicate

BooleanSupplier
(Correct)


BooleanConsumer


BooleanFunction

Explanation
There is only BooleanSupplier available in JDK 8.0.

Question 58: Skipped

Given code: 
1. package com.udayan.ocp;
2.  
3. class Message {
4. public void printMessage() {
5. System.out.println("Hello!");
6. }
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. Message msg = new Message() {
12. @Override
13. public void PrintMessage() {
14. System.out.println("HELLO!");
15. }
16. };
17. msg.printMessage();
18. }
19. }
What will be the result of compiling and executing Test class?

Runtime error


Hello!


Compilation error
(Correct)


HELLO!

Explanation
@Override annotation is used for overriding method.
But PrintMessage (P in upper case) method of anonymous inner class doesn't
override printMessage (p in lower case) method of its super class, Message.

Hence, @Override annotation causes compilation error.

Question 59: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.BiFunction;
4. import java.util.function.BiPredicate;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. BiPredicate<String, String> predicate = String::contains;
9. BiFunction<String, String, Boolean> func = (str1, str2) -> {
10. return predicate.test(str1, str2) ? true : false;
11. };
12.  
13. System.out.println(func.apply("Tomato", "at"));
14. }
15. }
What will be the result of compiling and executing Test class?

true
(Correct)


Compilation error

false

null
Explanation
BiPredicate<T, U> : boolean test(T t, U u); 

BiPredicate interface accepts 2 type parameters and these parameters (T,U) are
passed to test method, which returns primitive boolean.

In this case, 'BiPredicate<String, String>' means test method will have declaration:
'boolean test(String s1, String s2)'.

'String::contains' is equivalent to '(str1, str2) -> str1.contains(str2)'

This is an example of "Reference to an Instance Method of an Arbitrary Object of a


Particular Type" and not "method reference to static method", predicate declaration
is correct.
BiFunction<T, U, R> : R apply(T t, U u);

BiFunction interface accepts 3 type parameters, first 2 parameters (T,U) are passed to
apply method and 3rd type parameter is the return type of apply method.

In this case, 'BiFunction<String, String, Boolean>' means apply method will have
declaration: 'Boolean apply(String str1, String str2)'. Given lambda expression '(str1,
str2) -> { return predicate.test(str1, str2) ? true : false; };' is the correct implementation
of BiFunction<String, String, Boolean> interface.

Please note, the lambda expressions makes use of predicate declared above.

func.apply("Tomato", "at") returns true as "Tomato" contains "at", hence true is


printed on to the console.

Also note that usage of ternary operator (?:) is not needed here, you can simply write
'return predicate.test(str1, str2);' as well.

Question 60: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.LinkedList;
4. import java.util.List;
5. import java.util.Queue;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<String> list = new LinkedList<>();
10. list.add("ONE");
11. list.add("TWO");
12. list.remove(1);
13. System.out.println(list);
14.  
15. Queue<String> queue = new LinkedList<>();
16. queue.add("ONE");
17. queue.add("TWO");
18. queue.remove();
19. System.out.println(queue);
20. }
21. }
What will be the result of compiling and executing Test class?

[TWO]
[ONE]

[ONE]
[TWO]
(Correct)


[TWO]
[TWO]

[ONE]
[ONE]
Explanation
LinkedList implements both List and Queue. In this example reference type controls
the LinkedList behavior.

list.add("ONE"); => [ONE]. 

list.add("TWO"); => [ONE,TWO]. Adds to the last. 

list.remove(1); => [ONE]. Removes from the specified index. 

System.out.println(list); => [ONE].   

queue.add("ONE"); => [*ONE].  * represents HEAD of the queue. 

queue.add("TWO"); => [*ONE,TWO]. Adds to the end of the queue. 

queue.remove(); => [*TWO]. Removes from the HEAD of the queue. 

System.out.println(queue); => [TWO]. 

Question 61: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Comparator;
5. import java.util.List;
6.  
7. class Student implements Comparator<Student> {
8. private String name;
9. private String exam;
10.  
11. public Student() {
12. super();
13. }
14.  
15. public Student(String name, String exam) {
16. this.name = name;
17. this.exam = exam;
18. }
19.  
20. public int compare(Student s1, Student s2) {
21. return s2.name.compareToIgnoreCase(s1.name);
22. }
23.  
24. public String toString() {
25. return '{' + name + ", " + exam + '}';
26. }
27. }
28.  
29. public class Test {
30. public static void main(String[] args) {
31. Student stud1 = new Student("John", "OCA");
32. Student stud2 = new Student("Jack", "OCP");
33. Student stud3 = new Student("Rob", "OCP");
34. List<Student> list = Arrays.asList(stud1, stud2, stud3);
35. list.sort(new Student());
36. list.forEach(System.out::println);
37. }
38. }
What will be the result of compiling and executing Test class?

Compilation error


{Jack, OCP}
{John, OCA}
{Rob, OCP}

{Rob, OCP}
{John, OCA}
{Jack, OCP}
(Correct)


Runtime exception

Explanation
In real world programming you will hardly find a bean class implementing
Comparator but it is a legal code. A bean class generally implements Comparable
interface to define natural ordering.

Student class in this case correctly implements Comparator<Student> interface by


overriding compare(Student, Student) method.

Note, this compare method will sort in descending order of Student's name.
list.sort(...) accepts an argument of Comparator<Student> type. 

new Student() provides the instance of Comparator<Student> type. It sorts list in


descending order of Students' name.

Output is:

{Rob, OCP}

{John, OCA}

{Jack, OCP}

Question 62: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test<T> {
4. static T obj;
5. }
Does above code compile successfully?

Yes


No
(Correct)

Explanation
static declaration of type parameter is not allowed, only instance declaration is
possible.

'static T obj;' causes compilation failure.

Question 63: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream<String> stream = Stream.of("ocp");
8. stream._____________(s -> s.chars()).forEach(i ->
System.out.print((char)i));
9. }
10. }
Which code snippet, when filled into the blank, allows the class to compile?

flatMapToInt
(Correct)


flatMapToLong


flatMapToDouble


flatMap

Explanation
s -> s.chars() is of IntStream type as chars() method returns instance of IntStream
type.

All 4 are valid method names but each specify different parameters.

Only faltMapToInt can accept argument of IntStream type.

Question 64: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try(BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\test.txt")))
8. {
9. bw.close();
10. bw.newLine();
11. } catch(IOException e) {
12. System.out.println("IOException");
13. }
14. }
15. }
F: is accessible for reading/writing purposes.

Which of the following statement is true about above code?


Compilation error

On execution, IOException is printed on to the console
(Correct)


Class Test compiles and executes fine and no output is displayed on to the
console
Explanation
Once the close() method is called on BufferedWriter, same stream cannot be used for
writing.

bw.newLine(); tries to append a newline character to the closed stream and hence
IOException is thrown.

catch handler is provided for IOException. Control goes inside and prints
'IOException' on to the console.

Question 65: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.Consumer;
4.  
5. class Counter {
6. static int count = 1;
7. }
8. public class Test {
9. public static void main(String[] args) {
10. Consumer<Integer> add = i -> Counter.count += i;
11. Consumer<Integer> print = System.out::println;
12. add.andThen(print).accept(10); //Line 10
13. }
14. }
What will be the result of compiling and executing Test class?

11


10
(Correct)


1


Compilation error
Explanation
andThen is the default method defined in Consumer interface, so it is invoked on
consumer reference variable.

Value passed in the argument of accept method is passed to both the consumer
objects.

So, for understanding purpose Line 10 can be split into: add.accept(10);


print.accept(10); 

add.accept(10) is executed first and it increments the count variable by 10, so count
becomes 11.

Then print.accept(10); method prints 10 on to the console.

Check the code of andThen method defined in Consumer interface to understand it


better.

Question 66: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.Supplier;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Supplier<StringBuilder> supplier = () -> new StringBuilder(" olleH")
8. .reverse().append("!dlroW").reverse();
9. System.out.println(supplier.get());
10. }
11. }
What will be the result of compiling and executing Test class?

>World! olleH<
(Correct)


>World!Hello <


> olleHWorld!<


> olleH!dlroW<

>Hello World!<

Explanation
Syntax is correct and without any errors. Methods are chained from left to right.

new StringBuilder(" olleH") => " olleH"

" olleH".reverse() => "Hello "

"Hello ".append("!dlroW") => "Hello !dlroW"

"Hello !dlroW".reverse() => "World! olleH"

Question 67: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.PrintWriter;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try(PrintWriter writer = null) {
8. System.out.println("HELLO");
9. }
10. }
11. }
What will be the result of compiling and executing Test class?

NullPointerException is thrown at runtime


HELLO
(Correct)


Compilation error

Explanation
For null resources, close() method is not called and hence NullPointerException is not
thrown at runtime. 

HELLO is printed on to the console.

Question 68: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.Comparator;
5. import java.util.List;
6.  
7. class Fruit implements Comparable<Fruit>, Comparator<Fruit> {
8. String name;
9. String countryOfOrigin;
10.
11. Fruit() {}
12.
13. Fruit(String name, String countryOfOrigin) {
14. this.name = name;
15. this.countryOfOrigin = countryOfOrigin;
16. }
17.
18. public String toString() {
19. return name + ":" + countryOfOrigin;
20. }
21.  
22. @Override
23. public int compareTo(Fruit o) {
24. return this.name.compareToIgnoreCase(o.name);
25. }
26.
27. @Override
28. public int compare(Fruit o1, Fruit o2) {
29. return o1.countryOfOrigin.compareToIgnoreCase(o2.countryOfOrigin);
30. }
31.
32. public static int comp(String s1, String s2) {
33. return s2.compareToIgnoreCase(s1);
34. }
35. }
36.  
37. public class Test {
38. public static void main(String[] args) {
39. List<Fruit> list = new ArrayList<>();
40. list.add(new Fruit("Olive", "Middle East"));
41. list.add(new Fruit("Mango", "India"));
42. list.add(new Fruit("Cranberry", "North America"));
43. list.add(new Fruit("Watermelon", "Africa"));
44. list.add(new Fruit("Peach", "China"));
45. list.add(new Fruit("Fig", "Middle East"));
46. list.add(new Fruit("Blueberry", "North America"));
47.
48. /* INSERT */
49. }
50. }

Which of the following two options can replace /* INSERT */ such that output is:

1. Cranberry:North America
2. Blueberry:North America
3. Olive:Middle East
4. Fig:Middle East
5. Mango:India
6. Peach:China
7. Watermelon:Africa


list.stream().sorted().forEach(System.out::println);

list.stream().sorted(Comparator.comparing(f -> f.countryOfOrigin,
Fruit::comp)).forEach(System.out::println);
(Correct)


list.stream().sorted(new Fruit().reversed()).forEach(System.out::println);
(Correct)


list.stream().sorted(new Fruit()).forEach(System.out::println);
Explanation
As Comparable and Comparator are interfaces, so Fruit class can implement both the
interfaces.

Given code compiles successfully.

compareTo(Fruit) method of Comparable interface will help to sort in ascending


order of Fruit's name and compare(Fruit, Fruit) method of Comparator interface will
help to sort in ascending order of Fruit's country of origin.

By looking at the expected output it is clear that output is arranged in descending


order of Fruit's country of origin. This means Comparator needs to be used in
reversed order. Out of the given options 'list.stream().sorted(new
Fruit().reversed()).forEach(System.out::println);' will display the expected output.

'list.stream().sorted()' sorts Fruit instances on the basis of ascending order of their


names, not the correct option.

'list.stream().sorted(new Fruit())' sorts Fruit instances on the basis of ascending order


of their country of origin, not the correct option.

'list.stream().sorted(Comparator.comparing(f -> f.countryOfOrigin, Fruit::comp))':


keyExtractor is accepting Fruit object and returning countryOfOrigin, which is of
String type. The 2nd argument passed is Fruit::comp, which is keyComparator and it
sorts the Fruit objects in descending order of the key (courntryOfOrigin) in this case.
Hence this is also a correct option.

Question 69: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.function.UnaryOperator;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<Integer> list = Arrays.asList (2, 3, 4);
10. UnaryOperator<Long> operator = s -> s*s*s;
11. list.replaceAll(operator);
12. list.forEach(System.out::println);
13. }
14. }
What will be the result of compiling and executing Test class?

Compilation error
(Correct)


Runtime exception


8
27
64

2
3
4
Explanation
replaceAll(UnaryOperator<E> operator) is the default method added in List
interface. 

interface UnaryOperator<T> extends Function<T, T>. 

As List is of Integer type, this means operator must be of UnaryOperator<Integer>


type only.

'list.replaceAll(operator);' causes compilation error as operator is of


UnaryOperator<Long> type.

Question 70: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. IntStream.rangeClosed(1, 10).parallel()
8. .forEach(System.out::println);
9. }
10. }
What will be the result of compiling and executing Test class?

It will print numbers form 1 to 10 but not in any specific order
(Correct)


It will print numbers form 1 to 10 in descending order

It will print numbers from 1 to 10 in ascending order
Explanation
IntStream.rangeClosed(1, 10) returns a sequential ordered IntStream but parallel()
method converts it to a parallel stream.

Hence, forEach method doesn't guarantee the order for printing numbers.

Question 71: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream<String> stream = Stream.of("d", "cc", "bbb", "aaaa");
8. stream.sorted().forEach(System.out::println);
9. }
10. }

Which of the following needs to be done, so that output is: 

1. d
2. cc
3. bbb
4. aaaa


No need to make any changes, on execution given code prints expected result

Replace  stream.sorted()   with  stream.sorted((s1,s2) -> s1.length() -
s2.length())  
(Correct)


Replace  stream.sorted()   with  stream.sorted((s1,s2) -> s2.length() -
s1.length())  
Explanation
Given code sorts the stream in natural order (a appears before b, b appears before c
and so on).

To get the expected output, stream should be sorted in ascending order of length of
the string.

Replacing 'stream.sorted()' with 'stream.sorted((s1,s2) -> s1.length() - s2.length())' will


do the trick.

Question 72: Skipped

Which of the annotation is used for Functional Interface?


@FI


@Functional


@FunctionalInterface
(Correct)


@Functional Interface

Explanation
@FunctionalInterface annotation is used to tag a functional interface.

Question 73: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. File f1 = new File("F:\\f1.txt");
8. FileWriter fw = new FileWriter("F:\\dir\\f2.txt");
9. PrintWriter pw = new PrintWriter("F:\\f3.txt");
10. }
11. }
F: is accessible for reading/writing and currently doesn't contain any files/directories. 

On executing Test class, how many physical files will be created on the disc?

3


0
(Correct)


1


2

Explanation
Initially F:\ is blank.

new File("F:\\f1.txt"); => It just creates a Java object containing abstract path
'F:\f1.txt'.  NO physical file is created on the disc.

Constructors of FileWriter and PrintWriter can create a new file but not directory.

new FileWriter("F:\\dir\\f2.txt"); => Throws IOException as 'dir' is a folder, which


doesn't exist. This constructor can't create folders/directories.

new PrintWriter("F:\\f3.txt"); would have created 'f3.txt' on the disk but as previous
statement threw IOException, hence program ends abruptly after printing the stack
trace.

Question 74: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void m1() throws Exception {
5. throw new Exception();
6. }
7.  
8. public static void main(String[] args) {
9. try {
10. m1();
11. } finally {
12. System.out.println("A");
13. }
14. }
15. }
What will be the result of compiling and executing Test class?

A is printed to the console, stack trace is printed and then program ends abruptly

Compilation error
(Correct)


A is printed to the console and program ends normally

A is printed to the console, stack trace is printed and then program ends normally
Explanation
Method m1() throws Exception (checked) and it declares to throw it, so no issues with
method m1().

But main() method neither provides catch handler nor throws clause and hence main
method causes compilation error.

Handle or Declare rule should be followed for checked exception if you are not re-
throwing it.

Question 75: Skipped

Which of the following are Primitive variant of Optional class?


OptionalBoolean


IntOptional


ByteOptional


OptionalFloat


OptionalDouble
(Correct)
Explanation
Only 3 primitive variants available: OptionalDouble, OptionalInt and OptionalLong.

Question 76: Skipped

Given code: 
1. package com.udayan.ocp;
2.  
3. class Outer {
4. class Inner {
5. public void m() {
6. System.out.println("WELCOME!");
7. }
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. //Insert statement here
14. }
15. }
Which statement when inserted in the main(String []) method will print "WELCOME!"
in the output?

1. Outer.Inner obj1 = new Outer().new Inner();
2. obj1.m();
(Correct)


1. Inner obj2 = new Outer().new Inner();
2. obj2.m();


1. Outer.Inner obj3 = this.new Inner();
2. obj3.m();

1. Inner obj4 = this.new Inner();
2. obj4.m();
Explanation
There are 2 parts: 1st one is referring the name of inner class, Inner and 2nd one is
creating an instance of inner class, Inner.

Now main method is outside Outer class only, so inner class can be referred by one
way only and that is by using outer class name: Outer.Inner.

As, Inner is Regular inner class, so instance of outer class is needed for creating the
instance of inner class. Instance of outer class, Outer can only be obtained by new
Outer(). So, instance of inner class can be created by: new Outer().new Inner();

Also note, keyword 'this' is not allowed static main method.


Question 77: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. interface I10 {
4. void m(String s);
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. method(new I10() {
10. @Override
11. public void m(String s) {
12. System.out.println(s.toUpperCase());
13. }
14.
15. }, "good morning!");
16. }
17.
18. private static void method(I10 obj, String text) {
19. obj.m(text);
20. }
21. }
Which of the following code replaces the anonymous inner class code with lambda
expression?

method(s -> System.out.println(s.toUpperCase()), "good morning!");  
(Correct)


method(s -> s.toUpperCase(), "good morning!");  


method(s -> System.out.println(s.toUpperCase()));  


method(s -> { System.out.println(s.toUpperCase()) }, "good morning!");  
Explanation
Lambda expression can be assigned to static variable, instance variable, local
variable, method parameter or return type.  method(I10, String) accepts two
arguments, hence method(s -> System.out.println(s.toUpperCase())); would cause
compilation error. 

When curly brackets are used then semicolon is necessary, hence  method(s ->
{ System.out.println(s.toUpperCase()) }, "good morning!"); would cause compilation
error. 

method(s -> s.toUpperCase(), "good morning!"); is a legal syntax but, nothing is


printed to the console.
Question 78: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Collections;
5. import java.util.List;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<String> list = Arrays.asList("M", "R", "A", "P");
10. Collections.sort(list, null);
11. System.out.println(list);
12. }
13. }
What will be the result of compiling and executing Test class?

[A, M, P, R]
(Correct)


[M, R, A, P]


[R, P, M, A]


Runtime Exception

Explanation
If null Comparator is passed to sort method, then elements are sorted in natural
order (based on Comparable interface implementation). 

As list is of String type and String implements Comparable, hence list elements are
sorted in ascending order.

Question 79: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void div(int i, int j) {
5. try {
6. System.out.println(i / j);
7. } catch(ArithmeticException e) {
8. throw (RuntimeException)e;
9. }
10. }
11. public static void main(String[] args) {
12. try {
13. div(5, 0);
14. } catch(ArithmeticException e) {
15. System.out.println("AE");
16. } catch(RuntimeException e) {
17. System.out.println("RE");
18. }
19. }
20. }
What will be the result of compiling and executing Test class?

Program ends abruptly


AE
(Correct)


Compilation error


RE

Explanation
Any RuntimeException can be thrown without any need it to be declared in throws
clause of surrounding method.

'throw (RuntimeException)e;' doesn't cause any compilation error.

Even though variable 'e' is type casted to RuntimeException but exception object is
still of ArithmeticException, which is caught in main method and 'AE' is printed to the
console.

Question 80: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path path = Paths.get("F:", "user", "..", "udayan..");
9. System.out.println(path.normalize());
10. }
11. }
What will be the result of compiling and executing Test class?

F:\udayan..
(Correct)


F:\


F:\user


F:\user\udayan

Explanation
path --> {F:\user\..\udayan..}. path.normalize() will return {F:\udayan..}.

NOTE: double dot with 'udayan' is not removed as these are not path symbol.

Question 81: Skipped

For the code below:


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String [] arr = {"**", "***", "*", "*****", "****"};
8. Arrays.sort(arr, (s1, s2) -> s1.length()-s2.length());
9. for(String str : arr) {
10. System.out.println(str);
11. }
12. }
13. }
What do you need to do so that above code gives following output?
1. *
2. **
3. ***
4. ****
5. *****


Existing code without any changes displays above output.
(Correct)


Add the import statement for the Comparator interface: import
java.util.Comparator;


Change the lambda expression to  (s1, s2) -> s2.length()-s1.length()  

Change the lambda expression to  (s2, s1) -> s1.length()-s2.length()  
Explanation
Even though lambda expression is for the compare method of Comparator interface,
but in the code name "Comparator" is not used hence import statement is not
needed here.

Expressions (s1, s2) -> s2.length()-s1.length() and (s2, s1) -> s1.length()-s2.length()
displays the output in reversed order.

Question 82: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Point {
4. private int x;
5. private int y;
6.  
7. Point(){
8. Point(10, 20);
9. }
10.  
11. Point(int x, int y) {
12. this.x = x;
13. this.y = y;
14. }
15.  
16. @Override
17. public String toString() {
18. return "Point{" + x + ", " + y + "}";
19. }
20. }
21.  
22. public class Test {
23. public static void main(String[] args) {
24. Point p = new Point();
25. System.out.println(p);
26. }
27. }
What will be the result of compiling and executing Test class?

Compilation error in Test class


Compilation error in Point class
(Correct)


Point{0, 0}


Point{10, 20}

Explanation
To call another constructor of the class use this(10, 20);
No-argument constructor of Point class causes compilation error.

Question 83: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. class Student {
6. private String name;
7. private int age;
8.  
9. Student(String name, int age) {
10. this.name = name;
11. this.age = age;
12. }
13.  
14. public String getName() {
15. return name;
16. }
17.  
18. public int getAge() {
19. return age;
20. }
21.  
22. public void setName(String name) {
23. this.name = name;
24. }
25.  
26. public void setAge(int age) {
27. this.age = age;
28. }
29. }
30.  
31. public class Test {
32. public static void main(String[] args) throws IOException,
ClassNotFoundException {
33. Student stud = new Student("John", 20);
34.  
35. try( ObjectOutputStream oos = new ObjectOutputStream(
36. new FileOutputStream("C:\\Student.dat")) ){
37. oos.writeObject(stud);
38. }
39.  
40. try( ObjectInputStream ois = new ObjectInputStream(
41. new FileInputStream("C:\\Student.dat")) ){
42. stud = (Student)ois.readObject();
43. System.out.printf("%s : %d", stud.getName(), stud.getAge());
44. }
45. }
46. }
There is full permission to list/create/delete files and directories in C:.

What will be the result of compiling and executing Test class?


null : 0

Runtime Exception
(Correct)


John : 20


Compilation error

Explanation
As Student class doesn't implement Serializable or Externalizable, hence
'oos.writeObject(stud);' throws java.io.NotSerializableException.

To persist Student objects using ObjectInputStream, Student class should implement


Serializable.

Question 84: Skipped

C:\ is accessible for reading/writing and below is the content of 'C:\TEMP' folder:
1. C:\TEMP
2. │ msg
3. │
4. └───Parent
5. └───Child
6. Message.txt
'msg' is a symbolic link file for 'C:\TEMP\Parent\Child\Message.txt'.

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7.  
8. public class Test {
9. public static void main(String[] args) throws IOException {
10. Path src = Paths.get("C:", "TEMP", "msg");
11. Files.delete(src);
12. }
13. }
What will be the result of compiling and executing Test class?

The code executes successfully but doesn't delete anything

The code executes successfully and deletes all the directories and files in the path
'C:\TEMP\Parent\Child\Message.txt'

The code executes successfully and deletes the file referred by symbolic link
'Message.txt'

The code executes successfully and deletes symbolic link file 'msg'
(Correct)

Explanation
According to the javadoc comment of delete method, if the file is a symbolic link then the
symbolic link itself, not the final target of the link, is deleted.

Question 85: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Optional<Integer> optional = Optional.of(null); //Line 8
8. System.out.println(optional.orElse(-1)); //Line 9
9. }
10. }
What will be the result of compiling and executing Test class?

Line 9 throws NullPointerException


-1


Line 8 throws NullPointerException
(Correct)


null

Explanation
Optional.of(null); throws NullPointerException if null arguments is passes.

You can use 'Optional.ofNullable(null);' to create an empty optional.

Question 86: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Collections;
5. import java.util.List;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<String> list = Arrays.asList("M", "R", "A", "P");
10. Collections.sort(list, null);
11. list.stream().peek(System.out::print);
12. }
13. }
What will be the result of compiling and executing Test class?

AMPR


None of the other options
(Correct)


MRAP


Runtime Exception


RPMA

Explanation
Streams are lazily evaluated, which means if terminal operations such as: forEach,
count, toArray, reduce, collect, findFirst, findAny, anyMatch, allMatch, sum, min, max,
average etc. are not present, the given stream pipeline is not evaluated and hence
peek() method doesn't print anything on to the console.
Question 87: Skipped

Consider below code:


1. package com.udayan.ocp;
2.  
3. import java.util.function.Function;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Function<Integer, Integer> f = x -> x + 10;
8. Function<Integer, Integer> g = y -> y * y;
9.
10. Function<Integer, Integer> fog = g.compose(f); //Line 8
11. System.out.println(fog.apply(10));
12. }
13. }
On execution, Test class prints 400 on to the console. Which of the statements can
replace Line 8 such that there is no change in the output?

Function fog = f.andThen(g);  
(Correct)

Function fog = g.andThen(f);  


Function fog = f.compose(g);  
Explanation
compose & andThen are default methods defined in Function interface.

Starting with JDK 8, interfaces can define default and static methods.

g.compose(f); means first apply f and then g. Same result is achieved by f.andThen(g);
=> first apply f and then g.

f.apply(10) = 10 + 10 = 20 and g.apply(20) = 20 * 20 = 400.

Question 88: Skipped

Given statement:

_________ represents date-based amount of time whereas _________ represents time-


based amount of time.

Which of the following two options correctly fill the blanks in order?


Instant, Duration

Duration, Period

Duration, Instant

Period, Duration
(Correct)

Explanation
Correct statement is:

Period represents date-based amount of time whereas Duration represents time-


based amount of time.
Period is date-based, such as '10 years, 5 months and 3 days'.

Duration is time-based, such as '5 hours, 10 minutes and 44 seconds'.

Instant is to just represent an instantaneous point on the time-line.

Check the Javadoc of above classes.

Question 89: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class Adder extends RecursiveAction {
6.     private int from;
7.     private int to;
8.     int total = 0;
9.  
10.     Adder(int from, int to) {
11.         this.from = from;
12.         this.to = to;
13.     }
14.  
15.     @Override
16.     protected void compute() {
17.         if ((to - from) <= 4) {
18.             int sum = 0;
19.             for(int i = from; i <= to; i++) {
20.                 sum += i;
21.             }
22.             total+=sum;
23.         } else {
24.             int mid = (from + to) / 2;
25.             Adder first = new Adder(from, mid);
26.             Adder second = new Adder(mid + 1, to);
27.             invokeAll(first, second);
28.         }
29.     }
30. }
31.  
32. public class Test {
33.     public static void main(String[] args) {
34.         Adder adder = new Adder(1, 5); //Line 34
35.         ForkJoinPool pool = new ForkJoinPool(4);
36.         pool.invoke(adder);
37.         System.out.println(adder.total);
38.     }
39. }
What will be the result of compiling and executing Test class?

It will print 0 on to the console

It can print any number between 0 and 15

None of the other options

It will print 15 on to the console
(Correct)

Explanation
RecursiveAction class has an abstract method 'void compute()' and Adder class
correctly overrides it. 

new Adder(1, 5); instantiate an Adder object with from = 1, to = 5 and total = 0. 

5 - 1 = 4, which is less than or equal to 4 hence else block will not get executed.
compute() method will simply add the numbers from 1 to 5 and will update the total
field of Adder object created at Line 34.

So when 'System.out.println(adder.total);' is executed, it prints 15 on to the console.

If Line 34 is replaced with 'Adder adder = new Adder(1, 6);', then else block of
compute() method will create more Adder objects and total filed of those Adder
objects will be updated and not the Adder object created at Line 34. So, in this case
output will be 0.

Best solution would be to add below code as the last statement in the else block so
that total field of Adder object created at Line 34 is updated successfully:

total = first.total + second.total;

It will give the expected result in all the cases.

Question 90: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.List;
4. import java.util.concurrent.CopyOnWriteArrayList;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> list = new CopyOnWriteArrayList<>();
9. list.add("Melon");
10. list.add("Apple");
11. list.add("Banana");
12. list.add("Mango");
13. for(String s : list) {
14. list.removeIf(str -> str.startsWith("M"));
15. System.out.println(s);
16. }
17. }
18. }
What will be the result of compiling and executing Test class?

Melon
Apple
Banana
Mango
(Correct)


Apple
Banana

An exception is thrown at runtime


Compilation error

Explanation
removeIf method accepts Predicate, hence no compilation error.

Enhanced for loop uses an internal iterator and as CopyOnWriteArrayList is used,


add/set/remove operations while iterating doesn't cause any exception.

In first iteration, removeIf method removes 'Melon' and 'Mango' from the list. On
every modification, a fresh copy of underlying array is created, leaving the iterator
object unchanged. 'Melon' is printed on to he console.

In 2nd iteration, removeIf method doesn't remove anything as list doesn't contain
any element starting with 'M'. But iterator still has 4 elements. 2nd iteration prints
'Apple' on to the console. And so on.
Practice Test 4 - Results

 Return to review

Attempt 1
All knowledge areas

All questions

Question 1: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.Consumer;
4.  
5. public class Test {
6.  
7. public static void main(String[] args) {
8. Consumer<String> c1 = str -> {
9. System.out.println(new StringBuilder(str).reverse()
10. .toString().substring(2));
11. };
12. c1.accept("!yppahnu");
13. }
14. }
What will be the result of compiling and executing Test class?

happy!
(Correct)


unhapp


!yppah


ppahnu

Explanation
Consumer<T> interface has void accept(T) method, which means in this case,
Consumer<String> interface has void accept(String) method. 
Given lambda expression accepts String argument and does some operation. 

First String is converted to StringBuilder object to use the reverse method. new
StringBuilder("!yppahnu").reverse().toString() returns "unhappy!" and
"unhappy!".substring(2) returns "happy!", which is printed by System.out.println
method.

Question 2: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. System.out.printf("%2$d + %1$d", 10, 20);
6. }
7. }
What will be the result of compiling and executing Test class?

30


20 + 10
(Correct)


None of the other options


10 + 20

Explanation
In format string, format specifier are just replaced.

2$ means 2nd argument, which is 20 and 1$ means 1st argument, which is 10.

Hence 'System.out.printf("%2$d + %1$d", 10, 20);' prints '20 + 10' on to the console.

NOTE: System.out.printf(...) is same as  System.out.format(...).

Question 3: Skipped

F: is accessible for reading/writing and below is the directory structure for F:


1. F:.
2. ├───Parent
3. │ └───Child
4. │ Message.txt
5. │
6. ├───Shortcut
7. │ Child.lnk
8. │
9. └───Other
10. └───Logs

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7.     public static void main(String[] args) {
8.         Path path1 = Paths.get("F:", "Other", "Logs");
9.         Path path2 = Paths.get("..", "..", "Shortcut", "Child.lnk", "Message.txt");
10.         Path path3 = path1.resolve(path2).normalize();
11.         Path path4 = path1.resolveSibling(path2).normalize();
12.         System.out.println(path3.equals(path4));    }
13. }

What will be the result of compiling and executing Test class?


false


An exception is thrown at runtime.


true
(Correct)

Explanation
path1 --> [F:\Other\Logs]. 

path2 --> [..\..\Shortcut\Child.lnk\Message.txt]. 

path1.resolve(path2) --> [F:\Other\Logs\..\..\Shortcut\Child.lnk\Message.txt]. 

path3 --> [F:\Shortcut\Child.lnk\Message.txt]. 

path1.resolveSibling(path2) --> [F:\Other\..\..\Shortcut\Child.lnk\Message.txt].


path4 --> [F:\Shortcut\Child.lnk\Message.txt].

This is interesting, if you are at the root directory, and give the command cd .., then
nothing happens, you stay at the root only. 

System.out.println(Paths.get("F:\\..\\..\\..\\..").normalize()); would print F:\. 

This is the reason, why path4 is referring to [F:\Shortcut\Child.lnk\Message.txt] and


no exception is thrown at runtime.

As path3 and path4 refer to same location, hence path3.equals(path4) returns true.

Question 4: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. class MyResource implements AutoCloseable {
4. public void execute() {
5. System.out.println("Executing");
6. }
7.
8. @Override
9. public void close() {
10. System.out.println("Closing");
11. }
12. }
13.  
14. public class Test {
15. public static void main(String[] args) {
16. try(MyResource resource = new MyResource()) {
17. resource.execute();
18. }
19. }
20. }
What will be the result of compiling and executing Test class?

Executing


Executing
Closing
(Correct)


Runtime Exception

Compilation Error

Explanation
close() method in AutoCloseable interface has below declaration:

void close() throws Exception;

MyResource class correctly overrides close() method.

try-with-resources statement internally invokes resource.close() method after


executing resource.execute().

Output is:

Executing

Closing

Question 5: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Set<Character> set = new TreeSet<>(Arrays.asList('a','b','c','A','a','c'));
8. set.stream().forEach(System.out::print);
9. }
10. }
What will be the result of compiling and executing Test class?

abc


Aabc
(Correct)


Aaabcc

abcAac

Explanation
TreeSet requires you to provide either Comparable or Comparator. If you don't
provide Comparator explicitly, then for natural ordering your class should implement
Comparable interface.

Character and all wrapper classes implement Comparable interface, hence Characters
are sorted in ascending order. Uppercase characters appears before lowercase
characters.

Set doesn't allow duplicate, hence output will always be: 'Aabc'.

Question 6: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. List<String> colors = new ArrayList<>();
8. colors.add("RED");
9. colors.add("GREEN");
10. colors.add("BLUE");
11. Iterator<String> iter = colors.iterator();
12. while(iter.hasNext()) {
13. iter.remove();
14. iter.next();
15. }
16. System.out.println(colors.size());
17. }
18. }
What will be the result of compiling and executing Test class?

0


Runtime exception
(Correct)


2

Explanation
Iterator and ListIterator allow to remove elements while iterating. But next() should
be called before remove().

In this case, remove() is called before next() and hence IllegalStateException is thrown
at runtime.

Question 7: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Printer<T implements Cloneable> {}
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Printer<String> printer = new Printer<>();
8. System.out.println(printer);
9. }
10. }
What will be the result of compiling and executing Test class?

Some text containing @ symbol


Compilation error for Printer class
(Correct)


Compilation error for Test class

Explanation
For bounds, extends keyword is used for both class and interface.

Correct declaration of Printer class should be:

class Printer<T extends Cloneable> {}

Question 8: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path path = Paths.get("F:\\A\\B\\C\\Book.java");
9. System.out.println(path.subpath(1,5));
10. }
11. }
What will be the result of compiling and executing Test class?

F:\A\B\C\Book.java


A\B\C


Exception is thrown at runtime
(Correct)


A\B\C\Book.java

Explanation
Root folder or drive is not considered in count and indexing. In the given path A is at
0th index, B is at 1st index, C is at 2nd index and Book.java is at 3rd index.

In 'subpath(int beginIndex, int endIndex)' method beginIndex in inclusive and


endIndex is exclusive.

So, in the given question, starting index is 1 and end index is 4. In the given path
there is no element at the 4th index, hence an exception is thrown at runtime.

In fact, subpath(int beginIndex, int endIndex) throws IllegalArgumentException if


'beginIndex >= No. of path elements', 'endIndex > No. of path elements' and
'endIndex <= beginIndex'.

Question 9: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Scanner;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try(Scanner scan = new Scanner(System.in)) {
8. String s = scan.nextLine();
9. System.out.println(s);
10. scan = null;
11. }
12. }
13. }
What will be the result of compiling and executing Test class?

Compilation error
(Correct)


Exception is thrown at runtime


Normal Termination

Explanation
Resources used in try-with-resources statement are implicitly final, which means they
can't be reassigned.

scan = null; will fail to compile as we are trying to assign null to variable scan.

Question 10: Skipped

Consider below interface:


1. interface I2 {
2. int calc(int x);
3. }
Which of the following is the correct lambda expression for I2?

I2 obj1 = x -> return x*x;  


I2 obj2 = (x) -> return x*x;  


I2 obj3 = x - > x*x;  


I2 obj4 = x -> x*x;  
(Correct)

Explanation
If curly brackets are removed from lambda expression body, then return keyword
should also be removed.

There should not be space between - and >.

For one parameter, parentheses or round brackets () can be removed.

Question 11: Skipped

F: is accessible for reading/writing and below is the directory structure for F:


1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7.  
8. public class Test {
9. public static void main(String[] args) throws IOException{
10. Path src = Paths.get("F:\\A\\B\\C\\Book.java");
11. Path tgt = Paths.get("F:\\A\\B\\Book.java");
12. Path copy = Files.copy(src, tgt);
13. System.out.println(Files.isSameFile(src, copy));
14. System.out.println(Files.isSameFile(tgt, copy));
15. }
16. }

What will be the result of compiling and executing Test class?


false
true
(Correct)


true
false

false
false

true
true
Explanation
'Files.copy(src, tgt);' copies 'F:\A\B\C\Book.java' to 'F:\A\B\Book.java' and returns the
Path of copied element.

src refers to 'F:\A\B\C\Book.java'. 

tgt refers to 'F:\A\B\Book.java'. 

copy refers to 'F:\A\B\Book.java'. 


Files.isSameFile(Path path1, Path path2) returns true if both the paths locate the
same physical file. 

src and copy refer to different physical files, hence 'Files.isSameFile(src, copy)' returns
false. 

tgt and copy refer to same physical file, hence 'Files.isSameFile(tgt, copy)' returns
true.

Question 12: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.Collections;
5. import java.util.Comparator;
6. import java.util.List;
7.  
8. class Point {
9. private int x;
10. private int y;
11.
12. public Point(int x, int y) {
13. this.x = x;
14. this.y = y;
15. }
16.
17. public int getX() {
18. return x;
19. }
20.  
21. public int getY() {
22. return y;
23. }
24.  
25. @Override
26. public String toString() {
27. return "Point(" + x + ", " + y + ")";
28. }
29. }
30.  
31. public class Test {
32. public static void main(String [] args) {
33. List<Point> points = new ArrayList<>();
34. points.add(new Point(4, 5));
35. points.add(new Point(6, 7));
36. points.add(new Point(2, 2));
37.
38. Collections.sort(points, new Comparator<Point>() {
39. public int compare(Point o1, Point o2) {
40. return o2.getX() - o1.getX();
41. }
42. });
43.
44. System.out.println(points);
45. }
46. }

[Point(4, 5), Point(6, 7), Point(2, 2)]


Compilation error


[Point(6, 7), Point(4, 5), Point(2, 2)]
(Correct)


[Point(2, 2), Point(4, 5), Point(6, 7)]

Explanation
return o2.getX() - o1.getX(); means the Comparator is sorting the Point objects on
descending value of x of Point objects.

To sort the Point objects in ascending order of x, use: return o1.getX() - o2.getX(); 

To sort the Point objects in ascending order of y, use: return o1.getY() - o2.getY();

To sort the Point objects in descending order of y, use: return o2.getY() - o1.getY();

Question 13: Skipped

Consider below code:


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Collections;
5. import java.util.Comparator;
6. import java.util.List;
7.  
8. public class Test {
9. public static void main(String [] args) {
10. List<String> names = Arrays.asList("James", "diana", "Anna");
11.
12. /*INSERT*/
13.
14. System.out.println(names);
15. }
16. }

Currently on executing Test class, [James, diana, Anna] is printed in the output. 

Which of the following options can replace /*INSERT*/ such that on executing Test
class, [Anna, diana, James] is printed in the output?


Collections.sort(names);  


1. Collections.sort(names, new Comparator<String>() {
2. public int compare(String o1, String o2) {
3. return o1.compareToIgnoreCase(o2);
4. }
5. });
(Correct)


1. Collections.sort(names, new Comparator<String>() {
2. public int compare(String o1, String o2) {
3. return o2.compareTo(o1);
4. }
5. });

1. Collections.sort(names, new Comparator<String>() {
2. public int compare(String o1, String o2) {
3. return o1.compareTo(o2);
4. }
5. });
Explanation
If you sort String in ascending order, then upper case letters appear before the lower
case letters.

So in this case if I sort the list in ascending order then the output will be [Anna,
James, diana] and this is what Collections.sort(names); and o1.compareTo(o2);
method calls do.

o2.compareTo(o1); sorts the same list in descending order: [diana, James, Anna] but
you have to sort the list such that [Anna, diana, James] is printed in the output,

which means sort the names in ascending order but in case-insensitive manner.
String class has compareToIgnoreCase() method for such purpose.

Question 14: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Optional<String> optional = Stream.of("red", "green", "blue", "yellow")
9. .sorted().findFirst();
10. System.out.println(optional.get());
11. }
12. }
What will be the result of compiling and executing Test class?

green


blue
(Correct)


red


yellow

Explanation
Stream.of("red", "green", "blue", "yellow") => ["red", "green", "blue", "yellow"]. 

sorted() => ["blue", "green", "red", "yellow"]. 

findFirst() => ["blue"]. findFirst returns Optional<String> object.

Question 15: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.Arrays;
5. import java.util.List;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<String> list = new ArrayList<>(Arrays.asList("Z", "Y", "X"));
10. list.stream().sorted().findFirst().get();
11. System.out.println(list.get(2));
12. }
13. }
What will be the result of compiling and executing Test class?

Runtime Exception


X
(Correct)


Y

Z

Explanation
findFirst() will never return empty Optional if stream is not empty. So no exception
for get() method.

Also list and stream are not connected, which means operations done on stream
doesn't affect the source, in this case list.

list.get(2) will print 'X' on to the console.

Question 16: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. private static StringBuilder RES = new StringBuilder();
8.  
9. public static void main(String[] args) {
10. List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F",
11. "G", "H", "I", "J");
12. list.parallelStream().forEach(RES::append);
13. System.out.println(RES);
14. }
15. }
What will be the result of compiling and executing Test class?

Output cannot be predicted
(Correct)


Compilation error

It will always print ABCDEFGHIJ
Explanation
list.parallelStream() returns a parallel stream.

Method reference 'RES::append' is same as lambda expression 's -> RES.append(s)'.


NOTE: In the lambda expression as static variable RES is used hence given code
suffers from race condition.
Output cannot be predicted in this case.

Question 17: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.nio.file.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Path path = Paths.get("F:\\A");
8. System.out.println(path.getRoot().equals(path.getParent()));
9. }
10. }
What will be the result of compiling and executing Test class?

false


true
(Correct)


NullPointerException is thrown at runtime

Explanation
path refers to 'F:\A', path.getRoot() refers to 'F:\' and path.getParent() refers to 'F:\'.

Hence result is 'true'.

Question 18: Skipped

What will be the result of compiling and executing the following program?
1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static String s;
5. public static void main(String[] args) {
6. try {
7. System.out.println(s.length());
8. } catch(NullPointerException | RuntimeException ex) {
9. System.out.println("DONE");
10. }
11. }
12. }


Executes successfully but no output


Compilation error
(Correct)


DONE

Explanation
NullPointerException extends RuntimeException and in multi-catch syntax we can't specify
multiple Exceptions related to each other in multilevel inheritance.

Question 19: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.LocalTime;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalTime time = LocalTime.parse("14:14:59.1111");
8. System.out.println(time);
9. }
10. }
What will be the result of compiling and executing Test class?

14:14:59.1111


14:14:59.111100000


14:14:59.111100
(Correct)


Runtime Exception

Explanation
LocalTime.parse(text); => text must represent a valid time and it is parsed using
DateTimeFormatter.ISO_LOCAL_TIME.

ISO_LOCAL_TIME represents time in following format:

HH:mm (if second-of-minute is not available), 

HH:mm:ss (if second-of-minute is available), 

HH:mm:ss.SSS (if nano-of-second is 3 digit or less), 

HH:mm:ss.SSSSSS (if nano-of-second is 4 to 6 digits), 


HH:mm:ss.SSSSSSSSS (if nano-of-second is 7 to 9 digits). 

Valid values for hour-of-day (HH) is: 0 to 23. 

Valid values for minute-of-hour (mm) is: 0 to 59. 

Valid values for second-of-minute (ss) is: 0 to 59. 

Valid values for nano-of-second is: 0 to 999999999.

In the given expression, 'LocalTime.parse("14:14:59.1111");' all the values are within


range and as nano-of-second is of 4 digit, hence toString() method appends 2 zeros
to it.

Output is: '14:14:59.111100'.

Question 20: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. abstract class Animal {
4. public static void vaccinate() {
5. System.out.println("Vaccinating...");
6. }
7.  
8. abstract void treating();
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. Animal.vaccinate();
14. }
15. }
What will be the result of compiling and executing Test class?

Compilation error in Animal class


Compilation error in Test class


Vaccinating...
(Correct)
Explanation
Abstract class can have static methods and those can be called by using
Class_Name.method_name. 

class Animal is declared with package(default) scope, which means it can be


extended by other classes in the same package(com.udayan.ocp).

Above code executes fine and prints 'Vaccinating...' on to the console.

Question 21: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. class MyException extends RuntimeException {}
4.  
5. class YourException extends RuntimeException {}
6.  
7. public class Test {
8. public static void main(String[] args) {
9. try {
10. throw new YourException();
11. } catch(MyException | YourException e){
12. e = null;
13. }
14. }
15. }
What will be the result of compiling and executing Test class?

Compilation error
(Correct)


Runtime Exception


Nothing is printed on to the console and program terminates successfully

Explanation
Variable 'e' used in multi-catch block is implicitly final and can't be re-initialized.

e = null; causes compilation failure.

Question 22: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. File dirs = new File("F:\\A\\B\\C");
8. System.out.println(dirs.mkdirs());
9. File dir = new File("F:\\A");
10. System.out.println(dir.mkdir());
11. System.out.println(dir.delete());
12. }
13. }
F: is accessible for reading/writing and currently doesn't contain any files/directories.
What will be the result of compiling and executing Test class?

true
false
false
(Correct)


true
true
true

true
false
true

false
true
true

false
false
false
Explanation
Given File methods return boolean and don't throw any checked exception at
runtime.

dirs -> referring to File object for abstract path: F:\A\B\C.

Initially F: is blank.

System.out.println(dirs.mkdirs()); => Creates all the directories A, B, C as per abstract


path and returns true.
dir -> referring to File object for abstract path: F:\A

System.out.println(dir.mkdir()); => returns false as F:\A directory exists.

System.out.println(dir.delete()); => returns false as F:\A is not empty directory, it


contains directory 'B'.

Question 23: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class A{}
4. interface M{}
5. interface N{}
6.  
7. class B extends A {}
8. class C extends A implements M {}
9. class D extends A implements M, N {}
10.  
11. class Generic<T extends A & M & N> {}
12.  
13. public class Test {
14. public static void main(String[] args) {
15. /*INSERT*/
16. }
17. }

Which of the following statements, if used to replace /*INSERT*/, will not cause any
compilation error?


Generic<D> obj = new Generic<>();  
(Correct)


Generic<A> obj = new Generic<>();  


Generic<N> obj = new Generic<>();  


All options will work


Generic<M> obj = new Generic<>();  
Explanation
T is with multiple bounds, so the type argument must be a subtype of all bounds.

Question 24: Skipped

Given:
1. package com.udayan.ocp;
2.  
3. enum TrafficLight {
4. RED, YELLOW, GREEN;
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. TrafficLight tl1 = TrafficLight.GREEN;
10. TrafficLight tl2 = tl1.clone(); //Line 10
11. System.out.println(tl2); //Line 11
12. }
13. }
What will be the result of compiling and executing Test class?

GREEN


Line 11 throws CloneNotSupportedException at runtime


Compilation error at Line 10
(Correct)

Explanation
Every enum extends from java.lang.Enum class and it contains following definition of
clone method:

protected final Object clone() throws CloneNotSupportedException {


throw new CloneNotSupportedException();
}

Every enum constant (RED, YELLOW, GREEN) is an instance of TrafficLight enum and
as clone method is protected in Enum class so it cannot be accessed in
com.udayan.ocp package using reference variable.

Question 25: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Map<Integer, String> map = new LinkedHashMap<>();
8. map.put(null, "zero");
9. map.put(1, "one");
10.  
11. System.out.println(map);
12. }
13. }
What will be the result of compiling and executing Test class?

Runtime Exception


{null=zero, 1=one}
(Correct)


{1=one, null=zero}


Order cannot be predicted

Explanation
HashMap and LinkedHashMap can accept 1 null key but TreeMap cannot accept null
keys.

LinkedHashMap by default keeps an insertion order so every time you iterate the
map, you get same result.

Output will always be: {null=zero, 1=one}

Question 26: Skipped

Given code: 
1. package com.udayan.ocp;
2.  
3. class Message {
4. public void printMessage() {
5. System.out.println("Hello!");
6. }
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. Message msg = new Message() {
12. public void PrintMessage() {
13. System.out.println("HELLO!");
14. }
15. };
16. msg.PrintMessage();
17. }
18. }
What will be the result of compiling and executing Test class?

Compilation error
(Correct)


HELLO!


Hello!


Runtime error

Explanation
Even though anonymous inner class allows to define methods not available in its
super class but these methods cannot be invoked from outside the anonymous inner
class code.

Reason is very simple, methods are invoked on super class reference variable (msg)
which is of Message type.

And class Message is aware of the methods declared or defined within its boundary,
printMessage() method in this case.

So using Message class reference variable, methods defined in sub class cannot be
invoked. So, msg.PrintMessage(); statement causes compilation error.

Question 27: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date = LocalDate.ofYearDay(2018, 0);
8. System.out.println(date);
9. }
10. }
What will be the result of compiling and executing Test class?

Runtime Exception
(Correct)


2018-1-1


2018-01-01


2017-12-31

Explanation
LocalDate ofYearDay(int year, int dayOfYear): Valid values for dayOfYear for non-leap
year is 1 to 365 and for leap year is 1 to 366.

For other values, java.time.DateTimeException is thrown.

Question 28: Skipped

Given structure of EMPLOYEE table:


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below record: 


101, John, Smith, 12000

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try {
8. Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ocp",
9. "root",
"password");
10. String query = "Select * FROM EMPLOYEE";
11. Statement stmt = con.createStatement();
12. ResultSet rs = stmt.executeQuery(query);
13. while (rs.next()) {
14. System.out.println("ID: " + rs.getInt("IDD"));
15. System.out.println("First Name: " + rs.getString("FIRSTNAME"));
16. System.out.println("Last Name: " + rs.getString("LASTNAME"));
17. System.out.println("Salary: " + rs.getDouble("SALARY"));
18. }
19. rs.close();
20. stmt.close();
21. con.close();
22. } catch (SQLException ex) {
23. System.out.println("An Error Occurred!");
24. }
25. }
26. }

Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


Compilation Error


Code executes fine and prints following on to the console:
ID: 101
First Name: John
Last Name: Smith
Salary: 12000

Code executes fine and doesn't print anything on to the console.


Code executes fine and prints following on to the console: 
ID: 0
First Name: John
Last Name: Smith
Salary: 12000

'An Error Occurred!' is printed on to the console
(Correct)

Explanation
As SELECT statement returns one record, code inside while loop is executed.

'rs.getInt("IDD")' throws SQLException as column name 'IDD' will not be found at


runtime. Exception handler for SQLException is available, which prints 'An Error
Occurred!' on to the console.

Question 29: Skipped

Which of the following is a valid ResultSet type?



TYPE_BACKWARD_ONLY


TYPE_BOTH


TYPE_SCROLL


TYPE_FORWARD_ONLY
(Correct)

Explanation
There are 3 ResultSet types: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE and
TYPE_SCROLL_SENSITIVE.

Question 30: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4. import java.time.format.DateTimeFormatter;
5. import java.util.Locale;
6.  
7. public class Test {
8. public static void main(String [] args) {
9. Locale.setDefault(new Locale("en", "US"));
10. LocalDate date = LocalDate.parse("2018-09-10");
11. System.out.println(date.format(DateTimeFormatter.ofPattern("dd-MMM-
yyyy")));
12. }
13. }
What will be the result of compiling and executing Test class?

10-SEP-2018


10-SEPTEMBER-2018


10-September-2018


10-Sep-2018
(Correct)

Explanation
M -> Represents actual digit for the month (1 to 12). 
MM -> Represents 2 digits for the month (01 to 12). 

MMM -> Represents short name for the month, with first character in upper case,
such as Jun, Sep

MMMM -> Represents full name for the month, with first character in upper case,
such as June, September

DateTimeFormatter.ofPattern(String) method uses the default Locale and in this case


default Locale is set to en_US, hence English month names will be printed in this
case.

"2018-09-10" will be formatted to "10-Sep-2018".

Question 31: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Player {
4. String name;
5. int age;
6.  
7. Player() {
8. this.name = "Virat";
9. this.age = 29;
10. }
11.  
12. public int hashcode() {
13. return 100;
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. System.out.println(new Player());
20. }
21. }
Hexadecimal representation of 100 is 64.

Which of the following option is correct?


None of the other options
(Correct)


Code doesn't compile successfully


Code compiles successfully but throws an exception on executing it


Code compiles successfully and on execution always prints
"com.udayan.ocp.Player@64" on to the console

Explanation
If toString() method is not overridden, then Object class's version is invoked.

The toString() method in Object class has below definition:

public String toString() {


return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So, in the output you get: fully-qualified-name-of-the-class@hexadecimal-


representation-of-hash-code. NOTE: hashCode() method is called for that.

Player class doesn't override the hashCode() method, rather it defines a new method
hashcode() [NOTE: c in lower case in the method name].

Hence, hashcode() is never invoked and no guarantee of getting 64 always.

Question 32: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.FileNotFoundException;
4. import java.io.IOException;
5.  
6. abstract class Super {
7. public abstract void m1() throws IOException;
8. }
9.  
10. class Sub extends Super {
11. @Override
12. public void m1() throws IOException {
13. throw new FileNotFoundException();
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. Super s = new Sub();
20. try {
21. s.m1();
22. } catch (FileNotFoundException e) {
23. System.out.print("M");
24. } finally {
25. System.out.print("N");
26. }
27. }
28. }
What will be the result of compiling and executing Test class?

Program ends abruptly

Compilation error
(Correct)


N


MN

Explanation
Even though an instance of FileNotFoundException is thrown by method m1() at
runtime, but method m1() declares to throw IOException.

Reference variable s is of Super type and hence for compiler call to s.m1(); is to
method m1() of Super, which throws IOException.

And as IOException is checked exception hence calling code should handle it.

As calling code doesn't handle IOException or its super type, so s.m1(); causes
compilation error. Even though an instance of FileNotFoundException is thrown by
method m1() at runtime, but method m1() declares to throw IOException.

Reference variable s is of Super type and hence for compiler call to s.m1(); is to
method m1() of Super, which throws IOException.

And as IOException is checked exception hence calling code should handle it.

As calling code doesn't handle IOException or its super type, so s.m1(); causes
compilation error.

Question 33: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Map;
4. import java.util.TreeMap;
5. import java.util.function.Function;
6. import java.util.stream.Collectors;
7. import java.util.stream.Stream;
8.  
9. class Person {
10. int id;
11. String name;
12. Person(int id, String name) {
13. this.id = id;
14. this.name = name;
15. }
16. public String toString() {
17. return "{" + id + ", " + name + "}";
18. }
19.  
20. public boolean equals(Object obj) {
21. if(obj instanceof Person) {
22. Person p = (Person) obj;
23. return this.id == p.id;
24. }
25. return false;
26. }
27.  
28. public int hashCode() {
29. return new Integer(this.id).hashCode();
30. }
31. }
32.  
33. public class Test {
34. public static void main(String[] args) {
35. Person p1 = new Person(1010, "Sean");
36. Person p2 = new Person(2843, "Rob");
37. Person p3 = new Person(1111, "Lucy");
38.  
39. Stream<Person> stream = Stream.of(p1, p2, p3);
40. Map<Integer, Person> map = stream.collect(/*INSERT*/);
41. System.out.println(map.size());
42. }
43. }
Which of the following statements can replace /*INSERT*/ such that output is 3?
1.  Collectors.toMap(p -> p.id, Function.identity())  
2.  Collectors.toMap(p -> p.id, p -> p)  
3.  Collectors.toCollection(TreeMap::new)  

Both 1 & 2
(Correct)


Only 1


Only 2

Only 3


All 1, 2 & 3


Both 2 & 3

Explanation
Variable id has package scope and as class Test is in the same package hence p.id
doesn't cause any compilation error.

'Collectors.toMap(p -> p.id, Function.identity())' and 'Collectors.toMap(p -> p.id, p ->


p)' are exactly same, as 'Function.identity()' is same as lambda expression 'p -> p'.

Collectors.toCollection(TreeMap::new) causes compilation error as TreeMap doesn't


extend from Collection interface.

Question 34: Skipped

F: is accessible for reading/writing. Currently there is no 'err.log' file under F:.

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. System.setOut(new PrintStream("F:\\err.log"));
8. try {
9. System.out.println("ONE");
10. System.out.println(1 / 0);
11. } catch (ArithmeticException e) {
12. System.err.println("TWO");
13. }
14. }
15. }
What will be the result of compiling and executing Test class?

err.log file will be created and it will contain following texts:
ONE
TWO

err.log file will be created and it will contain following texts:
ONE
(Correct)


err.log will be created but it will not have any texts inside.


No err.log file will be created.


err.log file will be created and it will contain following texts: 
TWO
Explanation
new PrintStream("F:\\err.log") => This will create a new file 'err.log' under F: and will
create a PrintStream instance.

System.setOut(new PrintStream("F:\\err.log")); => Sets the out PrintStream to passed


object.

System.out.println("ONE"); => Writes 'ONE' to 'err.log' file.

System.out.println(1 / 0); => Throws ArithmeticException, which is caught by the


catch handler.

System.err.println("TWO"); => Prints 'TWO' on to the console, default err Stream. err
PrintStream was not changed using System.setErr(PrintStream) method.

So, 'err.log' file contains 'ONE' only.

Question 35: Skipped

For the given code: 


1. package com.udayan.ocp;
2.  
3. abstract class Greetings {
4. abstract void greet(String s);
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Greetings obj = new Greetings() {
10. public void greet(String s) {
11. System.out.println(s);
12. }
13. };
14. obj.greet("Happy New Year!");
15. }
16. }
Which of the following options successfully replace anonymous inner class code with
lambda expression code?

Greetings obj = (String s) -> {System.out.println(s.toUpperCase());};  


Greetings obj = s -> {System.out.println(s.toUpperCase());};  


Greetings obj = s -> System.out.println(s.toUpperCase());  


Lambda expression cannot be used in this case
(Correct)

Explanation
Reference variable to which lambda expression is assigned is known as target type.
Target type can be a static variable, instance variable, local variable, method
parameter or return type.

Lambda expression doesn't work without target type and target type must be a
functional interface. Functional interface was added in JDK 8 and it contains one non-
overriding abstract method. 

As Greetings is abstract class, so lambda expression cannot be used in this case.

Question 36: Skipped

Given code: 
1. package com.udayan.ocp;
2.  
3. class A {
4. public void print(String name) {
5. class B {
6. B() {
7. System.out.println(name); //Line 5
8. }
9. }
10. }
11. B obj = new B(); //Line 9
12. }
13.  
14. public class Test {
15. public static void main(String[] args) {
16. new A().print("OCP"); //Line 14
17. }
18. }
What will be the result of compiling and executing Test class?

Compilation error at Line 14


OCP


Compilation error at Line 9
(Correct)


Compilation error at Line 5

Explanation
Instance of method-local inner class can only be created within the boundary of
enclosing initialization block or enclosing method.

B obj = new B(); is written outside the closing curly bracket of print(String) method
and hence Line 9 causes compilation error.

Starting with JDK 8, a method local inner class can access local variables and
parameters of the enclosing block that are final or effectively final so no issues with
Line 5.

Question 37: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. IntStream stream = IntStream.rangeClosed(1, 5);
8. System.out.println(stream.parallel().reduce((x, y) -> x + y).getAsInt());
9. }
10. }
What will be the result of compiling and executing Test class?

None of the other options

It can print any number between 1 and 15

It will print 15 on to the console
(Correct)


It will print 0 on to the console
Explanation
stream --> {1, 2, 3, 4, 5}.

stream.parallel() returns a parallel stream.

To understand, 'reduce((x, y) -> x + y)' is equivalent to:

boolean foundAny = false;


int result = null;
for (int element : this stream) {
if (!foundAny) {
foundAny = true;
result = element;
}
else
result = accumulator.applyAsInt(result, element);
}
return foundAny ? OptionalInt.of(result) : OptionalInt.empty();

result will be initialized to 1st element of the stream and output will be the result of
'1 + 2 + 3 + 4 + 5', which is 15.

The whole computation may run in parallel, but parallelism doesn't impact final
result. In this case as there are only 5 numbers, hence it is an overhead to use
parallelism.

reduce((x, y) -> x + y) returns OptionalInt and it has getAsInt() method.


Question 38: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Comparator;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Stream<String> stream = Stream.of("d", "a", "mm", "bb", "zzz", "www");
9. Comparator<String> lengthComp = (s1, s2) -> s1.length() - s2.length();
10. stream.sorted(lengthComp).forEach(System.out::println);
11. }
12. }
Which of the following needs to be done, so that output is: 
a
d
bb
mm
www
zzz

No need to make any changes, on execution given code prints expected result.


Replace  stream.sorted(lengthComp)   with  stream.sorted(lengthComp.reversed()


Replace  stream.sorted(lengthComp)   with  stream.sorted(lengthComp.thenCompar
ing(String::compareTo))  
(Correct)

Explanation
Current code displays below output:

mm

bb

zzz

www
if string's length is same, then insertion order is preserved.

Requirement is to sort the stream in ascending order of length of the string and if
length is same, then sort on natural order.

lengthComp is for sorting the string on the basis of length, thenComparing default
method of Comparator interface allows to pass 2nd level of Comparator.

Hence replacing 'stream.sorted()' with


'stream.sorted(lengthComp.thenComparing(String::compareTo))' will do the trick.

stream.sorted(lengthComp.reversed()) will simply reversed the order, which means


longest string will be printed first, but this is not expected.

Question 39: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.List;
4. import java.util.stream.Collectors;
5. import java.util.stream.Stream;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Stream<String> stream = Stream.of("java", "python", "c", "c++");
10. List<String> list = stream.sorted().collect(Collectors.toList());
11. System.out.println(list);
12. }
13. }
What will be the result of compiling and executing Test class?

[c, c++, java, python]
(Correct)


[c++, c, java, python]


[python, java, c++, c]


[java, python, c, c++]
Explanation
stream.collect(Collectors.toList()) returns an instance of ArrayList and hence output will
always be in ascending order as stream was sorted using sorted() method before converting
to list.

Question 40: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. enum Flags {
4. TRUE, FALSE;
5.  
6. public Flags() {
7. System.out.println("HELLO");
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. Flags flags = Flags.TRUE;
14. }
15. }
What will be the result of compiling and executing Test class?

Exception is thrown at runtime

HELLO is printed twice

Compilation error
(Correct)


HELLO is printed once
Explanation
Enum constructors are implicitly private, even though you can provide private access
modifier but it will be redundant.

Using 'public' or 'protected' for enum constructors is not allowed.

Question 41: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws InterruptedException,
7. ExecutionException {
8. ExecutorService es = Executors.newSingleThreadExecutor();
9. Future<String> f = es.execute(() -> "HELLO");
10. System.out.println(f.get());
11. es.shutdown();
12. }
13. }
What will be the result of compiling and executing Test class?

Compilation error
(Correct)


null


HELLO


An exception is thrown at runtime

Explanation
ExecutorService interface extends Executor interface and it has 'void
execute(Runnable command);'. Runnable is a Functional interface which has single
abstract method 'public abstract void run();'.   

Given lambda expression, '() -> "HELLO"' returns a String and it doesn't match with
the implementation of run() method whose return type is void. Hence it causes
compilation error.

Return type of execute method is void, hence another reason for compilation error is
that result of ex.execute(...) cannot be assigned to Future<String>.

Question 42: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. try {
6. check();
7. } catch(RuntimeException e) {
8. System.out.println(e.getClass().getName()); //Line n1
9. }
10. }
11.
12. private static void check() {
13. try {
14. RuntimeException re = new RuntimeException(); //Line n2
15. throw re; //Line n3
16. } catch(RuntimeException e) {
17. System.out.println(1);
18. ArithmeticException ex = (ArithmeticException)e; //Line n4
19. System.out.println(2);
20. throw ex;
21. }
22. }
23. }
What will be the result of compiling and executing Test class?

1
2
java.lang.RuntimeException

1
java.lang.ClassCastException
(Correct)


1
java.lang.ArithmeticException

1
java.lang.RuntimeException

1
2
java.lang.ArithmeticException
Explanation
Line n3 throws an instance of RuntimeException. As catch(RuntimeException e) is
available, hence control starts executing catch-block inside check() method.

1 is printed on to the console.

At Line n4, instance of super-class (RuntimeException) is type-casted to sub-class


(ArithmeticException), hence Line n4 throws an instance of ClassCastException.

ClassCastException is a sub-class of RuntimeException, so catch-block of main


method is executed and Line n1 prints the fully qualified name of ClassCastException.
java.lang.ClassCastException is printed on to the console.

Question 43: Skipped

Is below functional interface correctly defined?


1. @FunctionalInterface
2. interface I8 {
3. boolean equals(Object obj);
4. }


No
(Correct)


Yes

Explanation
Functional interface must have one and only one non-overriding abstract method. 

boolean equals(Object) is declared and defined in Object class, hence it is not non-
overriding abstract method. 

@FunctionalInterface annotation causes compilation error.

Question 44: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. IntStream stream = IntStream.rangeClosed(1, 20).filter(i -> i % 2 == 0);
8. System.out.println(stream.summaryStatistics());
9. }
10. }
Which of the following statements is true for above code?

On execution a text containing @ symbol will be printed on to the console

On execution sum, average, max, min and count data will be printed on to the
console
(Correct)


On execution only max, min and count data will be printed on to the console

On execution only sum and average data will be printed on to the console
Explanation
There are 3 summary statistics methods available in JDK 8: IntSummaryStatistics,
LongSummaryStatistics & DoubleSummaryStatistics.

summaryStatistics() method in IntStream class returns an instance of


IntSummaryStatistics.
summaryStatistics() method in LongStream class returns an instance of
LongSummaryStatistics.

summaryStatistics() method in DoubleStream class returns an instance of


DoubleSummaryStatistics.

The 3 summary statistics classes override toString() method to print the data about
count, sum, min, average and max.

All the 3 summary statistics classes have methods to extract specific stat as well:
getCount(), getSum(), getMin(), getMax() and getAverage().

Summary Statistics are really useful if you want multiple stats, say for example you
want to find both min and max. As min and max are terminal operation for finite
stream so after using one operation stream gets closed and not possible to use the
same stream for other terminal operations.

Question 45: Skipped

Given structure of MESSAGES table:


MESSAGES (msg1 varchar(100), msg2 varchar(100))  

MESSAGES table contains below records: 


'Happy New Year!', 'Happy Holidays!'

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select msg1 as msg, msg2 as msg FROM MESSAGES";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
13.
ResultSet.CONCUR_READ_ONLY);
14. ResultSet rs = stmt.executeQuery(query);)
15. {
16. int colCount = rs.getMetaData().getColumnCount();
17. for(int i = 1; i <= colCount; i++) {
18. System.out.println(rs.getString(i));
19. }
20. }
21. }
22. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


An exception is thrown at runtime
(Correct)


Happy New Year!
Happy Holidays!

Happy New Year!
Happy New Year!

Happy Holidays!
Happy Holidays!
Explanation
rs.getMetaData().getColumnCount(); definitely returns 2 as there are 2 columns in the
table. 

But ResultSet cursor is initially before the first record, hence 'rs.getString(i)' throws
SQLException at runtime. 

To print both the column values correctly, either use rs.absolute(1) OR rs.relative(1)
OR rs.next() just before the for loop.

Question 46: Skipped

Built-in functional interfaces are part of which java package?


java.util


java.function


java.util.function
(Correct)


java.lang

Explanation
All the built-in functional interfaces are defined inside java.util.function package.

Question 47: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Random;
4. import java.util.stream.IntStream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. IntStream stream = IntStream.generate(() -> new Random().nextInt(100))
9. .limit(5);
10. stream.filter(i -> i > 0 && i < 10).findFirst()._______________;
11. }
12. }
Which code snippet, when filled into the blank, allows the class to compile?

ifPresent(System.out::println)  
(Correct)


map(i -> i * i)  


get()  


forEach(System.out::println)  
Explanation
It is very simple as you don't have to worry about return type of the code snippet.

stream is of IntStream type. Even method filter returns instance of IntStream type.

findFirst() returns an OptionalInt as it is called on IntStream.


Of all the given options, OptionalInt has 'ifPresent' method only. Hence correct
answer is: 'ifPresent(System.out::println)'.

Question 48: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void checkStatus(boolean flag) {
5. assert flag = true : flag = false;
6. }
7.  
8. public static void main(String[] args) {
9. checkStatus(false);
10. }
11. }
What will be the result of executing Test class with below command?
java -ea:com.udayan... com.udayan.ocp.Test  

Compilation error


AssertionError is thrown and program terminates abruptly


No output and program terminates successfully
(Correct)

Explanation
'java -ea:com.udayan...' enables the assertion in com.udayan package and its sub
packages. Test class is defined under 'com.udayan.ocp' package, hence assertion is
enabled for Test class. 

'assert flag = true : flag = false;' => On the left side 'flag = true' is a valid boolean
expression, so no issues and on right side 'flag = false' assigns false to flag and false
is returned as well, which is not void. Hence no issues with right side as well.

On execution, flag is true, hence AssertionError is not thrown.

Nothing is printed on to the console and program terminates successfully.

Question 49: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class Resource implements AutoCloseable {
4. public void close() {
5. System.out.println("CLOSE");
6. }
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. try(Resource r = null) {
12. r = new Resource();
13. System.out.println("HELLO");
14. }
15. }
16. }
What will be the result of compiling and executing Test class?

Compilation error
(Correct)


HELLO
CLOSE

HELLO


NullPointerException is thrown at runtime

Explanation
Variable r is implicitly final and hence can't be re-initialized.

'r = new Resource();' causes compilation error.

Question 50: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private <T extends Number> static void print(T t) {
5. System.out.println(t.intValue());
6. }
7.  
8. public static void main(String[] args) {
9. print(new Double(5.5));
10. }
11. }
What will be the result of compiling and executing Test class?

5


6


Compilation error
(Correct)


Runtime Exception

Explanation
A generic method is defined in non-generic class.

Type parameter for the method should be defined just before the return type of the
method.

In this case, '<T extends Number>' is not appearing just before void and hence
compilation error.

Question 51: Skipped

F: is accessible for reading and below is the directory structure for F:


1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java
'Book.java' file is available under 'C' directory.

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Path;
5. import java.nio.file.Paths;
6.  
7. public class Test {
8. public static void main(String[] args) throws IOException {
9. Path file = Paths.get("F:\\A\\.\\B\\C\\D\\..\\Book.java");
10. System.out.println(file.toRealPath());
11. }
12. }

What will be the result of compiling and executing Test class?


Book.java


F:\A\B\C\Book.java
(Correct)


F:\A\.\B\C\D\..\Book.java


FileNotFoundException is thrown at runtime.


NoSuchFileException is thrown at runtime.

Explanation
toRealPath() returns the path of an existing file. It returns the path after normalizing.

Let's first normalize the path.

"F:\\A\\.\\B\\C\\D\\..\\Book.java"

can be normalized to "F:\\A\\B\\C\\D\\..\\Book.java" [Single dot is for current


directory, hence it is redundant]. 

can be further normalized to "F:\\A\\B\\C\\Book.java" [Double dot is for going to


parent directory, hence dir 'D' is removed]. 

'F:\A\B\C\Book.java' exists on the file system, hence no exception.

Question 52: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.stream.LongStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. LongStream.rangeClosed(51,75).filter(l -> l % 5 == 0)
8. .forEach(l -> System.out.print(l + " "));
9. }
10. }
What will be the result of compiling and executing Test class?

55 60 65 70 75
(Correct)


75 70 65 60

55 60 65 70

75 70 65 60 55
Explanation
There are 3 primitive streams especially to handle primitive data: DoubleStream,
IntStream and LongStream.

There are some important methods available in Stream class: 

Stream<T> filter(Predicate<? super T> predicate); 

<R> Stream<R> map(Function<? super T, ? extends R> mapper); 

void forEach(Consumer<? super T> action); 

public static<T> Stream<T> generate(Supplier<T> s){...} 

Corresponding primitive streams have similar methods working with primitive


version of Functional interfaces:

Double Stream: 

DoubleStream filter(DoublePredicate predicate); 

DoubleStream map(DoubleUnaryOperator mapper); [Operator is similar to Function] 

void forEach(DoubleConsumer action); 

public static DoubleStream generate(DoubleSupplier s){...} 

IntStream: 

IntStream filter(IntPredicate predicate); 


IntStream map(IntUnaryOperator mapper); [Operator is similar to Function] 

void forEach(IntConsumer action); 

public static IntStream generate(IntSupplier s) {...} 

LongStream: 

LongStream filter(LongPredicate predicate); 

LongStream map(LongUnaryOperator mapper); [Operator is similar to Function] 

void forEach(LongConsumer action); 

public static LongStream generate(LongSupplier s) {...} 

For exams, you will have to remember some of the important methods and their
signature.

LongStream.rangeClosed(51,75) => [51,52,53,...,75]. Both start and end are inclusive. 

filter(l -> l % 5 == 0) => [55,60,65,70,75]. filter method accepts LongPredicate and


filters the data divisible by 5. 

forEach(l -> System.out.print(l + " ")) => Prints the stream data on to the console.

Question 53: Skipped

Given code: 
1. package com.udayan.ocp;
2.  
3. class A {
4. private String str = "Hello";
5. public class B {
6. public B(String s) {
7. if(s != null)
8. str = s;
9. }
10. public void m1() {
11. System.out.println(str);
12. }
13. }
14. }
15.  
16. public class Test {
17. public static void main(String[] args) {
18. //Insert statement here
19. }
20. }
Which statement when inserted in the main(String []) method will print "Hello" in the
output?

new A().new B().m1();  


new A.B().m1();  


new A().new B(null).m1();  
(Correct)


new A().new B("hello").m1();  
Explanation
new B() will cause compilation error as no-argument constructor is not defined in
inner class B.

new A.B() is invalid syntax for creating the instance of Regular inner classes.

new A().new B("hello").m1(); is a valid syntax but it will print "hello" in the output and
not "Hello".

Question 54: Skipped

Given code of Test.java file:


1. import java.io.*;
2.  
3. public class Test {
4. public static void main(String[] args) throws IOException {
5. Console console = System.console();
6. String name = console.readLine("What's your name? ");
7. System.out.printf("You entered: %s", name);
8. }
9. }
Which of the following two statements are correct regarding above program, if it is
executed from the command line?

It compiles fine and will never cause NullPointerException at runtime

It causes compilation failure

It compiles fine but can cause NullPointerException at runtime
(Correct)

It waits indefinitely for the user input after displaying the text: What's your name?
(Correct)


It waits for 1 min for the user input and then terminates
Explanation
This code compiles successfully.

Code inside main method doesn't throw IOException or its subtype but main method
is free to declare any exception in its throws clause.

Even though program is executed from command line but System.console() may
return null, in case no console available for the underlying OS.

In that case, console.readLine(...) will cause NullPointerException at runtime.

readLine method is a blocking method, it waits for the user action. It waits until user
presses Enter key or terminates the program.

Question 55: Skipped

Given code of 4 Java files:


1. //1. MyResourceBundle.java
2. package com.udayan.ocp;
3.  
4. import java.util.ListResourceBundle;
5.  
6. public class MyResourceBundle extends ListResourceBundle {
7.     @Override
8.     protected Object[][] getContents() {
9.         Object [][] arr = {{"surprise", "SURPRISE!"}};
10.         return arr;
11.     }
12. }

1. //2. MyResourceBundle_en_CA.java
2. package com.udayan.ocp;
3.  
4. import java.util.ListResourceBundle;
5.  
6. public class MyResourceBundle_en_CA extends ListResourceBundle {
7.     @Override
8.     protected Object[][] getContents() {
9.         Object [][] arr = {{"surprise", 12.64}};
10.         return arr;
11.     }
12. }
1. //3. MyResourceBundle_fr.java
2. package com.udayan.ocp;
3.  
4. import java.util.ListResourceBundle;
5.  
6. public class MyResourceBundle_fr extends ListResourceBundle {
7.     @Override
8.     protected Object[][] getContents() {
9.         Object [][] arr = {{"surprise", 1001}};
10.         return arr;
11.     }
12. }

1. //4. Test.java
2. package com.udayan.ocp;
3.  
4. import java.util.Locale;
5. import java.util.ResourceBundle;
6.  
7. public class Test {
8.     public static void main(String[] args) {
9.         Locale.setDefault(new Locale("fr", "IT"));
10.         Locale loc = new Locale("en", "US");
11.         ResourceBundle rb =
ResourceBundle.getBundle("com.udayan.ocp.MyResourceBundle", loc);
12.         System.out.println(rb.getObject("surprise"));
13.     }
14. }
What will be the result of compiling and executing Test class?

1001
(Correct)


12.64


MissingResourceException is thrown at runtime


SURPRISE!

Explanation
The search order for matching resource bundle is:

com.udayan.ocp.MyResourceBundle_en_US [1st: Complete, en_US]. 

com.udayan.ocp.MyResourceBundle_en [2nd: Only language, en]. 

com.udayan.ocp.MyResourceBundle_fr_IT [3rd: Complete Default Locale, fr_IT]. 

com.udayan.ocp.MyResourceBundle_fr [4th: Language of Default Locale, fr]. 


com.udayan.ocp.MyResourceBundle [5th: ResourceBundle's name without language
or country]. 

If search reaches the 5th step and no matching resource bundle is found, then
MissingResourceException is thrown at runtime.

In 4th step, matching resource bundle is found and hence '1001' is printed on to the
console.

Question 56: Skipped

Given structure of EMPLOYEE table: 


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
11.  
12. try (Connection con = DriverManager.getConnection(url, user, password);
13. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
14.
ResultSet.CONCUR_READ_ONLY);
15. ResultSet rs = stmt.executeQuery(query);) {
16. rs.absolute(-2);
17. rs.relative(-1);
18. System.out.println(rs.getInt(1));
19. }
20. }
21. }
Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


104


103


101


102
(Correct)

Explanation
Given sql query returns below records:

101 John    Smith   12000   

102 Sean    Smith   15000   

103 Regina  Williams    15500   

104 Natasha George  14600   

'resultSetType' can accept 3 constants: TYPE_FORWARD_ONLY,


TYPE_SCROLL_INSENSITIVE & TYPE_SCROLL_SENSITIVE. 

'resultSetConcurrency' can accept 2 constants: CONCUR_READ_ONLY &


CONCUR_UPDATABLE.

'rs.absolute(-2);' moves the cursor to 3rd record (2nd from last). 

'rs.relative(-1);' moves the cursor to 2nd record (1 up from the current cursor
position). 
'rs.getInt(1)' returns 102.

NOTE: Column index starts with 1 and not 0.

Question 57: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path file1 = Paths.get("F:\\A\\B\\C");
9. Path file2 = Paths.get("Book.java");
10. System.out.println(file1.resolve(file2));
11. System.out.println(file1.resolveSibling(file2));
12. }
13. }
What will be the result of compiling and executing Test class?

F:\A\B\C\Book.java
F:\A\B\Book.java
(Correct)


Book.java
Book.java

Book.java
F:\A\B\Book.java

F:\A\B\C\Book.java
Book.java

F:\A\B\Book.java
F:\A\B\C\Book.java
Explanation
file1.resolve(file2) resolves file2 against file1. file1 is an absolute path and file2 is a
relative path, hence resolve method returns Path object referring to
'F:\A\B\C\Book.java'.
file1.resolveSibling(file2) resolves file2 against parent path of file1. Parent path of
file1 is: 'F:\A\B\', hence resolveSibling method returns Path object referring to
'F:\A\B\Book.java'.

Question 58: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. class Employee {
6. private String name;
7. private double salary;
8.  
9. public Employee(String name, double salary) {
10. this.name = name;
11. this.salary = salary;
12. }
13.  
14. public String getName() {
15. return name;
16. }
17.  
18. public double getSalary() {
19. return salary;
20. }
21.  
22. public void setSalary(double salary) {
23. this.salary = salary;
24. }
25.  
26. public String toString() {
27. return "{" + name + ", " + salary + "}";
28. }
29. }
30.  
31. public class Test {
32. public static void main(String[] args) {
33. List<Employee> employees = Arrays.asList(new Employee("Jack", 10000),
34. new Employee("Lucy", 12000));
35. employees.stream().peek(e -> e.setSalary(e.getSalary() + 1000))
36. .forEach(System.out::println);
37. }
38. }
What will be the result of compiling and executing Test class?

{Jack, 10000.0}
{Lucy, 12000.0}

{Jack, 11000.0}
{Lucy, 13000.0}
(Correct)


{Lucy, 13000.0}
{Jack, 11000.0}

{Lucy, 12000.0}
{Jack, 10000.0}
Explanation
employees.stream() => [{"Jack",10000.0},{"Lucy",12000.0}].

peek(e -> e.setSalary(e.getSalary() + 1000)) => [{"Jack",11000.0},{"Lucy",13000.0}].


peek(Consumer) method applies the passed lambda expression to all the elements of
the stream and returns the same elements in the stream.

forEach(System.out::println); => Prints both the elements of the stream.

Arrays.asList(...) method returns sequential List object, so order of elements remain


same.

Output is:

{Jack, 11000.0}

{Lucy, 13000.0}

NOTE: peek() method is for debugging the streams and should not be used in
production ready code.

Question 59: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. Period period = Period.ofWeeks(100);
8. System.out.println(period);
9. }
10. }
What will be the result of compiling and executing Test class?

p100w


P100W


p700d


P700D
(Correct)

Explanation
For Period.ofWeeks(int), the resulting period will be day-based, with the amount of
days equal to the number of weeks multiplied by 7.

Period is represented in terms of Year, Month and Day only and toString() method
uses upper case characters.

NOTE: Other 'of' methods of Period class are:

Period.of(int years, int months, int days) => Returns a Period instance with specified
number of years, months and days. 

Period.ofDays(int days) => Returns a Period instance with specified number of days. 

Period.ofMonths(int months) => Returns a Period instance with specified number of


months. 

Period.ofYears(int years) => Returns a Period instance with specified number of


years.

Question 60: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.ExecutionException;
4. import java.util.concurrent.ExecutorService;
5. import java.util.concurrent.Executors;
6. import java.util.concurrent.Future;
7.  
8. public class Test {
9. private static void print() {
10. System.out.println("PRINT");
11. }
12.  
13. private static Integer get() {
14. return 10;
15. }
16.  
17. public static void main(String [] args) throws InterruptedException,
18. ExecutionException {
19. ExecutorService es = Executors.newFixedThreadPool(10);
20. Future<?> future1 = es.submit(Test::print);
21. Future<?> future2 = es.submit(Test::get);
22. System.out.println(future1.get());
23. System.out.println(future2.get());
24. es.shutdown();
25. }
26. }
What will be the result of compiling and executing Test class?

null
10
PRINT

PRINT
null
10
(Correct)


null
PRINT
10

Compilation error


PRINT
10
null
Explanation
Method reference 'Test::print' is for the run() method implementation of Runnable
and 'Test::get' is for the call() method implementation of Callable. 

Future<?> is valid return type for both the method calls. get() method throws 2
checked exceptions: InterruptedException and ExecutionException, hence given code
compiles fine. 

get() method waits for task completion, hence 'PRINT' will be printed first. 
future1.get() returns null and future2.get() returns 10. 

Question 61: Skipped

Which of the following instances can be passed to invoke() method of ForkJoinPool


class? 

Select 3 options.


RecursiveAction
(Correct)


Runnable


Callable


RecursiveTask
(Correct)


ForkJoinTask
(Correct)

Explanation
ForkJoinPool class declares the invoke() method as: public <T> T
invoke(ForkJoinTask<T> task) {...}

Instance of ForkJoinTask class can be easily passed to the invoke method.

As RecursiveAction and RecursiveTask extend from ForkJoinTask, hence their


instances can also be passed to the invoke method.

Question 62: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.BiFunction;
4. import java.util.function.BiPredicate;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. BiFunction<String, String, String> func = (str1, str2) -> {
9. return (str1 + str2);
10. };
11.
12. BiPredicate<String, String> predicate = (str1, str2) -> {
13. return func.apply(str1, str2).length() > 10;
14. };
15.
16. String [] arr = {"vention", "historic", "sident", "sentation", "vious"};
17.
18. for(String str : arr) {
19. if(predicate.test("pre", str)) {
20. System.out.println(func.apply("pre", str));
21. }
22. }
23. }
24. }
What will be the result of compiling and executing Test class?

prevention
prehistoric
presentation

prevention
prehistoric
president
presentation

prevention
prehistoric
president
presentation
previous

presentation

Program terminates successfully without printing anything on to the console

prehistoric
presentation
(Correct)

Explanation
BiFunction<T, U, R> : R apply(T t, U u);

BiFunction interface accepts 3 type parameters, first 2 parameters (T,U) are passed to
apply method and 3rd type parameter is the return type of apply method.
In this case, 'BiFunction<String, String, String>' means apply method will have
declaration: 'String apply(String str1, String str2)'. Given lambda expression '(str1,
str2) -> {  return (str1 + str2); };' is the correct implementation of BiFunction<String,
String, String> interface. It simply concatenates the passed strings.

BiPredicate<T, U> : boolean test(T t, U u); 

BiPredicate interface accepts 2 type parameters and these parameters (T,U) are
passed to test method, which returns primitive boolean.

In this case, 'BiPredicate<String, String>' means test method will have declaration:
'boolean test(String s1, String s2)'. Given lambada expression '(str1, str2) -> { return
func.apply(str1, str2).length() > 10; };' is correct implementation of BiPredicate<String,
String>. Also note, lambda expression for BiPredicate uses BiFunction. This predicate
returns true if combined length of passed strings is greater than 10.

For-each loop simply iterates over the String array elements and prints the string
after pre-pending it with "pre" in case the combined length of result string is greater
than 10. "prehistoric" has 11 characters and "presentation" has 12 characters and
hence these are displayed in the output.

Question 63: Skipped

You have to create below functional interface:


1. interface Generator<T, U> {
2. U generate(T t);
3. }

Which of the following built-in interface you can use instead of above interface?


Consumer


Function
(Correct)


Supplier


Predicate
Explanation
It is always handy to remember the names and methods of four important built-in
functional interfaces:

Supplier<T> : T get();

Function<T, R> : R apply(T t);

Consumer<T> : void accept(T t);

Predicate<T> : boolean test(T t);

Rest of the built-in functional interfaces are either similar to or dependent upon
these four interfaces.

Clearly, interface Function can be used instead or defining Generator interface.

Question 64: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.Predicate;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String [] arr = {"A", "ab", "bab", "Aa", "bb", "baba", "aba", "Abab"};
8.
9. Predicate<String> p1 = s -> s.startsWith("A");
10. Predicate<String> p2 = s -> s.startsWith("a");
11. Predicate<String> p3 = s -> s.length() >= 3;
12.
13. processStringArray(arr, p1.or(p2).and(p3));
14. }
15.
16. private static void processStringArray(String [] arr,
17. Predicate<String> predicate) {
18. for(String str : arr) {
19. if(predicate.test(str)) {
20. System.out.println(str);
21. }
22. }
23. }
24. }
What will be the result of compiling and executing Test class?

aba
Abab
(Correct)


A
ab
Aa
aba
Abab

Abab


bab
baba
aba
Abab
Explanation
"or" and "and" method of Predicate interface works just like short-circuit || and &&
operators.

p1.or(p2) will return {"A", "ab", "Aa", "aba", "Abab"} and after that and method will
retrieve strings of length greater than or equal to 3, this means you would get {"aba",
"Abab"} as the final result.

Question 65: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalTime t1 = LocalTime.now();
8. LocalDateTime t2 = LocalDateTime.now();
9. System.out.println(Duration.between(t1, t2));
10. }
11. }
What will be the result of compiling and executing Test class?

Program terminates successfully after displaying the output
(Correct)


Compilation error


Runtime Exception

Explanation
Signature of between method defined in Duration class is: 'Duration
between(Temporal startInclusive, Temporal endExclusive)'.

As both LocalTime and LocalDateTime implement 'Temporal' interface, hence there is


no compilation error.

If the Temporal objects are of different types as in this case, calculation is based on
1st argument and 2nd argument is converted to the type of 1st argument. It is easy
to convert LocalDateTime to LocalTime.

Program executes successfully and terminates successfully after displaying the


Duration object on to the console.

Question 66: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class Caller implements Callable<Void> {
6. String str;
7.  
8. public Caller(String s) {
9. this.str = s;
10. }
11.  
12. public Void call() throws Exception {
13. System.out.println(str.toUpperCase());
14. return null;
15. }
16. }
17.  
18. public class Test {
19. public static void main(String[] args) throws InterruptedException,
20. ExecutionException {
21. ExecutorService es = Executors.newSingleThreadExecutor();
22. Future<Void> future = es.submit(new Caller("Call"));
23. System.out.println(future.get());
24. }
25. }
What will be the result of compiling and executing Test class? 

The program terminates after printing:
CALL
null

The program doesn't terminate but prints following:
CALL
null
(Correct)


The program doesn't terminate but prints following:
null
null

The program doesn't terminate but prints following:
CALL
CALL
Explanation
Callable is of Void type and call() method returns null.

'es.submit(new Caller("Call"));' creates a Caller object and invokes the call method.
This method prints 'CALL' on to the console and returns null.

'System.out.println(future.get());' prints 'null' on to the console.

As 'es.shutdown();' is not invoked, hence program doesn't terminate.

Question 67: Skipped

Given structure of EMPLOYEE table:


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))

EMPLOYEE table contains below records:

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws Exception {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
13. ) {
14. ResultSet rs = stmt.executeQuery(query);
15. rs.moveToInsertRow();
16. rs.updateInt(1, 105);
17. rs.updateString(2, "Chris");
18. rs.updateString(3, "Lee");
19. rs.updateDouble(4, 16000);
20. rs.refreshRow(); //Line n1
21. rs.insertRow(); //Line n2
22. rs.last();
23. System.out.println(rs.getInt(1)); //Line n3
24. }
25. }
26. }

Also assume:

URL is correct and db credentials are: root/password.

SQL query is correct and valid.

The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


An exception is raised by Line n1
(Correct)


105

An exception is raised by Line n3

An exception is raised by Line n2

104
Explanation
Given query returns below records:
101 John    Smith   12000   

102 Sean    Smith   15000   

103 Regina  Williams    15500   

104 Natasha George  14600   

'rs.moveToInsertRow();' It moves the cursor to the insert row.

Please note, If the cursor is at insert row and refreshRow() or updateRow() or


deleteRow() method is called, then SQLException is thrown.

Hence, in this case an exception is raised by Line n1.

Question 68: Skipped

Which of the following will always represent Locale object for English in US?

Select 2 options.


Locale l2 = new Locale(Locale.US);  


Locale l4 = Locale.getDefault();  


Locale l1 = Locale.US;  
(Correct)


Locale l5 = new Locale("en", "US");  
(Correct)


Locale l3 = Locale.getInstance("us");  
Explanation
Locale.US; => Locale.US represents a Locale instance for en_US. 

new Locale(Locale.US); => There is no Locale constructor which accepts a Locale


object. 
Locale.getInstance("us"); => There is no getInstance method, which accepts single
String argument. Famous getInstance method has signature: 'getInstance(String
language, String country, String variant)'. 

Locale.getDefault(); => It will not always return Locale for en_US, it depends on the
default locale of JVM.

new Locale("en", "US"); => This definitely creates a Locale instance for en_US. 

Question 69: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Stream<Double> stream = Arrays.asList(1.8, 2.2, 3.5).stream();
9.  
10. /*INSERT*/
11. }
12. }

Which of the following options can replace /*INSERT*/ such that on executing Test
class, all the stream elements are added and result is printed on to the console?

Select 2 options.


System.out.println(stream.sum());  


System.out.println(stream.reduce(0, (d1, d2) -> d1 + d2));  


System.out.println(stream.reduce(0, Double::sum));  


System.out.println(stream.reduce(0.0, Double::sum));  
(Correct)


System.out.println(stream.reduce(0.0, (d1, d2) -> d1 + d2));  
(Correct)

Explanation
'stream.reduce(0.0, (d1, d2) -> d1 + d2)' and 'stream.reduce(0.0, Double::sum)' are
exactly same and adds all the stream contents.
stream.sum() causes compilation error as sum() method is declared only in primitive
streams (IntStream, LongStream and DoubleStream) but not in generic stream,
Stream<T>.

reduce method parameters are (Double, BinaryOperator).

0 (int literal) cannot be converted to Double and hence compilation error for
'stream.reduce(0, (d1, d2) -> d1 + d2)' and 'stream.reduce(0, Double::sum)'.

You can easily verify this by writing below code:

public class Test {


public static void main(String[] args) {
print(0); //Compilation error as int can't be converted to Double
}

private static void print(Double d) {


System.out.println(d);
}
}

Question 70: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Player {
4. String name;
5. int age;
6.  
7. Player() {
8. this.name = "Sachin";
9. this.age = 44;
10. }
11.  
12. public Object toString() {
13. return name + ", " + age;
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. System.out.println(new Player());
20. }
21. }
What will be the result of compiling and executing Test class?

Sachin, 44


Compilation error
(Correct)


null, 0


Text containing @ symbol

Explanation
The toString() method in Object class has below definition:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

class Player doesn't override it correctly, return type should be String and not Object.

Question 71: Skipped

Performance with parallel stream is always better than sequential streams.


true


false
(Correct)

Explanation
Parallel streams internally use fork/join framework only, so there is always an
overhead of splitting the tasks and joining the results.   

Parallel streams improves performance for streams with large number of elements,
easily splittable into independent operations and computations are complex.

Question 72: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class Adder extends RecursiveAction {
6. private int from;
7. private int to;
8. int total = 0;
9.  
10. Adder(int from, int to) {
11. this.from = from;
12. this.to = to;
13. }
14.  
15. @Override
16. protected void compute() {
17. if ((to - from) <= 4) {
18. int sum = 0;
19. for(int i = from; i <= to; i++) {
20. sum += i;
21. }
22. total+=sum;
23. } else {
24. int mid = (from + to) / 2;
25. Adder first = new Adder(from, mid);
26. Adder second = new Adder(mid + 1, to);
27. invokeAll(first, second);
28. }
29. }
30. }
31.  
32. public class Test {
33. public static void main(String[] args) {
34. Adder adder = new Adder(1, 20); //Line 34
35. ForkJoinPool pool = new ForkJoinPool(4);
36. pool.invoke(adder);
37. System.out.println(adder.total);
38. }
39. }
What will be the result of compiling and executing Test class?

None of the other options.


It can print any number between 0 and 210.


It will print 0 on to the console.
(Correct)


It will print 210 on to the console.

Explanation
RecursiveAction class has an abstract method 'void compute()' and Adder class
correctly overrides it. 
new Adder(1, 20); instantiate an Adder object with from = 1, to = 20 and total = 0. 

20 - 1 is not less than or equal to 4 hence else block will create multiple Adder
objects, and compute() method will be invoked on these objects. More Adder objects
will be created further.

Statement 'total+=sum;' will update the total filed of these objects but not the adder
object created at Line 34. So when 'System.out.println(adder.total);' is executed, it
prints 0 on to the console.

To get the expected output (which is sum of numbers from 1 to 20), add below code
as the last statement in the else block so that total field of Adder object created at
Line 34 is updated successfully:

total = first.total + second.total;

Question 73: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. NavigableSet<String> set = new TreeSet<>(Arrays.asList("red", "green",
8. "blue", "gray"));
9. System.out.println(set.ceiling("gray"));
10. System.out.println(set.floor("gray"));
11. System.out.println(set.higher("gray"));
12. System.out.println(set.lower("gray"));
13. }
14. }
What will be the result of compiling and executing Test class?

gray
gray
gray
gray

gray
gray
green
blue
(Correct)


green
blue
green
blue

green
blue
gray
gray
Explanation
new TreeSet<>(Arrays.asList("red", "green", "blue", "gray")); => [blue, gray, green,
red]. 

set.ceiling("gray") => Returns the least value greater than or equal to the given value,
'gray'. 

set.floor("gray") => Returns the greatest value less than or equal to the given value,
'gray'. 

set.higher("gray") => Returns the least value strictly greater than the given value,
'green'. 

set.lower("gray") => Returns the greatest value strictly less than the given value,
'blue'. 

Question 74: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.time.LocalDateTime;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDateTime dt = LocalDateTime.parse("2018-03-16t10:15:30.22");
8. System.out.println(dt.toLocalDate() + dt.toLocalTime());
9. }
10. }
What will be the result of compiling and executing Test class?

Runtime exception


2018-03-1610:15:30.220

2018-03-1610:15:30.22


Compilation error
(Correct)

Explanation
dt.toLocalDate() returns an instance of LocalDate and dt.toLocalTime() returns an
instance of LocalTime.

But '+' operator is not overloaded for LocalDate and LocalTime objects OR 2
LocalDate objects OR 2 LocalTime objects OR in general for 2 Java Objects. 

It would work if one of the operand is of String type.

Hence 'dt.toLocalDate() + " " + dt.toLocalTime()' doesn't cause any compilation error
as '+' operator is Left to Right associative. 

dt.toLocalDate() + " " + dt.toLocalTime()

= (dt.toLocalDate() + " ") + dt.toLocalTime()

= "2018-03-16 " + dt.toLocalTime()

= "2018-03-16 10:15:30.220"

Question 75: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Locale;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Locale loc = Locale.ENGLISH;
8. loc.setCountry("en");
9. loc.setCountry("CA");
10.  
11. System.out.println(loc.getDisplayCountry());
12. }
13. }
'CA' is the country code for 'Canada'.

What will be the result of compiling and executing Test class?


Canada


Compilation error
(Correct)


No text is displayed in the output


United States


English

Explanation
There are no setCountry(...) and setLanguage(...) methods defined in Locale class.

Question 76: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List list = new ArrayList<String>();
9. list.add(1);
10. list.add("2");
11. list.forEach(System.out::print);
12. }
13. }
Which of the following are correct?

Select 2 options.


Exception is thrown at runtime

12 is displayed on to the console
(Correct)


Code compiles with some warnings
(Correct)


Code compiles without any errors and warnings
Explanation
Compiler warning for unchecked call to add and forEach.

list can store all objects and when each element is passed to System.out.print()
method, toString() method for passed element is invoked.

Both Integer and String class overrides toString() method and hence 12 is printed on
to the console.

Question 77: Skipped

Can all streams be converted to parallel stream?


Yes
(Correct)


No

Explanation
All streams in Java implements BaseStream interface and this interface has parallel()
and sequential() methods.

Hence all streams can either be parallel or sequential.

Question 78: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. interface Printer {
4. default void print() {
5. System.out.println("Printer");
6. }
7. }
8.  
9. @FunctionalInterface
10. interface ThreeDPrinter extends Printer {
11. @Override
12. void print();
13. }
14.  
15. public class Test {
16. public static void main(String[] args) {
17. ThreeDPrinter p = () -> System.out.println("3DPrinter");
18. p.print();
19. }
20. }
What will be the result of compiling and executing Test class?

Printer


Compilation error in ThreeDPrinter class


3DPrinter
(Correct)


Compilation error in Test class

Explanation
An interface can override the default method of parent interface and declare it as
abstract as well.

ThreeDPrinter is a functional interface as it has one non-overriding abstract method.


No issues with ThreeDPrinter interface. 

Lambda syntax is correct and p.print() method invokes


'System.out.println("3DPrinter");' of lambda expression, hence '3DPrinter' is printed in
the output.

Question 79: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4. import java.util.function.Predicate;
5. import java.util.stream.Stream;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Stream<String> stream = Stream.of("and", "Or", "not", "Equals", "unary",
"binary");
10. Optional<String> optional = stream.filter(
11.
((Predicate<String>)Test::isFirstCharVowel).negate()).findFirst();
12. System.out.println(optional.get());
13. }
14.  
15. private static boolean isFirstCharVowel(String str) {
16. str = str.substring(0, 1).toUpperCase();
17. switch(str) {
18. case "A":
19. case "E":
20. case "I":
21. case "O":
22. case "U":
23. return true;
24. }
25. return false;
26. }
27. }
What will be the result of compiling and executing Test class?

and


not
(Correct)


binary


Or

Explanation
stream => ["and", "Or", "not", "Equals", "unary", "binary"]. 

Test::isFirstCharVowel is the predicate, to invoke negate() method, it needs to be


type-casted to 'Predicate<String>'. 

stream.filter(((Predicate<String>)Test::isFirstCharVowel).negate()) => ["not",


"binary"]. 

findFirst() => Optional<String> object containing "not".

optional.get() => "not".

Question 80: Skipped

Below files are available for your project:


1. //1. ResourceBundle.properties
2. k1=1
3. k2=2

1. //2. ResourceBundle_EN.properties
2. k3=EN3
3. k4=EN4

1. //3. ResourceBundle_US.properties
2. k2=US2
3. k3=US3

1. //4. Test.java
2. package com.udayan.ocp;
3.  
4. import java.util.Enumeration;
5. import java.util.Locale;
6. import java.util.ResourceBundle;
7.  
8. public class Test {
9. public static void main(String[] args) {
10. Locale loc = Locale.US;
11. ResourceBundle bundle = ResourceBundle.getBundle("ResourceBundle", loc);
12. Enumeration<String> enumeration = bundle.getKeys();
13. while (enumeration.hasMoreElements()) {
14. String key = enumeration.nextElement();
15. String val = bundle.getString(key);
16. System.out.println(key + "=" + val);
17. }
18. }
19. }
Assume that all the *.properties files are included in the CLASSPATH. What will be the
output of compiling and executing Test class?

k1=1
k2=2
k3=EN3
k4=EN4

k2=US2
k3=US3
k4=EN4
k1=1

k1=1
k2=2
k3=EN3
k4=EN4
k2=US2
k3=US3

k3=EN3
k4=EN4
k1=1
k2=2
(Correct)


k2=US2
k3=US3
k3=EN3
k4=EN4
k1=1
k2=2
Explanation
Locale.US represents a Locale instance for en_US. As locale is en_US, hence given files
will be searched in below order:

ResourceBundle_en_US.properties (Not available)

ResourceBundle_en.properties (Available and works even in the file name "EN" is in


upper-case, but convention is to use lowercase of language code)

ResourceBundle.properties (Available)

Note that 'ResourceBundle_US.properties' will not be considered.

Hence bundle.getKeys(); returns an Enumeration<String> instance containing (k3,k4)


from 'ResourceBundle_EN.properties' file and (k1,k2) from 'ResouceBundle.properties'
file.

You can iterate over Enumeration using hasMoreElements() and nextElement()


methods.

Iteration logic prints key-value pair in the order of Enumeration elements (k3, k4, k1,
k2). Hence the output will be:

k3=EN3

k4=EN4

k1=1
k2=2

Question 81: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream<StringBuilder> stream = Stream.of();
8. stream.map(s -> s.reverse()).forEach(System.out::println);
9. }
10. }
What will be the result of compiling and executing Test class?

ClassCastException is thrown at runtime


NullPointerException is thrown at runtime


Compilation error


Program executes successfully but nothing is printed on to the console
(Correct)

Explanation
Stream.of() returns blank stream. As Type of stream is specified, stream is of
'Stream<StringBuilder>', each element of the stream is considered to be of
'StringBuilder' type.

map method in this case accepts 'Function<? super StringBuilder, ? extends


StringBuilder>'.

In Lambda expression 's -> s.reverse()', s is of StringBuilder type and hence no


compilation error.

As stream is blank, hence map and forEach methods are not executed even once.
Program executes fine but nothing is printed on to the console.

Question 82: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. class Foo {
4. static { //static initialization block
5. System.out.print(1);
6. }
7. class Bar {
8. static { //static initialization block
9. System.out.print(2);
10. }
11. }
12. }
13.  
14. public class Test {
15. public static void main(String [] args) {
16. new Foo().new Bar();
17. }
18. }

12


Compilation error
(Correct)


21


Exception is thrown at runtime

Explanation
Regular inner class cannot define anything static, except static final variables.

In this case, static initialization block inside inner class Bar is not allowed.

Question 83: Skipped

Can an anonymous inner class implement multiple interfaces?


Yes


No
(Correct)

Explanation
Unlike other inner classes, an anonymous inner class can either extend from one class
or can implement one interface.
It cannot extend and implement at the same time and it cannot implement multiple
interfaces.

Question 84: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. class Student implements Serializable {
6. private transient String name;
7. private int age;
8.  
9. Student(String name, int age) {
10. this.name = name;
11. this.age = age;
12. }
13.  
14. public String getName() {
15. return name;
16. }
17.  
18. public int getAge() {
19. return age;
20. }
21.  
22. public void setName(String name) {
23. this.name = name;
24. }
25.  
26. public void setAge(int age) {
27. this.age = age;
28. }
29. }
30.  
31. public class Test {
32. public static void main(String[] args) throws IOException,
33. ClassNotFoundException {
34. Student stud = new Student("John", 20);
35.  
36. try( ObjectOutputStream oos = new ObjectOutputStream(
37. new FileOutputStream("C:\\Student.dat")) ){
38. oos.writeObject(stud);
39. }
40.  
41. try( ObjectInputStream ois = new ObjectInputStream(
42. new FileInputStream("C:\\Student.dat")) ){
43. stud = (Student)ois.readObject();
44. System.out.printf("%s : %d", stud.getName(), stud.getAge());
45. }
46. }
47. }
There is full permission to list/create/delete files and directories in C:.

What will be the result of compiling and executing Test class?


John : 20

Compilation error


Runtime Exception


null : 20
(Correct)


null : 0

Explanation
Student class implements Serializable, hence objects of Student class can be
serialized using ObjectOutputStream.

State of transient and static fields are not persisted.

While de-serializing, transient fields are initialized to default values (null for reference
type and respective Zeros for primitive types) and static fields refer to current value.

In this case, name is transient, so it is not persisted. On de-serializing, null is printed


for name and 20 is printed for age.

Question 85: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.io.FileNotFoundException;
4. import java.io.IOException;
5.  
6. abstract class Super {
7. public abstract void m1() throws IOException;
8. }
9.  
10. class Sub extends Super {
11. @Override
12. public void m1() throws IOException {
13. throw new FileNotFoundException();
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. Super s = new Sub();
20. try {
21. s.m1();
22. } catch (FileNotFoundException e) {
23. System.out.print("X");
24. } catch (IOException e) {
25. System.out.print("Y");
26. } finally {
27. System.out.print("Z");
28. }
29. }
30. }
What will be the result of compiling and executing Test class?

XZ
(Correct)


XYZ


Compilation Error


YZ

Explanation
Even though method m1() declares to throw IOException but at runtime an instance
of FileNotFoundException is thrown.

A catch handler for FileNotFoundException is available and hence X is printed on to


the console.

After that finally block is executed, which prints Z to the console.

Question 86: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Base {
4. public void m1() throws NullPointerException {
5. System.out.println("Base: m1()");
6. }
7. }
8.  
9. class Derived extends Base {
10. public void m1() throws RuntimeException {
11. System.out.println("Derived: m1()");
12. }
13. }
14.  
15. public class Test {
16. public static void main(String[] args) {
17. Base obj = new Derived();
18. obj.m1();
19. }
20. }
What will be the result of compiling and executing Test class?

Base: m1()


Compilation error in Derived class


Derived: m1()
(Correct)


Compilation error in Test class

Explanation
NullPointerException extends RuntimeException, but there are no overriding rules
related to unchecked exceptions.

So, method m1() in Derived class correctly overrides Base class method.

Rest is simple polymorphism. obj refers to an instance of Derived class and hence
obj.m1(); invokes method m1() of Derived class, which prints "Derived: m1()" to the
console.

Question 87: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. int i = 2000;
8. Deque<Integer> deque = new ArrayDeque<>();
9. deque.add(1000);
10. deque.add(i);
11. deque.add(3000);
12.
13. /*INSERT*/
14. }
15. }
Which of the following two statements, if used to replace /*INSERT*/, will print
following on to the console:
1000
2000
3000

deque.forEach(i -> System.out.println(i));  


deque.forEach(System.out::println);  
(Correct)


deque.forEach(System.out::print);  


deque.forEach(s -> System.out.println(s));  
(Correct)

Explanation
Iterator<T> interface has forEach(Consumer) method. As Consumer is a Functional
Interface, hence a lambda expression or method reference syntax can be passed as
argument to forEach() method. 

deque.forEach(System.out::print); => This will print 100020003000 without any


newline character in between. 

deque.forEach(System.out::println); => This prints desired output

deque.forEach(i -> System.out.println(i)); => Causes compilation failure as lambda


expression variable 'i' conflicts with local variable.

deque.forEach(s -> System.out.println(s)); => Prints desired output.

NOTE: 'System.out::print' is a method reference syntax corresponding to lambda


expression 's -> System.out.println(s)'.

Question 88: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.function.BinaryOperator;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. List<Boolean> list = Arrays.asList(false, new Boolean(null), new
Boolean("1"), new Boolean("0"));
10. BinaryOperator<Boolean> operator = (b1, b2) -> b1 || b2;
11. System.out.println(list.stream().reduce(false, operator));
12. }
13. }
What will be the result of compiling and executing Test class?

Compilation error

false
(Correct)


NullPointerException is thrown at runtime

true
Explanation
Constructor of Boolean class accepts String argument.

If passed argument is null, then Boolean object for 'false' is created.

If passed argument is non-null and equals to "true" in case-insensitive manner, then


Boolean object for 'true' is created otherwise Boolean object for 'false' is created.

So list contains 4 elements and all are Boolean objects for false.

As, BinaryOperator<T> extends BiFunction<T,T,T> so in this case signature of apply


method will be: Boolean apply(Boolean, Boolean). Given lambda expression correctly
implements the apply method.

To understand, 'stream.reduce(false, operator)' can be written as:

Boolean result = false;


for (Boolean element : stream) {
result = operator.apply(result, element);
}
return result;

Above code is just for understanding purpose, you can't iterate a stream using given
loop.
As 1st argument of reduce method (also known as identity) is set to false and all the
4 stream elements are also false, hence list.stream().reduce(false, operator) will return
false.

So, in this case false will be printed on to the console.

If you change identity to true, then statement


'System.out.println(list.stream().reduce(true, operator));' will print true.

Question 89: Skipped

Database URL starts with ________.


db:


database:


jdbc:
(Correct)


url:

Explanation
database url has the form: protocol:subprotocol:subname.

protocol is always 'jdbc'. 

subprotocol is database specific, for MySQL it is 'mysql'. 

subname contains database details, such as '//localhost:3306/ocp'.

Complete database url form MySQL db is: 'jdbc:mysql://localhost:3306/ocp'. So it


always starts with 'jdbc:'.
Question 90: Skipped

Below is the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Outer {
4. private static int i = 10;
5. private int j = 20;
6.
7. static class Inner {
8. void add() {
9. System.out.println(i + j);
10. }
11. }
12. }
13.  
14. public class Test {
15. public static void main(String[] args) {
16. Outer.Inner inner = new Outer.Inner();
17. inner.add();
18. }
19. }
What will be the result of compiling and executing Test class?

30


Compilation error in Inner class code
(Correct)


Exception is thrown at runtime


Compilation error in Test class code

Explanation
static nested class cannot access non-static member of the Outer class using static
reference.

Hence usage of variable j in Inner class causes compilation error.


Practice Test 5 - Results

 Return to review

Attempt 1
All knowledge areas

All questions

Question 1: Skipped

Below represents ZonedDateTime data:


1. 2018-02-01T10:30+05:30[Asia/Kolkata]
2. 2018-01-31T21:00-08:00[America/Los_Angeles]
Do above times represent same instance of time?

No


Yes
(Correct)

Explanation
To know whether 2 instances represent same time or not, convert the time to GMT
time by subtracting the offset.
2018-02-01T10:30 -(+05:30) = 2018-02-01T05:00 GMT. 

and

2018-01-31T21:00 -(-08:00) = 2018-02-01T05:00 GMT.

So both represents same instance of time.

Question 2: Skipped

F: is accessible for reading/writing and below is the directory structure for F:


1. F:.
2. └───A
3. └───B
4. Book.java
Book.java is a text file.
            
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.nio.file.*;
6.  
7. public class Test {
8. public static void main(String[] args) throws IOException{
9. Path src = Paths.get("F:\\A\\B\\Book.java");
10. try(BufferedReader reader = Files.newBufferedReader(src))
11. {
12. String str = null;
13. while((str = reader.readLine()) != null) {
14. System.out.println(str);
15. }
16. }
17. }
18. }

What will be the result of compiling and executing Test class?


Contents of Book.java are printed on to the console.
(Correct)


An exception is thrown at runtime.


Compilation error

Explanation
Files class has methods such as newInputStream(...), newOutputStream(...),
newBufferedReader(...) and newBufferedWriter(...) for files reading and writing.

Given code doesn't cause any compilation error.

As Book.java is a text file and accessible, hence its contents are printed on to the
console.

Question 3: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Player {
4. String name;
5. int age;
6.  
7. void Player() {
8. this.name = "Virat";
9. this.age = 29;
10. }
11.  
12. public String toString() {
13. return "Name: " + this.name + ", Age: " + this.age;
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. System.out.println(new Player());
20. }
21. }
What will be the result of compiling and executing Test class?

Name: Virat, Age: 29


Compilation error


An exception is thrown at runtime


Name: null, Age: 0
(Correct)

Explanation
Methods can have same name as the class. Player() is method and not constructor of
the class, note the void return type of this method.
As no constructors are provided in the Player class, java compiler adds default no-
argument constructor. That is why "new Player()" doesn't cause any compilation
error.

Default values are assigned to instance variables, hence null is assigned to name and
0 is assigned to age. 

In the output, Name: null, Age: 0 is displayed.

Question 4: Skipped

Does below code compile successfully?


1. class A{}
2. interface M{}
3. interface N{}
4.  
5. class B extends A {}
6. class C extends A implements M {}
7. class D extends A implements M, N {}
8.  
9. class Generic<T extends M & N & A> {}


No
(Correct)


Yes

Explanation
If multiple bounds are available and one of the bounds is a class, then it must be
specified first. 

class Generic<T extends M & N & A> {} => A is specified at last and hence
compilation error.

Question 5: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws IOException {
7. File f1 = new File("F:\\f1.txt");
8. FileWriter fw = new FileWriter("F:\\f2.txt");
9. PrintWriter pw = new PrintWriter("F:\\f3.txt");
10. }
11. }
F: is accessible for reading/writing and currently doesn't contain any files/directories. 

On executing Test class, how many physical files will be created on the disc?


3


2
(Correct)


1


0

Explanation
Initially F:\ is blank.

new File("F:\\f1.txt"); => It just creates a Java object containing abstract path
'F:\f1.txt'.  NO physical file is created on the disc.

new FileWriter("F:\\f2.txt"); => It creates 'f2.txt' under F:.

new PrintWriter("F:\\f3.txt"); => It creates 'f3.txt' under F:.

NOTE: Constructors of FileWriter and PrintWriter can create a new file but not
directory.

Question 6: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. @FunctionalInterface
4. interface I7 {
5. void print();
6. }
7.  
8. public class Test {
9. String var = "Lambda";
10. class Inner {
11. int var = 1000;
12. I7 obj = () -> System.out.println(this.var);
13. }
14.
15. public static void main(String[] args) {
16. Inner inner = new Test().new Inner();
17. inner.obj.print();
18. }
19. }

Lambda


Compilation Error


None of the other options


1000
(Correct)

Explanation
Lambda expression is written inside Inner class, so this keyword in lambda expression
refers to the instance of Inner class.

Hence, System.out.println(this.var); prints 1000.

Question 7: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. File dir = new File("F:" + System.getProperty("path.separator") + "A");
8. dir.mkdir();
9. }
10. }
F: is accessible for reading/writing and currently doesn't contain any files/directories. 

Will above code create directory 'A' inside F:?


No
(Correct)

Yes

Explanation
System.getProperty("path.separator") returns the path-separator, semicolon(;) on
Windows system and colon(:) on Linux system.

So, above code will definitely not create directory named, 'A'. On windows system, it
created directory with name ';A'.

You can get file separator by using below code:

System.getProperty("file.separator")  OR File.separator.

Question 8: Skipped

Below is the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class A {
4. static class B {
5.
6. }
7. }
8.  
9. public class Test {
10. /*INSERT*/
11. }
Which of the following options can replace /*INSERT*/ such that there are no
compilation errors?

B obj = new B();  


A.B obj = new A.B();  
(Correct)


B obj = new A.B();  


A.B obj = new A().new B();  
Explanation
In this case, you have to write code outside class A. B is a static nested class and
outside class A it is referred by A.B.
Instance of class B can be created by 'new A.B();'.

Question 9: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.function.BiFunction;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. BiFunction<String, String, String> func = (s1, s2) -> s2.concat(s1).trim();
8. System.out.println(func.apply(" CD", " AB"));
9. }
10. }

What will be the result of compiling and executing Test class?


CDAB


CD AB


AB CD
(Correct)


ABCD

Explanation
BiFunction<String, String, String> interface's apply method signature will be: String
apply(String str1, String str2). 

NOTE: Lambda expression's body is: 's2.concat(s1)' and not 's1.concat(s2)'. trim()
method trims leading and trailing white spaces and not the white spaces in between.

func.apply(" CD", " AB")

= " AB".concat(" CD").trim();

= " AB CD".trim(); = "AB CD"

Question 10: Skipped

For the given code:


1. package com.udayan.ocp;
2.  
3. interface Printable {
4. void print(String msg);
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Printable obj = new Printable() {
10. public void print(String msg) {
11. System.out.println(msg);
12. }
13. };
14. obj.print("Welcome!");
15. }
16. }
Which of the following options successfully replace anonymous inner class code with
lambda expression code?

Select 5 options.


Printable obj = (msg) -> {System.out.println(msg);};  
(Correct)


Printable obj = msg -> System.out.println(msg);  
(Correct)


Printable obj = y - > System.out.println(y);  


Printable obj = (msg) -> System.out.println(msg);  
(Correct)


Printable obj = x -> System.out.println(x);  
(Correct)


Printable obj = (String msg) -> {System.out.println(msg);};  
(Correct)

Explanation
print(String) method accepts parameter of String type, so left side of lambda
expression should specify one parameter, then arrow operator and right side of
lambda expression should specify the body. 

(String msg) -> {System.out.println(msg);}; => Correct. 


(msg) -> {System.out.println(msg);}; => Correct, type of variable can be removed
from left side. Java compiler handles it using type inference. 

(msg) -> System.out.println(msg); => Correct, if there is only one statement in the
right side then semicolon inside the body, curly brackets and return statement(if
available) can be removed. 

msg -> System.out.println(msg); => Correct, if there is only one parameter in left
part, then round brackets can be removed. 

x -> System.out.println(x); => Correct, any valid java identifier can be used in lambda
expression. 

y - > System.out.println(y); => Compilation error as there should not be any space
between - and > of arrow operator.

Question 11: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. NavigableMap<Integer, String> map = new TreeMap<>();
8. map.put(25, "Pune");
9. map.put(32, "Mumbai");
10. map.put(11, "Sri Nagar");
11. map.put(39, "Chennai");
12.  
13. System.out.println(map.headMap(25));
14. System.out.println(map.tailMap(25));
15. }
16. }
What will be the result of compiling and executing Test class?

{11=Sri Nagar, 25=Pune}
{32=Mumbai, 39=Chennai}

{11=Sri Nagar}
{25=Pune, 32=Mumbai, 39=Chennai}
(Correct)


{11=Sri Nagar, 25=Pune}
{25=Pune, 32=Mumbai, 39=Chennai}

{11=Sri Nagar}
{32=Mumbai, 39=Chennai}
Explanation
If you don't use 2nd parameter for headMap() and tailMap() methods to indicate
whether keys are inclusive or exclusive,

then by default 'toKey' used in headMap() method is exclusive and 'fromKey' used in
tailMap() method is inclusive.

You can confirm this by checking the definition of headMap() and tailMap() methods
in TreeMap class.

Methods defined in TreeMap class:

public SortedMap<K,V> headMap(K toKey) {


return headMap(toKey, false);
}

public SortedMap<K,V> tailMap(K fromKey) {


return tailMap(fromKey, true);
}

Question 12: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. class A {
4. A() {
5. System.out.print(1);
6. }
7. class B {
8. B() {
9. System.out.print(2);
10. }
11. }
12. }
13.  
14. public class Test {
15. public static void main(String [] args) {
16. B obj = new A().new B();
17. }
18. }

Compilation error
(Correct)


21


12


2

Explanation
To refer to inner class name from outside the top level class, use the syntax:
outer_class.inner_class.

In this case, correct syntax to refer B from Test class is: A.B and not B.

Question 13: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Scanner;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. System.out.print("Enter some text: ");
8. try(Scanner scan = new Scanner(System.in)) {
9. String s = scan.nextLine();
10. System.out.println(s);
11. scan.close();
12. scan.nextLine();
13. }
14. }
15. }
What will be the result of compiling and executing Test class?

User input is: HELLO


On execution program terminates successfully after printing 'HELLO' on to the
console


Compilation error


Runtime Exception
(Correct)

Explanation
Even though Scanner is created in try-with-resources block, calling close() method
explicitly doesn't cause any problem.

Scanner class allows to invoke close() method multiple times.

But once Scanner object is closed, other search operations should not be invoked. If
invoked on closed scanner, IllegalStateException is thrown.

Question 14: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. class Student {
6. private String name;
7. private int age;
8.  
9. Student(String name, int age) {
10. this.name = name;
11. this.age = age;
12. }
13.  
14. public String toString() {
15. return "Student[" + name + ", " + age + "]";
16. }
17.  
18. public boolean equals(Object obj) {
19. if(obj instanceof Student) {
20. Student stud = (Student)obj;
21. return this.name.equals(stud.name) && this.age == stud.age;
22. }
23. return false;
24. }
25. }
26.  
27. public class Test {
28. public static void main(String[] args) {
29. Set<Student> students = new HashSet<>();
30. students.add(new Student("James", 20));
31. students.add(new Student("James", 20));
32. students.add(new Student("James", 22));
33.  
34. System.out.println(students.size());
35. }
36. }
What will be the result of compiling and executing Test class?

3
(Correct)


Runtime Exception


2

Explanation
HashSet makes use of hashCode to find out the correct bucket, it then makes use of
equals(Object) method to find out duplicate objects.

Student class correctly overrides equals(Object) method but it doesn't override


hashCode() method. This means you get different hashCode for different objects.

HashSet in this case cannot find out duplicate Student objects and 3 Student objects
are added to the Set.

System.out.println(students.size()); => Prints 3 on to the console.

To avoid duplicate in the given Set, override hashCode() method in Student class:

public int hashCode() {


return name.hashCode() + age;
}

Question 15: Skipped

F: is accessible for reading/writing and currently doesn't contain any directories. 


1. F:.
2. └───A
3. └───B
4. └───C

Which of the code snippet allows to create below directory structure under F:?


1. File file = new File("F:\\A\\B\\C");
2. file.createNewDirectory();

1. File file = new File("F:\\A\\B\\C");
2. file.createNewDirectories();

1. File file = new File("F:\\A\\B\\C");
2. file.mkdir();


1. File file = new File("F:\\A\\B\\C");
2. file.mkdirs();
(Correct)

Explanation
createNewDirectory() and createNewDirectories() are not available in java.io.File class.

createNewFile() is for creating new file but not directory.

mkdir() is for creating just 1 directory, in this case abstract path is: 'F:\A\B\C', for
mkdir() to create directory, 'F:\A\B\' path must exist.

As per question F: doesn't contain any directories, hence mkdir() doesn't create any
directory and returns false.

mkdirs() creates all the directories (if not available), specified in the given abstract
path and returns true.

Question 16: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String str1 = Stream.iterate(1, i -> i + 1).limit(10)
8. .reduce("", (i, s) -> i + s, (s1, s2) -> s1 + s2);
9. String str2 = Stream.iterate(1, i -> i + 1).limit(10).parallel()
10. .reduce("", (i, s) -> i + s, (s1, s2) -> s1 + s2);
11. System.out.println(str1.equals(str2));
12. }
13. }
What will be the result of compiling and executing Test class?

Output cannot be predicted

It will always print true
(Correct)


It will always print false
Explanation
reduce method in Stream class is declared as: <U> U reduce(U identity,
BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)

By checking the reduce method 'reduce("", (i, s) -> i + s, (s1, s2) -> s1 + s2)', we can
say that:

Identity is String type, accumulator is BiFunction<String, ? super Integer, String>


type, combiner is BinaryOperator<String> type.

To get consistent output, there are requirements for reduce method arguments:

1. The identity value must be an identity for the combiner function. This means that
for all u, combiner(identity, u) is equal to u.

   As u is of String type, let's say u = "X", combiner("", "X") = "X". Hence, u is equal to
combiner("", "X"). First rule is obeyed.

  

2. The combiner function must be compatible with the accumulator function; for all u
and t, the following must hold:

   combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t).

   Let's consider, u = "Y", t is element of Stream, say t = 1, identity = "".

   combiner.apply(u, accumulator.apply(identity, t))

   = combiner.apply("Y", accumulator.apply("", 1))

   = combiner.apply("Y", "1")

   = "Y1"

  

   and
  

   accumulator.apply(u, t)

   = accumulator.apply("Y", 1)

   = "Y1"

  

   Hence, combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u,


t). 2nd rule is also followed.

  

3. The accumulator operator must be associative and stateless. Operator + is


associative and lambda expression is stateless. 3rd rule is followed.

4. The combiner operator must be associative and stateless. Operator + is associative


and lambda expression is stateless. 4th rule is followed.

As all the rules are followed in this case, hence str1 refers to "12345678910" and str2
refers to "12345678910"

Question 17: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream<Double> stream = Stream.of(9.8, 2.3, -3.0);
8. System.out.println(stream.min());
9. }
10. }
What will be the result of compiling and executing Test class?

-3.0


Compilation error
(Correct)

Runtime Exception


2.3

Explanation
stream is of Stream<Double> type, which is a generic stream and not primitive
stream.

There is no min() method available in generic stream interface, Stream<T> and


hence, 'stream.min()' causes compilation error. 

Generic Stream<T> interface has following methods: 

Optional<T> min(Comparator<? super T> comparator); 

Optional<T> max(Comparator<? super T> comparator); 

To calculate min for generic Stream, pass the Comparator as argument:


stream.min(Double::compareTo), but note it will return an instance of
Optional<Double> type.

Question 18: Skipped

Below is the code of Test.java file:


1. public class Test {
2. enum TrafficLight {
3. RED, YELLOW, GREEN;
4. }
5.  
6. public static void main(String[] args) {
7. TrafficLight tl = TrafficLight.valueOf(args[0]);
8. switch(tl) {
9. case RED:
10. System.out.println("STOP");
11. break;
12. case YELLOW:
13. System.out.println("SLOW");
14. break;
15. case GREEN:
16. System.out.println("GO");
17. break;
18. }
19. }
20. }
What will be the output if Test class is executed by the commands: 
javac Test.java
java Test GREEN AMBER

Compilation error


GO
(Correct)


NullPointerException is thrown at runtime


IllegalArgumentException is thrown at runtime

Explanation
args[0] refers to "GREEN" and args[1] refers to "AMBER".

TrafficLight.valueOf(args[0]); -> TrafficLight.valueOf("GREEN");

GREEN is a valid enum constant, hence case label for GREEN is executed and "GO" is
printed to the console.

Question 19: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. interface Operator<T> {
4. public abstract T operation(T t1, T t2);
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Operator<String> opr1 = (s1, s2) -> s1 + s2;
10. Operator<Integer> opr2 = (i1, i2) -> i1 + i2;
11. opr1.operation("Hello", "World");
12. opr2.operation(10, 40);
13. }
14. }


HelloWorld
1040

Program compiles and executes successfully but nothing is printed on to the
console
(Correct)


HelloWorld
50

Compilation error

Explanation
Operator is a generic interface, hence it can work with any java class. There are
absolutely no issues with lambda expressions but we are not capturing or printing
the return value of operation method, hence nothing is printed on to the console. 

System.out.println(opr1.operation("Hello", "World")); => Prints HelloWorld. 

System.out.println(opr2.operation(10, 40)); => Prints 50. Over here int literals 10 and
40 are converted to Integer instances by auto-boxing.

Question 20: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.Random;
4. import java.util.stream.IntStream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. IntStream stream = new Random().ints(1, 7).limit(2);
9. System.out.println(stream.max().getAsInt());
10. }
11. }
Above code compiles and executes successfully and generates random integers.

Which of the following is not the possible output of above code?


7
(Correct)


5


4

6

Explanation
new Random().ints(start, end) => start is inclusive and end is exclusive.

So this code generates random integers between 1 and 6. All the 6 integers from 1 to
6 are possible.

Above code will never generate 7.

Question 21: Skipped

Given code: 
1. package com.udayan.ocp;
2.  
3. class Outer {
4. private String msg = "A";
5. public void print() {
6. final String msg = "B";
7. class Inner {
8. public void print() {
9. System.out.println(this.msg);
10. }
11. }
12. Inner obj = new Inner();
13. obj.print();
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. new Outer().print();
20. }
21. }
What will be the result of compiling and executing Test class?

B


A


Exception is thrown at runtime


Compilation error
(Correct)

Explanation
Keyword "this" inside method-local inner class refers to the instance of inner class.

In this case this.msg refers to msg variable defined inside Inner class but there is no
msg variable inside Inner class. Hence, this.msg causes compilation error.

System.out.println(msg); would print B (msg shadows Outer class variable) and


System.out.println(Outer.this.msg); would print A.

Question 22: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.Comparator;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Comparator<Integer> comp = (i1, i2) -> i2.compareTo(i1);
9. Stream<Integer> stream = Stream.of(55, 23, -9, 8, 42);
10. stream.sorted(comp.reversed()).forEach(i -> System.out.print(i + " "));
11. }
12. }
What will be the result of compiling and executing Test class?

55 23 -9 8 42


55 42 23 8 -9


-9 8 23 42 55
(Correct)


42 8 -9 23 55

Explanation
'(i1, i2) -> i2.compareTo(i1)' helps to sort in descending order. Code is:
'i2.compareTo(i1)' and not 'i1.compareTo(i2)'.

comp.reversed() returns a Comparator for sorting in ascending order. Hence, the


output is: '-9 8 23 42 55 '.

Question 23: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream<Double> stream = Stream.generate(() -> new Double("1.0")).limit(10);
8. System.out.println(stream.filter(d -> d > 2).allMatch(d -> d == 2));
9. }
10. }
What will be the result of compiling and executing Test class?

false


true
(Correct)

Explanation
Method signatures:

boolean anyMatch(Predicate<? super T>) : Returns true if any of the stream element
matches the given Predicate. If stream is empty, it returns false and predicate is not
evaluated. 

boolean allMatch(Predicate<? super T>) : Returns true if all the stream elements
match the given Predicate. If stream is empty, it returns true and predicate is not
evaluated. 

boolean noneMatch(Predicate<? super T>) : Returns true if none of the stream


element matches the given Predicate. If stream is empty, it returns true and predicate
is not evaluated.

In the given code,

Stream.generate(() -> new Double("1.0")).limit(10); => returns a Stream<Double>


containing 10 elements and each element is 1.0.
stream.filter(d -> d > 2) => returns an empty stream as given predicate is not true
for even 1 element.

allMatch method, when invoked on empty stream, returns true.

Question 24: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.LocalDateTime;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDateTime dt = LocalDateTime.parse("2018-03-16t10:15:30.22");
8. System.out.println(dt.toLocalDate() + " " + dt.toLocalTime());
9. }
10. }
What will be the result of compiling and executing Test class?

2018-03-16 10:15:30.22


Runtime exception


Compilation error


2018-03-16 10:15:30.220
(Correct)

Explanation
LocalDateTime.parse(text); => text is parsed using
DateTimeFormatter.ISO_LOCAL_DATE_TIME.

ISO_LOCAL_DATE_TIME is a combination of ISO_LOCAL_DATE and ISO_LOCAL_TIME,


and it parses the date-time in following format: 

[ISO_LOCAL_DATE][T][ISO_LOCAL_TIME]: T is case-insensitive.

ISO_LOCAL_DATE represents date in following format:

uuuu-MM-dd
Valid values for year (uuuu) is: 0000 to 9999.   

Valid values for month-of-year (MM) is: 01 to 12. 

Valid values for day-of-month (dd) is: 01 to 31 (At runtime this value is validated
against month/year). 

ISO_LOCAL_TIME represents time in following format:

HH:mm (if second-of-minute is not available), 

HH:mm:ss (if second-of-minute is available), 

HH:mm:ss.SSS (if nano-of-second is 3 digit or less), 

HH:mm:ss.SSSSSS (if nano-of-second is 4 to 6 digits), 

HH:mm:ss.SSSSSSSSS (if nano-of-second is 7 to 9 digits). 

Valid values for hour-of-day (HH) is: 00 to 23. 

Valid values for minute-of-hour (mm) is: 00 to 59. 

Valid values for second-of-minute (ss) is: 00 to 59. 

Valid values for nano-of-second is: 0 to 999999999. 

dt.toLocalDate() returns an instance of LocalDate, whose toString() method prints


date part: '2018-03-16'. 

dt.toLocalTime() returns an instance of LocalTime, whose toString() method prints


time part: '10:15:30.220'. As nano-of-second is of 2 digit, hence single zero is
appended to its value.

Question 25: Skipped

Will below code compile successfully?


1. package com.udayan.ocp;
2.  
3. class Outer {
4. interface I1 {
5. void m1();
6. }
7. }

No


Yes
(Correct)

Explanation
interface can be nested inside a class. Class Outer is top-level class and interface I1 is
implicitly static.

Static nested interface can use all 4 access modifiers(public, protected, default and
private).

Question 26: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.*;
4. import java.time.format.DateTimeFormatter;
5.  
6. public class Test {
7. public static void main(String [] args) {
8. LocalDate date = LocalDate.of(2018, 2, 1);
9. DateTimeFormatter formatter = DateTimeFormatter
10. .ofPattern("DD'nd day of' uuuu");
11. System.out.println(formatter.format(date));
12. }
13. }
What will be the result of compiling and executing Test class?

02nd day of 2018


Runtime Exception


01nd day of 2018


32nd day of 2018
(Correct)

Explanation
In the parse string, anything between opening and closing quote is displayed as it is.
DD -> 2 digit representation for the day-of-year. 

'nd day of' -> nd day of is displayed.

uuuu -> 4 digit representation for the year.

Output is: 32nd day of 2018.

NOTE: To display single quote, escape it with one more single quote. For example,

'DateTimeFormatter.ofPattern("'It''s' DD'nd day of' uuuu");' this will help to print: [It's
32nd day of 2018] whereas 'DateTimeFormatter.ofPattern("'It's' DD'nd day of'
uuuu");' causes runtime exception.

Question 27: Skipped

Given structure of EMPLOYEE table: 


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try {
8. Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ocp", "root", "password");
9. String query = "Select * FROM EMPLOYEE";
10. Statement stmt = con.createStatement();
11. ResultSet rs = stmt.executeQuery(query);
12. while (rs.next()) {
13. System.out.println("ID: " + rs.getInt("IDD"));
14. System.out.println("First Name: " + rs.getString("FIRSTNAME"));
15. System.out.println("Last Name: " + rs.getString("LASTNAME"));
16. System.out.println("Salary: " + rs.getDouble("SALARY"));
17. }
18. rs.close();
19. stmt.close();
20. con.close();
21. } catch (SQLException ex) {
22. System.out.println("An Error Occurred!");
23. }
24. }
25. }

Also assume: 
URL, username and password are correct.
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 result of compiling and executing Test class?


Compilation Error


NullPointerException is thrown at runtime

'An Error Occurred!' is printed on to the console

Code executes fine and doesn't print anything on to the console
(Correct)

Explanation
Even if there are no records in EMPLOYEE table, ResultSet object returned by
'stmt.executeQuery(query);' will never be null.

rs.next() returns false and control doesn't enter while loop.

'rs.getInt("IDD")' statement has wrong column name but as this statement is not
executed, hence SQLException is not thrown at runtime.

Code executes fine and doesn't print anything on to the console.

Question 28: Skipped

What will be the result of compiling and executing TestPoint class?


1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.Collections;
5. import java.util.Comparator;
6. import java.util.List;
7.  
8. class Point {
9. private int x;
10. private int y;
11.
12. public Point(int x, int y) {
13. this.x = x;
14. this.y = y;
15. }
16.
17. @Override
18. public String toString() {
19. return "Point(" + x + ", " + y + ")";
20. }
21. }
22.  
23. public class TestPoint {
24. public static void main(String [] args) {
25. List<Point> points = new ArrayList<>();
26. points.add(new Point(4, 5));
27. points.add(new Point(6, 7));
28. points.add(new Point(2, 2));
29.
30. Collections.sort(points, new Comparator<Point>() {
31. @Override
32. public int compare(Point o1, Point o2) {
33. return o1.x - o2.x;
34. }
35. });
36. }
37. }

Compilation error
(Correct)


[Point(2, 2), Point(4, 5), Point(6, 7)]


[Point(4, 5), Point(6, 7), Point(2, 2)]


[Point(6, 7), Point(4, 5), Point(2, 2)]

Explanation
x and y are private variables and are accessible within the boundary of Point class.

TestPoint class is outside the boundary of Point class and hence o1.x and o2.x cause
compilation error.

Make sure to check the accessibility before working with the logic.

Question 29: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.nio.file.*;
4. import java.util.*;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path path = Paths.get("F:\\A\\B\\C\\Book.java");
9. /*INSERT*/
10. }
11. }
 
Which of the following statements, if used to replace /*INSERT*/, will print below
output on to the console?
A
B
C
Book.java

Select ALL that apply.


1. Iterator<Path> iterator = path.iterator();
2. while(iterator.hasNext()) {
3. System.out.println(iterator.next());
4. }
(Correct)


1. for(int i = 0; i < path.getNameCount(); i++) {
2. System.out.println(path.getName(i));
3. }
(Correct)


1. for(Path p : path) {
2. System.out.println(p);
3. }
(Correct)


path.forEach(System.out::println);  
(Correct)

Explanation
All 4 are the correct way to iterate through path elements.

Root folder or drive is not considered in count and indexing. In the given path A is at
0th index, B is at 1st index, C is at 2nd index and Book.java is at 3rd index. 
path.getNameCount() returns 4.

Question 30: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void checkStatus() {
5. /*INSERT*/
6. }
7.  
8. private static String get() {
9. return "TEST";
10. }
11.  
12. public static void main(String[] args) {
13. try {
14. checkStatus();
15. } catch (AssertionError ae) {
16. System.out.println(ae.getCause());
17. }
18. }
19. }
Which of the following options can replace /*INSERT*/ such that there are no
compilation error?

assert 1 == 2 : () -> "a";  


assert 1 == 2 : return 1;  


assert 1 == 2 : 1;  
(Correct)


assert 1 == 2 : Test::get;  
Explanation
assert 1 == 2 : () -> "a"; => Right expression can't specify any lambda expression. 

assert 1 == 2 : return 1; => Right expression can't use return keyword, it should just
specify the value. 

assert 1 == 2 : Test::get; => Right expression can't specify any method reference
syntax.

assert 1 == 2 : 1; => Legal. Left expression '1 == 2' returns boolean and right
expression '1' is a non-void value.

Question 31: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.UnaryOperator;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. UnaryOperator<String> opr = s -> s.toString().toUpperCase(); //Line n1
8. System.out.println(opr.apply(new StringBuilder("Hello"))); //Line n2
9. }
10. }
What will be the result of compiling and executing Test class?

Compilation error at Line n1

HELLO

Compilation error at Line n2
(Correct)


Hello
Explanation
interface UnaryOperator<T> extends Function<T, T>, so its apply function has the
signature: T apply(T).

In this case, UnaryOperator<String> is used and hence apply method will have the
signature: String apply(String).

Lambda expression 's -> s.toString().toUpperCase()' is the correct implementation of


'String apply(String)' method and hence there is no issue with Line n1.

But at Line n2, argument passed to apply method is of StringBuilder type and not
String type and hence Line n2 causes compilation error.

Question 32: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.Predicate;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String [] arr = {"*", "**", "***", "****", "*****", "******"};
8. Predicate<String> pr1 = s -> s.length() > 3;
9. print(arr, pr1.negate());
10. }
11.
12. private static void print(String [] arr, Predicate<String> predicate) {
13. for(String str : arr) {
14. if(predicate.test(str)) {
15. System.out.println(str);
16. }
17. }
18. }
19. }
What will be the result of compiling and executing Test class?

*
**
***
****
*****
******

*
**
***
(Correct)


****
*****
******

*
**
Explanation
Lambda expression for Predicate is: s -> s.length() > 3. This means return true if
passed string's length is > 3.

pr1.negate() means return true if passed string's length is <= 3.

So first three array elements are printed.

Question 33: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String s1 = Arrays.asList("A", "E", "I", "O", "U").stream()
8. .reduce("_", String::concat);
9. String s2 = Arrays.asList("A", "E", "I", "O", "U").parallelStream()
10. .reduce("_", String::concat);
11. System.out.println(s1.equals(s2));
12. }
13. }
What will be the result of compiling and executing Test class?

Output cannot be predicted
(Correct)


It will always print false

It will always print true
Explanation
reduce method in Stream class is declared as: T reduce(T identity, BinaryOperator<T>
accumulator)

By checking the reduce method, 'reduce("", String::concat)', we can say that:

Identity is String type, accumulator is BinaryOperator<String> type.

Though you may always get false but result cannot be predicted as identity value
("_") used in reduce method is not following an important rule.

For each element 't' of the stream, accumulator.apply(identity, t) is equal to t.

'String::concat' is equivalent to lambda expression '(s1, s2) -> s1.concat(s2);'.

For 1st element of the stream, "A" accumulator.apply("_", "A") results in "_A", which is
not equal to "A" and hence rule is not followed.

s1 will always refer to "_AEIOU" but s2 may refer to various possible string objects
depending upon how parallel stream is processed.

s2 may refer to "_A_E_I_O_U" or "_AE_I_OU" or "_AEIOU". So output cannot be


predicted.

Question 34: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class MyException1 extends RuntimeException {}
4.  
5. class MyException2 extends RuntimeException {}
6.  
7. public class Test {
8. private static void m() {
9. try {
10. throw new RuntimeException();
11. } catch(RuntimeException ex) {
12. throw new MyException1();
13. } finally {
14. throw new MyException2();
15. }
16. }
17.  
18. public static void main(String[] args) {
19. try {
20. m();
21. } catch(MyException1 e) {
22. System.out.println("MyException1");
23. } catch(MyException2 e) {
24. System.out.println("MyException2");
25. } catch (RuntimeException e) {
26. System.out.println("RuntimeException");
27. }
28. }
29. }
What will be the result of compiling and executing Test class?

MyException2
(Correct)


RuntimeException


MyException1

Explanation
If finally block throws exception, then exception thrown by try or catch block is
ignored.

In this case, method m() throws an instance of MyException2 class.

Question 35: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.List;
4. import java.util.Map;
5. import java.util.stream.Collectors;
6. import java.util.stream.Stream;
7.  
8. class Certification {
9. String studId;
10. String test;
11. int marks;
12.  
13. Certification(String studId, String test, int marks) {
14. this.studId = studId;
15. this.test = test;
16. this.marks = marks;
17. }
18.  
19. public String toString() {
20. return "{" + studId + ", " + test + ", " + marks + "}";
21. }
22.  
23. public String getStudId() {
24. return studId;
25. }
26.  
27. public String getTest() {
28. return test;
29. }
30.  
31. public int getMarks() {
32. return marks;
33. }
34. }
35.  
36. public class Test {
37. public static void main(String[] args) {
38. Certification c1 = new Certification("S001", "OCA", 87);
39. Certification c2 = new Certification("S002", "OCA", 82);
40. Certification c3 = new Certification("S001", "OCP", 79);
41. Certification c4 = new Certification("S002", "OCP", 89);
42. Certification c5 = new Certification("S003", "OCA", 60);
43. Certification c6 = new Certification("S004", "OCA", 88);
44.  
45. Stream<Certification> stream = Stream.of(c1, c2, c3, c4, c5, c6);
46. Map<String, List<Certification>> map =
47. stream.collect(Collectors.groupingBy(Certification::getTest));
48. System.out.println(map.get("OCP"));
49. }
50. }
What will be the result of compiling and executing Test class?

[{S001, OCA, 87}, {S002, OCA, 82}, {S001, OCP, 79}, {S002, OCP, 89}, {S003, OCA,
60}, {S004, OCA, 88}]


[]


[{S001, OCP, 79}, {S002, OCP, 89}]
(Correct)


[{S001, OCA, 87}, {S002, OCA, 82}, {S003, OCA, 60}, {S004, OCA, 88}]
Explanation
Collectors.groupingBy(Certification::getTest) => groups on the basis of test which is
String type.

Hence return type is:  Map<String, List<Certification>>.

There are 4 records for OCA exam and 2 records for OCP exam, hence
map.get("OCP") returns the list containing OCP records.

Question 36: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.Collections;
5. import java.util.List;
6. import java.util.stream.IntStream;
7.  
8. public class Test {
9. public static void main(String[] args) {
10. List<Integer> list = Collections.synchronizedList(new ArrayList<>());
11. IntStream stream = IntStream.rangeClosed(1, 7);
12. stream.parallel().map(x -> {
13. list.add(x); //Line 13
14. return x;
15. }).forEach(System.out::print); //Line 15
16. System.out.println();
17. list.forEach(System.out::print); //Line 17
18. }
19. }
Which of the following statement is true about above code?

Output cannot be predicted
(Correct)


Line 15 and Line 17 will print exact same output on to the console

Line 15 and Line 17 will not print exact same output on to the console
Explanation
Line 13 is changing the state of list object and hence it should be avoided in parallel
stream. You can never predict the order in which elements will be added to the
stream.

Line 13 and Line 15 doesn't run in synchronized manner, hence as the result, output
of Line 17 may be different from that of Line 15.
On my machine below is the output of various executions:

Execution 1:

5427163

5412736

Execution 2:

5476231

5476123

Execution 3:

5476231

5476231

Question 37: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.LongFunction;
4. import java.util.function.LongUnaryOperator;
5. import java.util.stream.Stream;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. long seed = 10;
10. Stream<Long> stream = Stream.iterate(seed, i -> i + 2).limit(2); //Line n1
11. LongFunction<LongUnaryOperator> func = m -> n -> n / m; //Line n2
12. stream.mapToLong(i -> i).map(func.apply(2)).forEach(System.out::println);
//Line n3
13. }
14. }
What will be the result of compiling and executing Test class?

Compilation error

1
1

0
0

10
12

5
6
(Correct)

Explanation
As variable seed is of long type, Hence Stream.iterate(seed, i -> i + 2) returns an
infinite stream of Stream<Long> type. limit(2) returns the Stream<Long> object
containing 2 elements 10 and 12. There is no issue with line n1.

Though the lambda expression with 2 arrows seems confusing but it is correct syntax.
To understand, Line n2 can be re-written as:

LongFunction<LongUnaryOperator> func = (m) -> {


return (n) -> {
return n / m;
};
};

And corresponding anonymous class syntax is:

LongFunction<LongUnaryOperator> func = new LongFunction<LongUnaryOperator>() {


@Override
public LongUnaryOperator apply(long m) {
LongUnaryOperator operator = new LongUnaryOperator() {
@Override
public long applyAsLong(long n) {
return n / m;
}
};
return operator;
}
};

So, there is no issue with Line n2. Let's check Line n3.

stream.mapToLong(i -> i) returns an instance of LongStream and LongStream has


map(LongUnaryOperator) method.

'func.apply(2)' returns an instance of LongUnaryOperator, in which


applyAsLong(long) method has below implementation:

LongUnaryOperator operator = new LongUnaryOperator() {


@Override
public long applyAsLong(long n) {
return n / 2;
}
};

As stream has elements 10 and 12, so map(func.apply(2)) returns an instance of


LongStream after dividing each element by 2, so resultant stream contains elements
5 and 6.

forEach(System.out::println) prints 5 and 6 on to the console.

Question 38: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. IntStream.iterate(1, i -> i + 1).limit(11)
8. .filter(i -> i % 2 != 0).forEach(System.out::print);
9. }
10. }
What will be the result of compiling and executing Test class?

1357911
(Correct)


24681012

246810


13579

Explanation
IntStream.iterate(1, i -> i + 1) => [1,2,3,4,5,6,7,...]. This is an infinite stream. 

limit(11) => [1,2,3,4,5,...,11]. Eleven elements from the above stream. 

filter(i -> i % 2 != 0) => [1,3,5,7,9,11]. Returns a stream consisting of all odd


numbers. 

forEach(System.out::print); => Prints '1357911' on to the console.

Question 39: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. class Employee {
6. private String name;
7. private double salary;
8.  
9. public Employee(String name, double salary) {
10. this.name = name;
11. this.salary = salary;
12. }
13.  
14. public String getName() {
15. return name;
16. }
17.  
18. public double getSalary() {
19. return salary;
20. }
21.  
22. public void setSalary(double salary) {
23. this.salary = salary;
24. }
25.  
26. public String toString() {
27. return "{" + name + ", " + salary + "}";
28. }
29. }
30.  
31. public class Test {
32. public static void main(String[] args) {
33. List<Employee> employees = Arrays.asList(new Employee("Jack", 10000),
34. new Employee("Lucy", 12000));
35. employees.stream().filter(x -> x.getSalary() > 10000)
36. .map(e -> e.getName()).forEach(System.out::println);
37. }
38. }
What will be the result of compiling and executing Test class?

Lucy
Jack

Lucy
(Correct)


Jack


Jack
Lucy
Explanation
employees.stream() => Gets the stream for employees list. 

filter(x -> x.getSalary() > 10000) => Returns a stream consisting of elements of the
stream that match the given Predicate. In this case {"Lucy", 12000} is returned.

map(e -> e.getName()) => Returns a stream consisting of the results of applying the
given function to the elements of this stream. In this case {"Lucy"} is returned. 

forEach(System.out::println) => Prints 'Lucy' on to the console.

Question 40: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void m1() {
5. System.out.println(1/0);
6. }
7.  
8. public static void main(String[] args) {
9. try {
10. m1();
11. } finally {
12. System.out.println("A");
13. }
14. }
15. }
What will be the result of compiling and executing Test class?

A is printed to the console and program ends normally

A is printed to the console, stack trace is printed and then program ends abruptly
(Correct)


A is printed to the console, stack trace is printed and then program ends normally

Compilation error
Explanation
Method m1() throws an instance of ArithmeticException and method m1() doesn't
handle it, so it forwards the exception to calling method main.

Method main doesn't handle ArithmeticException so it forwards it to JVM, but just


before that finally block is executed. This prints A on to the console.

After that JVM prints the stack trace and terminates the program abruptly.

Question 41: Skipped

A bank's swift code is generally of 11 characters and used in international money


transfers
An example: ICICINBBRT4
ICIC: First 4 letters for bank code
IN: Next 2 letters for Country code
BB: Next 2 letters for Location code
RT4: Next 3 letters for Branch code

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Collections;
5. import java.util.Comparator;
6. import java.util.List;
7.  
8. public class SortSwiftCode {
9. public static void main(String[] args) {
10. List<String> swiftCodes = Arrays.asList("ICICINDD016", "ICICINBBRT4",
"BOTKINDD075", "BARBINBB011",
11. "SBBJINDD062", "ABNATHBK865", "BKCHTHBK012");
12.
13. Comparator<String> countryLocationBank =
Comparator.comparing(SortSwiftCode::extractCountry)
14.
.thenComparing(SortSwiftCode::extractLocation).thenComparing(SortSwiftCode::extract
Bank);
15.
16. Collections.sort(swiftCodes, countryLocationBank);
17. printCodes(swiftCodes);
18.  
19. }
20.  
21. private static String extractCountry(String swiftCode) {
22. return swiftCode.substring(4, 6);
23. }
24.  
25. private static String extractLocation(String swiftCode) {
26. return swiftCode.substring(6, 8);
27. }
28.  
29. private static String extractBank(String swiftCode) {
30. return swiftCode.substring(0, 4);
31. }
32.  
33. private static void printCodes(List<String> list) {
34. for (String str : list) {
35. System.out.println(str);
36. }
37. }
38. }
What will be the result of compiling and executing SortSwiftCode class?

BARBINBB011
BOTKINDD075
ICICINBBRT4
ICICINDD016
SBBJINDD062
ABNATHBK865
BKCHTHBK012

ABNATHBK865
BKCHTHBK012
BARBINBB011
ICICINBBRT4
BOTKINDD075
ICICINDD016
SBBJINDD062

BARBINBB011
ICICINBBRT4
BOTKINDD075
ICICINDD016
SBBJINDD062
ABNATHBK865
BKCHTHBK012
(Correct)


None of the other options

Explanation
Default thenComparing method helps to chain the Comparators.

First the list is sorted on the basis of country code, if matching country code is found
then sorted on the basis of location code and if location code matches then list is
sorted on bank code.

Question 42: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream.of().map(s -> s.reverse()).forEach(System.out::println);
8. }
9. }
What will be the result of compiling and executing Test class?

Program executes successfully but nothing is printed on to the console


NullPointerException is thrown at runtime


ClassCastException is thrown at runtime


Compilation error
(Correct)

Explanation
Stream.of() returns blank stream. As Type of stream is not specified, stream is of
'Stream<Object>', each element of the stream is considered to be of 'Object' type.

map method in this case accepts 'Function<? super Object, ? extends R>'.
There is no 'reverse()' method in Object class and hence lambda expression causes
compilation failure.

Question 43: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class MyResource implements AutoCloseable {
4. public void execute() {
5. System.out.println("Executing");
6. }
7.  
8. @Override
9. public void close() throws Exception {
10. System.out.println("Closing");
11. }
12. }
13.  
14. public class Test {
15. public static void main(String[] args) {
16. try(MyResource resource = new MyResource()) {
17. resource.execute();
18. }
19. }
20. }
What will be the result of compiling and executing Test class?

Executing


Compilation Error
(Correct)


Runtime Exception


Executing
Closing
Explanation
close() method in AutoCloseable interface has below declaration:

void close() throws Exception;

MyResource class correctly overrides close() method.


try-with-resources statement internally invokes resource.close() method after
executing resource.execute().

Overriding close method declares to throw Exception (checked exception) and hence
handle or declare rule must be followed.

As main method neither declares to throw Exception nor provides catch block for
Exception type, hence try-with-resources statement causes compilation error.

Question 44: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Optional<Integer> optional = Stream.of(10).findFirst();
9. System.out.println(optional);
10. }
11. }
What will be the result of compiling and executing Test class?

Text containing @ symbol


10


Optional[10]
(Correct)

Explanation
Optional<T> is a final class and overrides toString() method:
public String toString() {
return value != null
? String.format("Optional[%s]", value)
: "Optional.empty";
}
In the question, Optional is of Integer type and Integer class overrides toString()
method, so output is: Optional[10]

Question 45: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date1 = LocalDate.of(2019, 1, 1);
8. Duration d = Duration.ofDays(1);
9. System.out.println(date1.plus(d));
10. }
11. }
What will be the result of compiling and executing Test class?

2019-01-01


Compilation error


Runtime exception
(Correct)


2019-01-02

Explanation
Duration works with time component and not Date component.

plus(TemporalAmount) method of LocalDate class accepts TemporalAmount type


and Duration implement TemporalAmount, so no compilation error. But at runtime
date1.plus(d) causes exception.

Don't get confused with 'Duration.ofDays(1);', it is a convenient method to work with


large time.

Question 46: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.text.NumberFormat;
4. import java.util.Locale;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Locale loc = new Locale("en", "US");
9. NumberFormat nf = NumberFormat.getCurrencyInstance(loc);
10. System.out.printf("Amount %s is in %s" , nf.format(10), nf.getCurrency());
11. }
12. }
What will be the result of compiling and executing above program?

Amount 10.00 is in US Dollar

Amount $10.00 is in US Dollar

Amount $10.00 is in USD
(Correct)


Amount 10.00 is in USD
Explanation
As Locale instance is for en_US, hence 'NumberFormat.getCurrencyInstance(loc);'
returns NumberFormat instance for US.

Currency code for US is USD and it is represented as $.

nf.getCurrency() returns the Currency object with currency Code "USD" and
nf.format(10) returns $10.00

Question 47: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.Function;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Function<String, Integer> f1 = Integer::new;
8. Function<String, String> f2 = s -> new
StringBuilder(s).reverse().toString();
9. System.out.println(f1.compose(f2).apply("12345"));
10. }
11. }
12.  
What will be the result of compiling and executing Test class?

NumberFormatException is thrown at runtime


12345


54321
(Correct)


Compilation error

Explanation
f1.compose(f2) means first apply f2 and then f1.

f2.apply("12345") returns "54321" and then f1.apply("54321") returns 54321

Question 48: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. class Person {
6. private String name;
7. private int age;
8.  
9. public Person(String name, int age) {
10. this.name = name;
11. this.age = age;
12. }
13.  
14. public String getName() {
15. return name;
16. }
17.  
18. public int getAge() {
19. return age;
20. }
21. }
22.  
23. class Student extends Person implements Serializable {
24. private String course;
25.  
26. public Student(String name, int age, String course) {
27. super(name, age);
28. this.course = course;
29. }
30.  
31. public String getCourse() {
32. return course;
33. }
34. }
35.  
36. public class Test {
37. public static void main(String[] args) throws IOException,
ClassNotFoundException {
38. Student stud = new Student("John", 20, "Computer Science");
39. try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(("F:\\stud.ser")));
40. ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("F:\\stud.ser")))
41. {
42. oos.writeObject(stud);
43.  
44. Student s = (Student) ois.readObject();
45. System.out.printf("%s, %d, %s", s.getName(), s.getAge(),
s.getCourse());
46. }
47. }
48. }
F: is accessible for reading/writing and currently doesn't contain any files/directories. 

What will be the result of compiling and executing Test class?


John, 20, Computer Science


null, 0, null


Runtime Exception
(Correct)


null, 0, Computer Science

Explanation
Class Student implements Serializable but it's super class Person is not Serializable.

While de-serializing of Serializable class, constructor of that class is not invoked.

But if Parent class is not Serializable, then to construct the Parent class object, a no-
argument constructor in Parent class is needed. This no-argument constructor
initializes the properties to their default values.

As Person class doesn't have no-argument constructor, hence 'ois.readObject();'


throws runtime exception.

Question 49: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. @FunctionalInterface
4. interface I4 {
5. void print();
6. boolean equals(Object obj);
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. I4 obj = () -> System.out.println("Lambda expression");
12. obj.print();
13. }
14. }


No output


Compilation error


Runtime error


Lambda expression
(Correct)

Explanation
Functional interface must have only one non-overriding abstract method but
Functional interface can have constant variables, static methods, default methods
and overriding abstract methods [equals(Object) method, toString() method etc.
from Object class].

I4 is a Functional Interface.

Question 50: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. interface Operation {
4. int operate(int x, int y);
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. int x = 10;
10. int y = 20;
11. Operation o1 = (x, y) -> x * y;
12. System.out.println(o1.operate(5, 10));
13. }
14. }


200


Exception is thrown at runtime


50


Compilation error
(Correct)

Explanation
Lambda expression's variables x and y cannot redeclare another local variables defined in the
enclosing scope.

Question 51: Skipped

Given code of Test.java file: 


1. import java.io.*;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. Console console = System.console();
6. if(console != null) {
7. console.format("%d %<x", 10);
8. }
9. }
10. }

What will be the output of compiling and executing Test class from command
prompt?
javac Test.java
java Test

Runtime Exception


10 a
(Correct)


10 12


10


10 10

Explanation
'<' within format string is used to reuse the argument matched by the previous
format specifier.

d is for Integer and x is for hexadecimal. Hexadecimal value for 10 is a.


So, 'console.format("%d %<x", 10);' prints '10 a' on to the console.

NOTE: console.format(...) and console.printf(...) methods are same. In fact, printf(...)


method invokes format(...) method.

Question 52: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.IntSummaryStatistics;
5. import java.util.stream.Stream;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. String text = "I am going to pass OCP exam in first attempt";
10. Stream<String> stream = Arrays.stream(text.split(" "));
11. IntSummaryStatistics stat = stream.map(s ->
s.length()).summaryStatistics();
12. System.out.println(stat.getMax());
13. }
14. }
Which of the following needs to be done, so that output is 7?

Replace  stream.map(s -> s.length())   with  stream.mapToInt(s -> s.length())  
(Correct)


Replace  text.split(" ")   with  text.split(",")  

No need to make any changes, on execution given code prints 7 on to the
console

Replace  stat.getMax()   with  stat.getCount()  
Explanation
text.split(" ") => {"I", "am", "going", "to", "pass", "OCP", "exam", "in", "first",
"attempt"}. 

Arrays.stream(text.split(" ")); => ["I", "am", "going", "to", "pass", "OCP", "exam", "in",
"first", "attempt"]. Stream<String> instance is returned. 

stream.map(s -> s.length()) => [1, 2, 5, 2, 4, 3, 4, 2, 5, 7]. Stream<Integer> is


returned. 
summaryStatistics() method is declared in IntStream, LongStream and DoubleStream
interfaces but not declared in Stream<Integer> interface and hence 'stream.map(s ->
s.length()).summaryStatistics();' causes compilation failure.

Out of the given options, replacing 'stream.map(s -> s.length())' with


'stream.mapToInt(s -> s.length())' will correctly return an instance of IntStream and
hence summaryStatistics() method can easily be invoked.

As you had to select only one option, so you can stop here. No need to validate
other options. I am explaining other options just for knowledge purpose.

stat.getCount() will return 10 so not a correct option.

text.split(" ") delimits the text on the basis of single space.

text.split(",") will delimit it on the basis of comma but as no comma is present in the
given text, hence whole text will be returned and stat.getMax() will print 44.

Question 53: Skipped

Given code of Adder.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.ForkJoinPool;
4. import java.util.concurrent.RecursiveTask;
5.  
6. public class Adder {
7. private static long LIMIT = 1000000000;
8. private static final int THREADS = 100;
9.  
10. static class AdderTask extends RecursiveTask<Long> {
11. long from, to;
12.  
13. public AdderTask(long from, long to) {
14. this.from = from;
15. this.to = to;
16. }
17.  
18. @Override
19. protected Long compute() {
20. if ((to - from) <= LIMIT/THREADS) {
21. long localSum = 0;
22. for(long i = from; i <= to; i++) {
23. localSum += i;
24. }
25. return localSum;
26. }
27. else {
28. long mid = (from + to) / 2;
29. AdderTask first = new AdderTask(from, mid);
30. AdderTask second = new AdderTask(mid + 1, to);
31. first.fork();
32. /*INSERT*/
33. }
34. }
35. }
36.  
37. public static void main(String[] args) {
38. ForkJoinPool pool = new ForkJoinPool(THREADS);
39. long sum = pool.invoke(new AdderTask(1, LIMIT));
40. System.out.printf("sum of the number from %d to %d is %d %n", 1, LIMIT,
sum);
41. }
42. }
Which of the following statement, if used to replace /*INSERT*/, will EFFICIENTLY add
the numbers from 1 to 1000000000?

return first.join() + second.compute();  


return first.join();  


return second.compute() + first.join();  
(Correct)


return second.compute();  
Explanation
After invoking fork() on 1st subtask, it is necessary to invoke join() on 1st subtask and
compute() on 2nd subtask. Hence 'return first.join();' and 'return second.compute();'
are not valid options.

The order of execution of calling join() and compute() on divided subtasks is


important in a fork/join framework.

For the statement 'return first.join() + second.compute();' as join() is called so each


task waits for its completion before starting execution of a new thread. Even though
you will get the correct output but it is not utilizing the fork/join framework
efficiently.
If you are interested in finding out the time difference then I will suggest to modify
main(String[]) method as below and run the program for both the statements
separately.

public static void main(String[] args) {


LocalTime start = LocalTime.now();
ForkJoinPool pool = new ForkJoinPool(THREADS);
long sum = pool.invoke(new AdderTask(1, LIMIT));
System.out.printf("sum of the number from %d to %d is %d %n", 1, LIMIT,
sum);
LocalTime end = LocalTime.now();
System.out.println(ChronoUnit.NANOS.between(start, end));
}

Question 54: Skipped

Which of the following keywords is used to manually throw an exception?


throw
(Correct)


catch


throws


thrown

Explanation
catch is for catching the exception and not throwing it. 

thrown is not a java keyword. 

throws is used to declare the exceptions a method can throw.

To manually throw an exception, throw keyword is used. e.g., throw new Exception(); 

Question 55: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> list = Arrays.asList("A", "E", "I", "O", "U");
9. System.out.println(list.________________.isParallel());
10. }
11. }
Which of the options correctly fills the blank, such that output is true?

Select 2 options.


stream().parallel()  
(Correct)


parallel()  


stream()  


parallelStream()  
(Correct)

Explanation
Collection interface has a default method stream() to return a sequential() stream for
the currently executing Collection.

Collection interface has a default method parallelStream() to return a parallel stream


for the currently executing Collection.

Stream class has parallel() method to convert to parallel stream and sequential()
method to convert to sequential stream.

isParallel() method of Stream class returns true for parallel Stream.

list is a Collection. So,

list.stream() returns a sequential stream and list.stream().parallel() returns a parallel


stream. list.stream().parallel().isParallel() returns true. 

stream() returns a sequential stream and list.stream().isParallel() returns false. 


list.parallel() causes compilation error.

list.parallelStream() returns a parallel stream. list.parallelStream().isParallel() returns


true.

Question 56: Skipped

What will be the result of compiling and executing Test class?


1. package com.udayan.ocp;
2.  
3. import java.util.function.Function;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Function<char [], String> obj = String::new; //Line 5
8. String s = obj.apply(new char[] {'j', 'a', 'v', 'a'}); //Line 6
9. System.out.println(s);
10. }
11. }

Compilation error at Line 5


Exception is thrown at runtime


Compilation error at Line 6


java
(Correct)

Explanation
String::new is the constructor reference for String(char []) constructor and
obj.apply(new char[] {'j', 'a', 'v', 'a'}); would call the constructor at runtime, converting
char [] to String. Variable s refers "java".

If you have issues in understanding method reference syntax, then try to write the
corresponding lambda expression first.

For example, in Line 5, I have to write a lambda expression which accepts char [] and
returns String object. It can be written as:

Function<char [], String> obj2 = arr -> new String(arr); It is bit easier to understand
this syntax.
Question 57: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static <T extends Number> void print(T t) {
5. System.out.println(t.intValue());
6. }
7.  
8. public static void main(String[] args) {
9. /*INSERT*/
10. }
11. }
Which of the following statements, if used to replace /*INSERT*/, will not cause any
compilation error?

Select 2 options.


print(new Character('a'));  


print(new Number(0));  


print(new Integer(1));  
(Correct)


print(new Object());  


print(new Double(5.5));  
(Correct)

Explanation
Number is an abstract class, so 'new Number(0)' cannot be used.

Character class doesn't extend Number.

Object class doesn't extend Number.

Question 58: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.sql.SQLException;
4.  
5. public class Test {
6. private static void m() throws SQLException {
7. try {
8. throw new SQLException();
9. } catch (Exception e) {
10. e = null; //Line 10
11. throw e; //Line 11
12. }
13. }
14.  
15. public static void main(String[] args) {
16. try {
17. m(); //Line 17
18. } catch(SQLException e) {
19. System.out.println("Caught Successfully.");
20. }
21. }
22. }
What will be the result of compiling and executing Test class?

Program ends abruptly

Line 17 causes compilation failure

Line 11 causes compilation failure
(Correct)


Line 10 causes compilation failure

Caught Successfully.

Explanation
Exception is a java class, so e = null; is a valid statement and compiles successfully.

If you comment Line 10, and simply throw e, then code would compile successfully as
compiler is certain that e would refer to an instance of SQLException only.

But the moment compiler finds 'e = null;', 'throw e;' (Line 11) causes compilation
error as at runtime e may refer to any Exception type.

NOTE: No issues with Line 17 as method m() declares to throw SQLException and
main method code correctly handles it.

Question 59: Skipped

Given structure of MESSAGES table:


MESSAGES (msg1 varchar(100), msg2 varchar(100))  
MESSAGES table contains below records: 
'Happy New Year!', 'Happy Holidays!'

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4. import java.util.Properties;
5.  
6. public class Test {
7. public static void main(String[] args) throws Exception {
8. String url = "jdbc:mysql://localhost:3306/ocp";
9. Properties prop = new Properties();
10. prop.put("user", "root");
11. prop.put("password", "password");
12. String query = "Select count(*) FROM MESSAGES";
13. try (Connection con = DriverManager.getConnection(url, prop);
14. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
15. ResultSet rs = stmt.executeQuery(query);)
16. {
17. rs.absolute(0);
18. System.out.println(rs.getInt(1));
19. }
20. }
21. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


2


1


An exception is thrown at runtime
(Correct)


0

Explanation
Initially cursor is just before the first record. 'rs.absolute(0);' also moves the cursor to
just before the first record. 

As ResultSet cursor is initially before the first record, hence 'rs.getInt(1)' throws
SQLException at runtime.

Question 60: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream.of(true, false, true).map(b -> b.toString()
8. .toUpperCase()).peek(System.out::println).count();
9. }
10. }
What will be the result of compiling and executing Test class?

TRUE
FALSE
TRUE
3

TRUE
FALSE
TRUE
(Correct)


true
false
true

true
false
true
3
Explanation
count() is a terminal method for finite stream, hence peek(System.out::println) is
executed for all the 3 elements of the stream.

count() method returns long value but it is not used.

Question 61: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<String> list = Arrays.asList("A", "A", "b", "B", "c", "c");
9. list.stream().distinct().forEach(System.out::print);
10. }
11. }
What will be the result of compiling and executing Test class?

Abc


AbBc
(Correct)


ABc


AAbBcc


ABbc

Explanation
Uppercase characters are different from Lowercase characters.

distinct() method of Stream returns a stream consisting of the distinct elements


(according to Object.equals(Object)) of this stream.

"A" and "A" are same, "b" and "B" are different & "c" and "c" are same.

Arrays.asList(...) method returns sequential List object, so order of elements remain


same.

Output is: AbBc

Question 62: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayDeque;
4. import java.util.Deque;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Deque<Character> chars = new ArrayDeque<>();
9. chars.add('A');
10. chars.add('B');
11. chars.remove();
12. chars.add('C');
13. chars.remove();
14.  
15. System.out.println(chars);
16. }
17. }
What will be the result of compiling and executing Test class?

[C]
(Correct)


[B]


[A]

Explanation
Deque's add() method invokes addLast(E) method and remove() method invokes
removeFirst() method.

chars.add('A'); => [*A], {* represents HEAD element}

chars.add('B'); => [*A,B], 

chars.remove(); => [*B], 

chars.add('C'); => [*B,C], 

chars.remove(); => [*C], 

System.out.println(chars); => Prints [C] on to the console.

Question 63: Skipped

F: is accessible for reading/writing and below is the directory structure for F:


1. F:.
2. └───Parent
3. │ a.txt
4. │ b.txt
5. │
6. └───Child
7. c.txt
8. d.txt

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7. import java.nio.file.attribute.BasicFileAttributes;
8. import java.util.function.BiPredicate;
9. import java.util.stream.Stream;
10.  
11. public class Test {
12. public static void main(String[] args) throws IOException {
13. Path root = Paths.get("F:");
14. BiPredicate<Path, BasicFileAttributes> predicate = (p,a) ->
p.endsWith(null);
15. try(Stream<Path> paths = Files.find(root, 2, predicate))
16. {
17. paths.forEach(System.out::println);
18. }
19. }
20. }

What will be the result of compiling and executing Test class?


Above program executes successfully and prints below lines on to the console: 
F:Parent\Child\c.txt
F:Parent\Child\d.txt
F:Parent\a.txt
F:Parent\b.txt

Compilation error
(Correct)


Above program executes successfully and prints below lines on to the console:
F:Parent\a.txt
F:Parent\b.txt

Above program executes successfully and prints nothing on to the console
Explanation
endsWith method is overloaded in Path interface:
boolean endsWith(Path other);

boolean endsWith(String other);

'p.endsWith(null)' causes compilation error as it is an ambiguous method call.

Question 64: Skipped

F: is accessible for reading and below is the directory structure for F:


1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java
'Book.java' file is available under 'C' directory.

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path file = Paths.get("F:\\A\\.\\B\\C\\D\\..\\Book.java");
9. System.out.println(file.toRealPath());
10. }
11. }

What will be the result of compiling and executing Test class?


F:\A\B\C\Book.java


Compilation Error
(Correct)


Book.java


NoSuchFileException is thrown at runtime.


F:\A\.\B\C\D\..\Book.java
Explanation
toRealPath() returns the path of an existing file. It returns the path after normalizing.

As toRealPath() works with existing file, there is a possibility of I/O error hence
toRealPath() method declares to throw IOException, which is a checked exception.

Given code doesn't handle or declare IOException and that is why 'file.toRealPath()'
causes compilation error.

Question 65: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. enum Flags {
4. TRUE;
5.  
6. Flags() {
7. System.out.println("HELLO");
8. }
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. Flags f1 = Flags.TRUE;
14. Flags f2 = Flags.TRUE;
15. Flags f3 = Flags.TRUE;
16. }
17. }
What will be the result of compiling and executing Test class?

HELLO is printed once
(Correct)


HELLO Is not printed on to the console

HELLO is printed thrice

HELLO is printed twice
Explanation
Enum constructor is invoked once for every constant. There is only one constant,
hence constructor is invoked only once.

For first 'Flags.TRUE', enum constructor is invoked but for later statements enum
constructor is not invoked.
Question 66: Skipped

Given code:
1. package com.udayan.ocp;
2.  
3. class Message {
4. public void printMessage() {
5. System.out.println("Hello!");
6. }
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. Message msg = new Message() {
12. public void PrintMessage() {
13. System.out.println("HELLO!");
14. }
15. };
16. msg.printMessage();
17. }
18. }
What will be the result of compiling and executing Test class?

Hello!
(Correct)


Runtime error


HELLO!


Compilation error

Explanation
It is a valid anonymous inner class syntax. But anonymous inner class code doesn't
override printMessage() method of Message class rather it defines a new method
PrintMessage (P in upper case).

Anonymous inner class allows to define methods not available in its super class, in
this case PrintMessage() method.

But msg.printMessage(); statement invokes the printMessage method of super class,


Message and thus "Hello!" gets printed in the output.

Question 67: Skipped

Which of the following is a valid ResultSet concur type?



CONCUR_READ_ONLY
(Correct)


CONCUR_BOTH


CONCUR_READ_WRITE


CONCUR_WRITE_ONLY

Explanation
There are 2 ResultSet concur types: CONCUR_READ_ONLY and
CONCUR_UPDATABLE.
Question 68: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.ExecutionException;
4. import java.util.concurrent.atomic.AtomicInteger;
5.  
6. public class Test {
7. public static void main(String [] args) throws InterruptedException,
ExecutionException{
8. AtomicInteger ai = new AtomicInteger(10);
9. /*INSERT*/
10. }
11. }
Which of the following statements, if used to replace /*INSERT*/, will print '11:11' on
to the console?

Select 2 options.


System.out.println(ai.incrementAndGet(1) + ":" + ai.get());  


System.out.println(ai.getAndIncrement() + ":" + ai.get());  


System.out.println(ai.getAndAdd(1) + ":" + ai.get());  


System.out.println(ai.incrementAndGet() + ":" + ai.get());  
(Correct)


System.out.println(ai.addAndGet(1) + ":" + ai);  
(Correct)

Explanation
AtomicInteger overrides toString() method hence when ai is passed to println
method, its value is printed.

'ai.addAndGet(1)' first adds 1 (10+1) and returns 11. 'ai' also prints 11. 

'ai.getAndAdd(1)' first returns 10 and then adds 1. 

'ai.getAndIncrement()' first returns 10 and then adds 1. 

'ai.incrementAndGet()' increments the value by 1 (10+1) and returns 11. 

'ai.incrementAndGet(1)' causes compilation failure. 

'ai.get()' returns the current value of ai. 

Question 69: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.stream.IntStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. System.out.println(IntStream.range(-10, -10).count());
8. System.out.println(IntStream.rangeClosed(-10, -10).count());
9. }
10. }
What will be the result of compiling and executing Test class?

1
1

1
0

0
0

0
1
(Correct)

Explanation
IntStream.range(int start, int end) => start is inclusive and end is exclusive. If start >=
end, then empty stream is returned. 

IntStream.range(-10, -10) => returns empty stream.

IntStream.rangeClosed(int start, int end) => Both start and end are inclusive. If start
> end, then empty stream is returned.

IntStream.rangeClosed(-10, -10) => returns a stream containing just 1 element,


which is -10.

Question 70: Skipped

Given structure of EMPLOYEE table:


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))

EMPLOYEE table contains below records:

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file:

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws Exception {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
11. try (Connection con = DriverManager.getConnection(url, user, password);
12. Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
13. ) {
14. ResultSet rs = stmt.executeQuery(query);
15. rs.absolute(1);
16. rs.moveToInsertRow();
17. rs.updateInt(1, 105);
18. rs.updateString(2, "Chris");
19. rs.updateString(3, "Morris");
20. rs.updateDouble(4, 25000);
21. rs.deleteRow();
22. rs.refreshRow();
23. System.out.println(rs.getInt(1));
24. }
25. }
26. }

Also assume:

URL is correct and db credentials are: root/password.

SQL query is correct and valid.

The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


An exception is raised by rs.refreshRow();

105

An exception is raised by rs.deleteRow();
(Correct)


102

104
Explanation
Given query returns below records:

101 John    Smith   12000   

102 Sean    Smith   15000   

103 Regina  Williams    15500   

104 Natasha George  14600   

'rs.absolute(1);' It moves the cursor to 1st record

'rs.moveToInsertRow();' It moves the cursor to the insert row.


Please note, If the cursor is at insert row and refreshRow() or updateRow() or
deleteRow() method is called, then SQLException is thrown.

Hence, in this case an exception is raised by rs.deleteRow();

Question 71: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.util.function.DoubleFunction;
4. import java.util.function.DoubleUnaryOperator;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. DoubleFunction<DoubleUnaryOperator> func = m -> n -> m + n; //Line n1
9. System.out.println(func.apply(11).applyAsDouble(24)); //Line n2
10. }
11. }
What will be the result of compiling and executing Test class?

Line n1 causes compilation error

Line n2 causes compilation error

35.0
(Correct)


48.0

22.0
Explanation
Though the lambda expression with 2 arrows seems confusing but it is correct syntax.
To understand, Line n1 can be re-written as:
DoubleFunction<DoubleUnaryOperator> func = (m) -> {
return (n) -> {
return m + n;
};
};

And corresponding anonymous class syntax is:

DoubleFunction<DoubleUnaryOperator> func = new


DoubleFunction<DoubleUnaryOperator>() {
@Override
public DoubleUnaryOperator apply(double m) {
DoubleUnaryOperator duo = new DoubleUnaryOperator() {
@Override
public double applyAsDouble(double n) {
return m + n;
}
};
return duo;
}
};

So, there is no issue with Line n1. Let's check Line n2.

'func.apply(11)' returns an instance of DoubleUnaryOperator, in which


applyAsDouble(double) method has below implementation:
DoubleUnaryOperator duo = new DoubleUnaryOperator() {
@Override
public double applyAsDouble(double n) {
return 11 + n;
}
};

And hence, when applyAsDouble(24) is invoked on above instance of


DoubleUnaryOperator, then it returns the result of 11 + 24, which is 35 and as return
type is double, so 35.0 is returned.

Question 72: Skipped

Which of the following pairs correctly represent the Functional interface and its single
abstract method?


Consumer : accept
Function : apply
Supplier : get
Predicate : test
(Correct)

Consumer : accept
Function : apply
Supplier : test
Predicate : get

Consumer : apply
Function : accept
Supplier : test
Predicate : get

Consumer : apply
Function : accept
Supplier : get
Predicate : test
Explanation
It is always handy to remember the names and methods of four important built-in
functional interfaces:

Supplier<T> : T get();

Function<T, R> : R apply(T t);

Consumer<T> : void accept(T t);

Predicate<T> : boolean test(T t);

Rest of the built-in functional interfaces are either similar to or dependent upon
these four interfaces.

Question 73: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.Locale;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Locale l1 = new Locale.Builder().setLanguage("en").setRegion("US").build();
8. Locale l2 = Locale.US;
9. Locale l3 = new Locale("en");
10.  
11. System.out.println(l1.equals(l2));
12. System.out.println(l2.equals(l3));
13. }
14. }
What will be the result of compiling and executing Test class?

false
false

true
false
(Correct)


true
true

false
true
Explanation
Builder is a static nested class added in Locale class in JDK 7. 

NOTE: Builder's region is same as Locale's country. 

l1 refers to Locale object for 'en_US'. l2 also refers to Locale object for 'en_US' but l3
doesn't refer to Locale object for 'en_US'. It just refers to Locale object for 'en'.

In fact, l3.getCountry() and l3.getDisplayCountry() return blank string.

l1 and l2 are same but l3 is different.

Question 74: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate date = LocalDate.ofYearDay(2018, 32);
8. System.out.println(date);
9. }
10. }
What will be the result of compiling and executing Test class?

Runtime exception


2018-2-2


2018-2-1


2018-02-02


2018-02-01
(Correct)

Explanation
LocalDate ofYearDay(int year, int dayOfYear) returns an instance of LocalDate from a
year and day-of-year.

January has 31 days, so 32nd day of the year means 1st Feb of the given year.

Output is: '2018-02-01' as toString() method of LocalDate class prints the LocalDate
object in ISO-8601 format: "uuuu-MM-dd".

Question 75: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static <T> T get(T t) {
5. return t;
6. }
7.  
8. public static void main(String[] args) {
9. String str = get("HELLO");
10. System.out.println(str);
11. }
12. }
What will be the result of compiling and executing Test class?

HELLO
(Correct)


Compilation error in 'get' method


Compilation error in 'main' method


Runtime Exception

Explanation
Return type of generic method 'get' is T, which is correctly defined before the return
type of the method.

get("HELLO"); passed String so return value should be String only.

String result is stored in str variable and same is printed using System.out.println
statement.

Question 76: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. class MyCallable implements Callable<Integer> {
6. private Integer i;
7.  
8. public MyCallable(Integer i) {
9. this.i = i;
10. }
11.  
12. public Integer call() throws Exception {
13. return --i;
14. }
15. }
16.  
17. class MyThread extends Thread {
18. private int i;
19.  
20. MyThread(int i) {
21. this.i = i;
22. }
23.  
24. public void run() {
25. i++;
26. }
27. }
28.  
29. public class Test {
30. public static void main(String[] args) throws ExecutionException,
InterruptedException{
31. ExecutorService es = Executors.newSingleThreadExecutor();
32. MyCallable callable = new MyCallable(10);
33. MyThread thread = new MyThread(10);
34. System.out.println(es.submit(callable).get());
35. System.out.println(es.submit(thread).get());
36. es.shutdown();
37. }
38. }
What will be the result of compiling and executing Test class?

9
0

9
10

9
null
(Correct)


9
11
Explanation
Method submit is overloaded to accept both Callable and Runnable: <T> Future<T>
submit(Callable<T> task); and Future<?> submit(Runnable task); 

Both returns a Future object. call() method of MyCallable returns 9 and get() method
returns this value.

run() method of MyThread doesn't return anything, hence get() method of Future
object returns null.

Question 77: Skipped

Given code:
1. package com.udayan.ocp;
2.  
3. class Outer {
4. Outer() {
5. System.out.print(2);
6. }
7. /*INSERT 1*/
8.
9. class Inner {
10. Inner() {
11. System.out.print(4);
12. }
13. /*INSERT 2*/
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. new Outer().new Inner();
20. }
21. }
Currently on executing Test class, 24 is printed in the output. 

Which of the following pairs will correctly replace /*INSERT 1*/ and /*INSERT 2*/ so
that on executing Test class, 1234 is printed in the output?

Select 2 options.

Replace /*INSERT 1*/ with static  {System.out.print(1);}  
Replace /*INSERT 2*/ with static  {System.out.print(3);}  

Replace /*INSERT 1*/ with static  {System.out.print(1);}  
Replace /*INSERT 2*/ with  {System.out.print(3);}  
(Correct)


Replace /*INSERT 1*/ with  {System.out.print(1);}  
Replace /*INSERT 2*/ with  {System.out.print(3);}  
(Correct)


Replace /*INSERT 1*/ with  {System.out.print(1);}  
Replace /*INSERT 2*/ with static  {System.out.print(3);}  
Explanation
Regular inner class cannot define anything static, except static final variables.

So static {System.out.print(3);} will cause compilation error.

If a class contains, constructor, instance initialization block and static initialization


block and constructor is invoked, then the execution order is:

static initialization block, instance initialization block and then constructor.

Question 78: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.PrintWriter;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try(PrintWriter writer;) {
8. writer = new PrintWriter(System.out);
9. writer.println("HELLO");
10. }
11. }
12. }
What will be the result of compiling and executing Test class?

Runtime exception


Compilation error
(Correct)


HELLO

Explanation
Resources used in try-with-resources statement must be initialized.

'try(PrintWriter writer;)' causes compilation error as writer is not initialized in this


statement.

Question 79: Skipped

Given code of Test.java file:


1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4. import java.time.Month;
5. import java.time.Period;
6.  
7. public class Test {
8. public static void main(String [] args) {
9. LocalDate startDate = LocalDate.of(2018, Month.MARCH, 1);
10. LocalDate endDate = LocalDate.of(2018, Month.MARCH, 11);
11.  
12. System.out.println(Period.between(endDate, startDate));
13. }
14. }
What will be the result of compiling and executing Test class?

P-11D


P10D


P-10D
(Correct)


P11D

Explanation
Signature of Period.between method is: Period between(LocalDate startDateInclusive,
LocalDate endDateExclusive) {...}   
Difference between 1st March 2018 and 11th March 2018 is 10 days and the result of
this method is negative period as 1st argument is later date.

Question 80: Skipped

Given structure of LOG table: 


LOG (ID integer, MESSAGE varchar(1000), PRIMARY KEY (ID))  

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4. import java.util.Properties;
5.  
6. public class Test {
7. public static void main(String[] args) throws Exception {
8. String url = "jdbc:mysql://localhost:3306/ocp";
9. Properties prop = new Properties();
10. prop.put("user", "root");
11. prop.put("password", "password");
12. String query = "Select count(*) FROM LOG";
13. try (Connection con = DriverManager.getConnection(url, prop);
14. Statement stmt = con.createStatement();
15. ResultSet rs = stmt.executeQuery(query);)
16. {
17. System.out.println(rs.getInt(1));
18. }
19. }
20. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.
LOG table doesn't have any records.

What will be the result of compiling and executing Test class?


0


An exception is thrown at runtime
(Correct)


1

Explanation
As credentials are passed as java.util.Properties so user name should be passed as
"user" property and password should be passed as "password" property.

In the given code, correct property names 'user' and 'password' are used. As URL and
DB credentials are correct, hence no issues in connecting the database. 

Given query returns just one column containing no. of records, 0 in this case.

But ResultSet cursor is initially before the first record, hence 'rs.getInt(1)' throws
SQLException at runtime.

Question 81: Skipped

F: is accessible for reading/writing and below is the directory structure for F:


1. F:.
2. └───Parent
3. │ a.txt
4. │ b.txt
5. │
6. └───Child
7. c.txt
8. d.txt

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7. import java.nio.file.attribute.BasicFileAttributes;
8. import java.util.function.BiPredicate;
9. import java.util.stream.Stream;
10.  
11. public class Test {
12. public static void main(String[] args) throws IOException {
13. Path root = Paths.get("F:");
14. BiPredicate<Path, BasicFileAttributes> predicate = (p,a) ->
p.endsWith("txt");
15. try(Stream<Path> paths = Files.find(root, 2, predicate))
16. {
17. paths.forEach(System.out::println);
18. }
19. }
20. }

What will be the result of compiling and executing Test class?



Above program executes successfully and prints nothing on to the console
(Correct)


Above program executes successfully and prints below lines on to the console:
F:Parent\a.txt
F:Parent\b.txt

Above program executes successfully and prints below lines on to the console: 
F:Parent\Child\c.txt
F:Parent\Child\d.txt
F:Parent\a.txt
F:Parent\b.txt
Explanation
endsWith method is overloaded in Path interface:

boolean endsWith(Path other);

boolean endsWith(String other);

Even though endsWith(String) accepts String but it should evaluate to pathname,


such as "Child" OR "a.txt" but not just a part of pathname, such as "txt".

p.endsWith("txt") will return false for all the available paths and hence nothing will
get printed on to the console.

NOTE: If you want to find the files ending with "txt" then use
'p.toString().endsWith("txt")' in the lambda expression.

Question 82: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4. import java.util.Optional;
5. import java.util.stream.Stream;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Stream<LocalDate> stream = Stream.of(LocalDate.of(2018, 1, 1),
LocalDate.of(2018, 1, 1));
10. Optional<LocalDate> optional = stream.distinct().findAny();
11.  
12. System.out.println(optional.isPresent() + " : " + optional.get());
13. }
14. }
What will be the result of compiling and executing Test class?

true : 2018-1-1


false : 2018-1-1


true : 2018-01-01
(Correct)


false : 2018-01-01

Explanation
stream => [{2018-1-1}, {2018-1-1}]. 

stream.distinct() => [{2018-1-1}]. 

findAny() => Optional[{2018-1-1}]. 

optional.isPresent() => true. isPresent method returns true if optional is not empty
otherwise false. 

optional.get() => Returns LocalDate object {2018-1-1}, toString() method of


LocalDate class pads 0 to single digit month and day.

'true : 2018-01-01' is printed on to the console.

NOTE: In real world projects, it is advisable to check using isPresent() method before
using the get() method.

if(optional.isPresent()) {
System.out.println(optional.get());
}
Question 83: Skipped

Consider below code: 


1. //Test.java
2. package com.udayan.ocp;
3.  
4. abstract class Animal {
5. abstract void eat();
6. }
7.  
8. class Dog extends Animal {
9. public void eat() {
10. System.out.println("Dog eats biscuit.");
11. }
12. }
13.  
14. class Cat extends Animal {
15. public void eat() {
16. System.out.println("Cat eats fish.");
17. }
18. }
19.  
20.  
21. public class Test {
22. public static void main(String[] args) {
23. Animal [] animals = new Dog[2];
24. animals[0] = new Dog();
25. animals[1] = new Cat();
26.  
27. animals[0].eat();
28. animals[1].eat();
29. }
30. }
What will be the result of compiling and executing Test class?

Runtime exception
(Correct)


Dog eats biscuit.
Cat eats fish.

None of the other options.


Compilation error

Explanation
Dog and Cat are siblings as both extend from Animal class.

animals refer to an instance of Dog [] type. Each element of Dog [] can store Dog
instances and not Cat instances.

But as we are using reference variable of Animal [] type hence compiler allows to add
both Cat and Dog instances.
So, animals[0] = new Dog(); and animals[1] = new Cat(); don't cause any compilation
error.

But at runtime, while executing the statement: "animals[1] = new Cat();", a Cat
instance is assigned to Dog array's element hence java.lang.ArrayStoreException is
thrown.

Question 84: Skipped

Consider the code of Test.java file:


1. package com.udayan.ocp;
2.  
3. class Calculator {
4. public static void add(int x, int y) {
5. System.out.println("The sum is: " + x + y);
6. }
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. Calculator.add(15, 25);
12. }
13. }
What will be the result of compiling and executing Test class?

The sum is: 40


Compilation error


The sum is: 1525
(Correct)

Explanation
Operator + is left to right associative, so given expression can be grouped as:

"The sum is: " + x + y

= ("The sum is: " + x) + y

= (("The sum is: " + x) + y)

= (("The sum is: " + 15) + 25)

= ("The sum is: 15" + 25)


= "The sum is: 1525"

Question 85: Skipped

Which of the following problems can be efficiently solved using Fork/Join framework?


Problems that can be divided into sub tasks, where each sub-task can be
computed independently in asynchronous manner
(Correct)


Problems that has lots of File Input/Output activities

Problems that can be divided into sub tasks, where each sub-task can be
computed independently in synchronous manner
Explanation
Fork/Join framework is for the problems that can be divided into sub tasks and result
of computation can be combined later. Each sub-task should be computed
independently without depending upon other tasks and result can be combined
later.

Input/Output operations may block and hence this framework is not suitable for any
type of I/O operations.

Synchronization defeats the purpose of fork/join framework to compute the tasks in


parallel.

Question 86: Skipped

Given code of 3 Java files:


1. //1. MyResourceBundle.java
2. package com.udayan.ocp;
3.  
4. import java.util.ListResourceBundle;
5.  
6. public class MyResourceBundle extends ListResourceBundle {
7. @Override
8. protected Object[][] getContents() {
9. Object [][] arr = {{"surprise", "SURPRISE!"}};
10. return arr;
11. }
12. }

1. //2. MyResourceBundle_en_CA.java
2. package com.udayan.ocp;
3.  
4. import java.util.ListResourceBundle;
5.  
6. public class MyResourceBundle_en_CA extends ListResourceBundle {
7. @Override
8. protected Object[][] getContents() {
9. Object [][] arr = {{"surprise", 12.64}};
10. return arr;
11. }
12. }

1. //3. Test.java
2. package com.udayan.ocp;
3.  
4. import java.util.Locale;
5. import java.util.ResourceBundle;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Locale.setDefault(new Locale("fr", "IT"));
10. Locale loc = new Locale("en", "US");
11. ResourceBundle rb =
ResourceBundle.getBundle("com.udayan.ocp.MyResourceBundle", loc);
12. System.out.println(rb.getObject("surprise"));
13. }
14. }
What will be the result of compiling and executing Test class?

12.64


1001


SURPRISE!
(Correct)


MissingResourceException is thrown at runtime

Explanation
The search order for matching resource bundle is:

com.udayan.ocp.MyResourceBundle_en_US [1st: Complete, en_US]. 

com.udayan.ocp.MyResourceBundle_en [2nd: Only language, en]. 

com.udayan.ocp.MyResourceBundle_fr_IT [3rd: Complete Default Locale, fr_IT]. 

com.udayan.ocp.MyResourceBundle_fr [4th: Language of Default Locale, fr]. 

com.udayan.ocp.MyResourceBundle [5th: ResourceBundle's name without language


or country].
If search reaches the 5th step and no matching resource bundle is found, then
MissingResourceException is thrown at runtime.

In 5th step, matching resource bundle is found and hence 'SURPRISE!' is printed on
to the console.

Question 87: Skipped

Which of the following correctly specifies the entries in resource bundle properties
file?


1. country=Sri Lanka
2. continent=Asia
(Correct)


country=Sri Lanka:continent=Asia  


1. country="Sri Lanka"
2. continent="Asia"

country=Sri Lanka;continent=Asia  
Explanation
Format of resource bundle properties file is:

key1=value1

key2=value2

There must be a newline between 2 pairs of key and value. Colon(:) and Semicolon(;)
are not used as separators.

Even if value has space in between, double quotes are not used.

NOTE: Generally as a good convention spaces in keys are not OK but if you have to
have the space, then escape it properly.

country name=Sri Lanka => NOT OK. 


country\ name=Sri Lanka => OK. 

Question 88: Skipped

Given code of Test.java file: 


1. package com.udayan.ocp;
2.  
3. import java.io.FileNotFoundException;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. try {
8. System.out.println(1);
9. } catch (NullPointerException ex) {
10. System.out.println("ONE");
11. } catch (FileNotFoundException ex) {
12. System.out.println("TWO");
13. }
14. System.out.println("THREE");
15. }
16. }
What will be the result of compiling and executing Test class?

TWO
THREE

None of the System.out.println statement is executed


THREE


ONE
THREE

Compilation error
(Correct)

Explanation
Java doesn't allow to catch specific checked exceptions if these are not thrown by the
statements inside try block.

catch(FileNotFoundException ex) {} causes  compilation error in this case as


System.out.println(1); will never throw FileNotFoundException.

NOTE: Java allows to catch Exception type. catch(Exception ex) {} will never cause
compilation error.
Question 89: Skipped

Given structure of EMPLOYEE table: 


EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
11.  
12. try (Connection con = DriverManager.getConnection(url, user, password);
13. Statement stmt = con.createStatement();
14. ResultSet rs = stmt.executeQuery(query);) {
15. rs.absolute(3);
16. rs.relative(-1);
17. rs.deleteRow();
18. }
19. }
20. }

Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


Record corresponding to ID 103 is deleted successfully

Record corresponding to ID 102 is deleted successfully

Record corresponding to ID 101 is deleted successfully

Record corresponding to ID 104 is deleted successfully

An exception is thrown at runtime
(Correct)

Explanation
By default ResultSet is not updatable. 

'rs.deleteRow();' throws an exception at runtime.

To update the ResultSet in any manner (insert, update or delete), the ResultSet must
come from a Statement that was created with a ResultSet type of
ResultSet.CONCUR_UPDATABLE.

NOTE: If you want to successfully delete the row, then replace


'con.createStatement();' with

'con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);'

OR

'con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);'

Question 90: Skipped

F: is accessible for reading/writing and below is the directory structure for F:


1. F:.
2. └───A
3. └───B
4. Book.java
      
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.File;
4. import java.io.IOException;
5. import java.nio.file.*;
6.  
7. public class Test {
8. public static void main(String[] args) throws IOException{
9. Path path = Paths.get("F:\\A\\B\\Book.java");
10. long size1 = Files.size(path);
11.  
12. File file = new File("F:\\A\\B\\Book.java");
13. long size2 = file.length();
14.  
15. System.out.println(size1 == size2);
16. }
17. }

What will be the result of compiling and executing Test class?


true
(Correct)


false


Compilation error

Explanation
static method Files.size(path) method is equivalent to instance method length()
defined in java.io.File class.

Both returns length of the file, in bytes.

Practice Test 6 - Results

 Return to review
Skipped100.0%
Attempt 1
All knowledge areas
All questions
Question 1: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.OptionalLong;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. OptionalLong optional = OptionalLong.empty();
8. System.out.println(optional.isPresent() + " : " + optional.getAsLong());
9. }
10. }

What will be the result of compiling and executing Test class?



Runtime Exception
(Correct)


true : 0


false : 0


true : null


false : null

Explanation
In this case, value variable inside Optional instance is null.

optional.isPresent() => false. isPresent method returns true if optional is not empty
otherwise false. 

If value variable inside Optional instance is null (empty optional), then


NoSuchElementException is thrown at runtime.
In real world projects, it is advisable to to check using isPresent() method before
using the get() method.

if(optional.isPresent()) {
System.out.println(optional.getAsLong());
}

NOTE: There are 3 primitive equivalents of Optional<T> interface available.


Remember their similarity with Optional<T> class.

Optional<T>:

Optional<T> empty(),

T get(),

boolean isPresent(),

Optional<T> of(T),

void ifPresent(Consumer<? super T>),

T orElse(T),

T orElseGet(Supplier<? extends T>),

T orElseThrow(Supplier<? extends X>),

Optional<T> filter(Predicate<? super T>),

Optional<U> map(Function<? super T, ? extends U>),

Optional<U> flatMap(Function<? super T, Optional<U>>).

OptionalInt:

OptionalInt empty(),

int getAsInt(),
boolean isPresent(),

OptionalInt of(int),

void ifPresent(IntConsumer),

int orElse(int),

orElseGet(IntSupplier),

int orElseThrow(Supplier<X>).

[filter, map and faltMap methods are not available in primitive type].

OptionalLong:

OptionalLong empty(),

long getAsLong(),

boolean isPresent(),

OptionalLong of(long),

void ifPresent(LongConsumer),

long orElse(long),

long orElseGet(LongSupplier),

long orElseThrow(Supplier<X>).

[filter, map and faltMap methods are not available in primitive type].

OptionalDouble:

OptionalDouble empty(),

double getAsDouble(),

boolean isPresent(),
OptionalDouble of(double),

void ifPresent(DoubleConsumer),

double orElse(double),

double orElseGet(DoubleSupplier),

double orElseThrow(Supplier<X>).

[filter, map and faltMap methods are not available in primitive type].

Question 2: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream<String> stream = Stream.of("J", "A", "V", "A");
8. String text = stream.parallel().reduce(String::concat).get();
9. System.out.println(text);
10. }
11. }

What will be the result of compiling and executing Test class?



It will always print JAVA on to the console
(Correct)


None of the other options


Output cannot be predicted

Explanation
reduce method in Stream class is declared as: 'Optional<T>
reduce(BinaryOperator<T> accumulator);'

'String::concat' is equivalent to lambda expression '(s1, s2) -> s1.concat(s2);'.

By checking the reduce method, 'reduce(String::concat)' we can say that:

accumulator is BinaryOperator<String> type.


To get consistent output, accumulator must be associative and stateless. concat is
associative as (s1.concat(s2)).concat(s3) equals to s1.concat(s2.concat(s3)). Given
method reference syntax is stateless as well.

Hence, reduce will give the same result for both sequential and parallel stream.

As per Javadoc, given reduce method is equivalent to:

boolean foundAny = false;


T result = null;
for (T element : this stream) {
if (!foundAny) {
foundAny = true;
result = element;
}
else
result = accumulator.apply(result, element);
}
return foundAny ? Optional.of(result) : Optional.empty();

This means, output will be JAVA.

Question 3: Skipped
F: is currently blank and accessible for Reading/Writing. 

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7.  
8. public class Test {
9. public static void main(String[] args) throws IOException {
10. Path path = Paths.get("F:", "A", "B", "File.txt");
11.  
12. /*INSERT*/
13. }
14. }

Test.class file is under 'C:\classes\com\udayan\ocp'. 


Which of the following statements, if used to replace /*INSERT*/, will successfully
create the file "File.txt" under F:\A\B directory?


1. Files.createDirectories(path.getParent());
2. Files.createFile(path);

(Correct)


1. Files.createDirectories(path);
2. Files.createFile(path);


1. Files.createDirectories(path.getParent());
2. Files.createFile(path.getFileName());

Files.createFile(path);  

Explanation
Files.createFile(path); => throws IOException as parent directories don't exist. 

Files.createDirectories(path); => Creates the directories 'A', 'B' and 'File.txt'. Path after
creation is: 'F:\A\B\File.txt\'. 

Files.createFile(path); => FileAlreadyExistsException as directory with the same


name already exists.   

path.getParent() returns 'F:\A\B', which is an absolute path and path.getFileName()


returns 'File.txt', which is a relative path. 

Files.createDirectories(path.getParent()); => Creates the directories 'A' and 'B'. Path


after creation is: 'F:\A\B\'. 

Files.createFile(path.getFileName()); => Creates the file under current directory, Path


after creation is: 'C:\classes\com\udayan\ocp\File.txt'. 

Files.createDirectories(path.getParent()); => Creates the directories 'A' and 'B'. Path


after creation is: 'F:\A\B\'. 

Files.createFile(path); => Creates the file, 'File.txt' under 'F:\A\B\'. Path after creation
is: 'F:\A\B\File.txt'.
Question 4: Skipped
Given code of Test.java file:
1. import java.io.*;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. Console console = System.console();
6. if(console != null) {
7. console.format("%d %x", 10);
8. }
9. }
10. }

What will be the output of compiling and executing Test class from command
prompt?

javac Test.java

java Test


10


10 12


10 a


Runtime Exception
(Correct)


10 10

Explanation
console.format("%d %x", 10); => There are 2 format specifiers (%d and %x) in the
format string but only one argument (10) is passed.

MissingFormatArgumentException is thrown at runtime.

NOTE: console.format(...) and console.printf(...) methods are same.

In fact, printf(...) method invokes format(...) method.

Question 5: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. interface I1 {
4. void print();
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. I1 obj = () -> System.out.println("Hello");
10. }
11. }


Runtime error


Program compiles and executes successfully but nothing is printed on to the
console
(Correct)


Hello


Compilation error

Explanation
Lambda expression is defined correctly but print() method is not invoked on obj
reference.

So, no output.

Question 6: Skipped
Which of the import statements correctly imports the functional interface
Comparator?

import java.util.function.Comparator;  


import java.util.Comparator;  
(Correct)


import java.function.Comparator;  


import java.lang.Comparator;  

Explanation
java.util.Comparator interface is available with Java since JDK 1.2.
So, even though it is a functional interface but Java guys didn't move it to
java.util.function package.

Had Comparator interface moved to java.util.function package, then millions of lines


of existing Java codes would have broken. That's why package of all the existing
functional interface was not changed.

Question 7: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.UnaryOperator;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. final String password = "Oracle";
8. UnaryOperator<String> opr1 = s -> s.replace('a', '@'); //Line n1
9. UnaryOperator<String> opr2 = s -> password.concat(s); //Line n2
10. System.out.println("Password: " + opr1.apply(opr2.apply("!"))); //Line n3
11. }
12. }

What will be the result of compiling and executing Test class?



Password: Or@cle!
(Correct)


Compilation error at Line n1


Compilation error at Line n3


Password: Oracle!


Compilation error at Line n2

Explanation
interface UnaryOperator<T> extends Function<T, T>, so its apply function has the
signature: T apply(T).

In this case, UnaryOperator<String> is used and hence apply method will have the
signature: String apply(String).

Lambda expression 's -> s.replace('a', '@')' is the correct implementation of 'String
apply(String)' method and hence there is no issue with Line n1.
Lambda expression 's -> str.concat(s)' is also the correct implementation of 'String
apply(String)' method. Don't get confused with final modifier being used for 'str'
reference, it is safe to invoke methods on final reference variable but yes you can't
assign another String object to final reference variable. By invoking str.concat(s) a
new String object is returned. So, no there is no issue with Line n2 as well.

Let's solve Line n3:

System.out.println("Password: " + opr1.apply(opr2.apply("!"))); 

System.out.println("Password: " + opr1.apply("Oracle!")); //opr2.apply("!") returns


"Oracle!" 

System.out.println("Password: " + "Or@cle!"); //opr1.apply("Oracle!") returns


"Or@cle!" 

Hence, output is: Password: Or@cle!

Question 8: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream<Double> stream = Stream.generate(() -> new Double("1.0"));
8. System.out.println(stream.sorted().findFirst());
9. }
10. }

What will be the result of compiling and executing Test class?



Optional[1.0] is printed and program runs infinitely


Optional[1.0] is printed and program terminates successfully


Nothing is printed and program runs infinitely
(Correct)


Compilation error

Explanation
Stream.generate(() -> new Double("1.0")); generates an infinite stream of Double,
whose elements are 1.0.
stream.sorted() is an intermediate operation and needs all the elements to be
available for sorting.

As all the elements of infinite stream are never available, hence sorted() method
never completes.

So among all the available option, correct option is: 'Nothing is printed and program
runs infinitely.'

Question 9: Skipped
Which of the following method a concrete class must override if it extends from
ListResourceBundle?

abstract protected String[][] getContents();  


abstract protected Object[][] getContents();  
(Correct)


abstract protected Object[] getContents();  


abstract protected String[] getContents();  

Explanation
ListResourceBundle has one abstract method: 'abstract protected Object[][]
getContents();'.

All the concrete sub classes of ListResourceBundle must override this method.

Question 10: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. enum Status {
4. PASS, FAIL, PASS;
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. System.out.println(Status.FAIL);
10. }
11. }


FAIL

None of the other options
(Correct)


fail


Fail

Explanation
enum Status will cause compilation error as constant name should be unique, but
PASS is declared twice.
Question 11: Skipped
Which of the following classes support time zone?

LocalTime


LocalDate


ZonedDateTime
(Correct)


LocalDateTime

Explanation
LocalDate, LocalTime and LocalDateTime don't have concepts of time zones.

ZonedDateTime class is used for time zones.

Question 12: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.LongStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. LongStream.iterate(0, i -> i + 2).limit(4).forEach(System.out::print);
8. }
9. }

What will be the result of compiling and executing Test class?



0246
(Correct)

02


024


02468

Explanation
LongStream.iterate(long seed, LongUnaryOperator f) => 'seed' is the initial element
and 'f' is a function to be applied to the previous element to produce a new element.

LongUnaryOperator is a functional interface and has method 'long applyAsLong(long


operand);'. This means lambda expression should accept long parameter and return
long value.

'i -> i + 2' is the correct lambda expression.

LongStream.iterate(0, i -> i + 2) => This results in an infinite stream consisting of


elements [0,2,4,6,8,10,12,...]

limit(4) => Returns a stream consisting of 4 elements [0,2,4,6] from the given
stream. 

Hence, the output is: 0246

Question 13: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path file1 = Paths.get("F:\\A\\B");
9. Path file2 = Paths.get("F:\\A\\B\\C\\Book.java");
10.
System.out.println(file1.resolve(file2).equals(file1.resolveSibling(file2)));
11. }
12. }
What will be the result of compiling and executing Test class?

false


true
(Correct)

Explanation
As file2 refers to an absolute path and not relative path, hence both
'file1.resolve(file2)' and 'file1.resolveSibling(file2)' returns Path object referring to
'F:\A\B\C\Book.java'.

equals method returns true in this case.

Question 14: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class TestException extends Exception {
4. public TestException() {
5. super();
6. }
7.
8. public TestException(String s) {
9. super(s);
10. }
11. }
12.  
13. public class Test {
14. public void m1() throws __________ {
15. throw new TestException();
16. }
17. }

For the above code, fill in the blank with one option.

Error


RuntimeException


Object


Exception
(Correct)

Explanation
Method m1() throws an instance of TestException, which is a checked exception as
it extends Exception class.
So in throws clause we must provide:

1. Checked exception.

2. Exception of TestException type or it's super types (Exception, Throwable), Object


cannot be used in throws clause.

Question 15: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static final <X extends Integer, Y extends Integer> void add(X x, Y y)
{
5. System.out.println(x + y);
6. }
7.  
8. public static void main(String[] args) {
9. add(10, 20);
10. }
11. }

What will be the result of compiling and executing Test class?



1020


30
(Correct)


Compilation error


Runtime Exception

Explanation
If a generic method is defined in a non-generic class then type parameters must
appear before the return type of the method.

Integer is also a final class so parameters X and Y can only be of Integer type.

add(10, 20); => Auto-boxing converts int literals to Integer objects. 30 is printed on to
the console.

Question 16: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.BiFunction;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. BiFunction<Double, Double, Integer> compFunc = Double::compareTo;
8. System.out.println(compFunc.apply(10.01, 11.99));
9. }
10. }

What will be the result of compiling and executing Test class?



0


-1
(Correct)


-2


Compilation error


2


1

Explanation
BiFunction<T, U, R> : R apply(T t, U u);

BiFunction interface accepts 3 type parameters, first 2 parameters (T,U) are passed
to apply method and 3rd type parameter is the return type of apply method.

In this case, 'BiFunction<Double, Double, Integer>' means apply method will have
declaration: 'Integer apply(Double d1, Double d2)'.

Lambda expression should accept 2 Double type parameters and must return Integer
object. Lambda expression is:
(d1, d2) -> d1.compareTo(d2); and corresponding method reference syntax is:
'Double::compareTo'.

This is an example of "Reference to an Instance Method of an Arbitrary Object of a


Particular Type" and not "method reference to static method".

If d1 < d2, then -1 is returned and if d1 > d2, then 1 is returned.

Question 17: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Set<String> set = new HashSet<>(Arrays.asList(null,null,null));
8. long count = set.stream().count();
9. System.out.println(count);
10. }
11. }

What will be the result of compiling and executing Test class?



Runtime exception


3


0


1
(Correct)

Explanation
HashSet cares about uniqueness and allows 1 null value.
Question 18: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.function.IntConsumer;
4. import java.util.stream.IntStream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. IntConsumer consumer = i -> i * i * i;
9. int result = IntStream.range(1, 5).sum();
10. System.out.println(result);
11. }
12. }

What will be the result of compiling and executing Test class?



Runtime Exception


Compilation error
(Correct)


225


100

Explanation
IntConsumer has single abstract method, 'void accept(int value);'.

accept(int) method doesn't return anything.

Lambda expression 'i -> i * i * i' returns an int value and hence given lambda
expression causes compilation failure.

Question 19: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. String [] arr1 = {"Virat", "Rohit", "Shikhar", "Dhoni"};
9. String [] arr2 = {"Bumrah", "Pandya", "Sami"};
10. String [] arr3 = {};
11.  
12. Stream<String[]> stream = Stream.of(arr1, arr2, arr3);
13. stream.flatMap(s -> Arrays.stream(s)).sorted().forEach(s ->
System.out.print(s + " "));
14. }
15. }

What will be the result of compiling and executing Test class?



null Bumrah Dhoni Pandya Rohit Sami Shikhar Virat

Virat Rohit Shikhar Dhoni Bumrah Pandya Sami null


Bumrah Dhoni Pandya Rohit Sami Shikhar Virat
(Correct)


Bumrah Dhoni Pandya Rohit Sami Shikhar Virat null


Virat Rohit Shikhar Dhoni Bumrah Pandya Sami

Explanation
stream is not of Stream<String> type rather it is of Stream<String[]> type.

flatMap method combines all the non-empty streams and returns an instance of
Stream<String> containing the individual elements from non-empty stream.

stream => [{"Virat", "Rohit", "Shikhar", "Dhoni"}, {"Bumrah", "Pandya", "Sami"}, {}]. 

stream.flatMap(s -> Arrays.stream(s)) => ["Virat", "Rohit", "Shikhar", "Dhoni", "Bumrah",


"Pandya", "Sami"].

sorted() => ["Bumrah", "Dhoni", "Pandya", "Rohit", "Sami", "Shikhar", "Virat"].

Question 20: Skipped
To efficiently use fork/join framework, after invoking fork() on first subtask, the
order of invoking join() and compute() is as follows:

Invoke join() on 1st subtask and then compute() on 2nd subtask


Invoke join() on 2nd subtask and then compute() on 1st subtask


Invoke compute() on 2nd subtask and then join() on 1st subtask
(Correct)


Invoke compute() on 1st subtask and then join() on 2nd subtask

Explanation
After invoking fork() on 1st subtask, it is necessary to invoke join() on 1st subtask
and compute() on 2nd subtask.
The order of execution of calling join() and compute() on divided subtasks is
important in a fork/join framework.

First invoke compute() on 2nd subtask and then join() on 1st subtask.

Question 21: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4. import java.time.format.DateTimeFormatter;
5.  
6. public class Test {
7. public static void main(String [] args) {
8. LocalDate date = LocalDate.of(2018, 11, 4);
9. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("DD-MM-uuuu");
10. System.out.println(formatter.format(date));
11. }
12. }

What will be the result of compiling and executing Test class?



04-11-2018


Runtime Exception
(Correct)


Compilation Error

Explanation
D represents day-of-year and DD is for printing 2 digits. If you calculate, day of the
year for 4th Nov 2018, it will be of 3 digit value as year has 365 days and date is in
November month.

Pattern DD (for 2 digits) will cause Runtime Exception in this case.

If you get confused with pattern letters in lower case and upper case, then easy way
to remember is that Bigger(Upper case) letters represent something bigger.

M represents month & m represents minute, D represents day of the year & d
represents day of the month.
Question 22: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.Collections;
5. import java.util.List;
6. import java.util.stream.IntStream;
7.  
8. public class Test {
9. public static void main(String[] args) {
10. List<Integer> list = Collections.synchronizedList(new ArrayList<>());
11. IntStream stream = IntStream.rangeClosed(1, 7);
12. stream.parallel().map(x -> {
13. list.add(x); //Line 13
14. return x;
15. }).forEachOrdered(System.out::print); //Line 15
16. System.out.println();
17. list.forEach(System.out::print); //Line 17
18. }
19. }

Which of the following statement is true about above code?



Output of Line 15 can be predicted
(Correct)


Line 15 and Line 17 will print exact same output on to the console


Output of both Line 15 and Line 17 can be predicted


Line 15 and Line 17 will not print exact same output on to the console


Output of Line 17 can be predicted

Explanation
Line 13 is changing the state of list object and hence it should be avoided in parallel
stream. You can never predict the order in which elements will be added to the
stream.

Line 13 and Line 15 doesn't run in synchronized manner, hence as the result, output
of Line 17 may be different from that of Line 15.
forEachOrdered() will processes the elements of the stream in the order specified by
its source, regardless of whether the stream is sequential or parallel.

As forEachOrdered() method is used at Line 15, hence Line 15 will always print
'1234567' on to the console.

On my machine below is the output of various executions:

Execution 1:

1234567

1352764

Execution 2:

1234567

6514327

Execution 3:

1234567

1732645

Question 23: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.sql.SQLException;
4.  
5. public class Test {
6. private static void m() throws SQLException {
7. throw null; //Line 7
8. }
9.  
10. public static void main(String[] args) {
11. try {
12. m(); //Line 12
13. } catch(SQLException e) {
14. System.out.println("Caught Successfully.");
15. }
16. }
17. }

What will be the result of compiling and executing Test class?



Caught Successfully


Line 7 causes compilation failure


Line 12 causes compilation failure


Program ends abruptly
(Correct)

Explanation
Classes in Exception framework are normal java classes, hence null can be used
wherever instances of Exception classes are used, so Line 7 compiles successfully.

No issues with Line 12 as method m() declares to throw SQLException and main
method code correctly handles it.

Program compiles successfully but on execution, NullPointerException is thrown,


stack trace is printed on to the console and program ends abruptly.

If you debug the code, you would find that internal routine for throwing null exception
causes NullPointerException.

Question 24: Skipped
Consider the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. abstract class Animal {
4. public static void vaccinate() {
5. System.out.println("Vaccinating...");
6. }
7.  
8. private abstract void treating();
9. }
10.  
11. public class Test {
12. public static void main(String[] args) {
13. Animal.vaccinate();
14. }
15. }
What will be the result of compiling and executing Test class?

Compilation error in Animal class
(Correct)


Compilation error in Test class


Vaccinating...

Explanation
'abstract' and 'private' cannot be used together.
Question 25: Skipped
Given:
1. package com.udayan.ocpjp;
2.  
3. import java.util.Arrays;
4. import java.util.List;
5. import java.util.function.UnaryOperator;
6.  
7. public class Test {
8. public static void main(String[] args) {
9. /* INSERT */
10. List<Character> vowels = Arrays.asList('A', 'E', 'I', 'O', 'U');
11. vowels.stream().map(x -> operator.apply(x)).forEach(System.out::print);
//Line n1
12. }
13. }

Line n1 is causing compilation error as variable 'operator' is not found.

Which of the following two options can replace /* INSERT */ such that output is:
BFJPV?


Function<Character, Integer> operator = x -> x + 1;


UnaryOperator<Character> operator = c -> (char)(c.charValue() + 1);
(Correct)


Function<Character, Character> operator = x -> (char)(x + 1);
(Correct)


UnaryOperator<Character> operator = c -> c + 1;


UnaryOperator<Character> operator = c -> c.charValue() + 1;

UnaryOperator<Integer> operator = c -> c + 1;

Explanation
As 'vowels' refers to List<Character>, hence vowels.stream() returns
Stream<Character> type. So, map method of Stream<Character> type has signature:
<R> Stream<R> map(Function<? super Character, ? extends R> mapper);

Since forEach(System.out::print) is printing BFJPV, hence result of map(x ->


operator.apply(x)) should be Stream<Character> and not Stream<Integer>.

This means correct reference type of 'operator' variable is Function<Character,


Character>. Now as UnaryOperator<T> extends Function<T, T>, so
UnaryOpeartor<Character> is also correct reference type of 'operator' variable.

Out of 6, we are left with 4 options. Let's check the options one by one:

'UnaryOperator<Character> operator = c -> c + 1;': 'c + 1' results in int and int can be
converted to Integer but not Character, so this causes compilation failure.

'UnaryOperator<Character> operator = c -> c.charValue() + 1;': 'c.charValue() + 1'


results in int and int can be converted to Integer but not Character, so this causes
compilation failure.

'UnaryOperator<Character> operator = c -> (char)(c.charValue() + 1);': This


expression adds 1 to the current char value (primitive char is compatible with
primitive int) and resultant int value is type-casted to char, which is converted to
Character by auto-boxing. Hence, this is correct option.

'Function<Character, Character> operator = x -> (char)(x + 1);': This is also correct


option. x + 1 results in int, which is type-casted to char and finally converted to
Character by auto-boxing.

Question 26: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. class Student implements Serializable {
6. private String name;
7. private int age;
8.  
9. Student(String name, int age) {
10. this.name = name;
11. this.age = age;
12. }
13.  
14. public String getName() {
15. return name;
16. }
17.  
18. public int getAge() {
19. return age;
20. }
21.  
22. public void setName(String name) {
23. this.name = name;
24. }
25.  
26. public void setAge(int age) {
27. this.age = age;
28. }
29. }
30.  
31. public class Test {
32. public static void main(String[] args) throws IOException,
ClassNotFoundException {
33. Student stud = new Student("John", 20);
34.  
35. try( ObjectOutputStream oos = new ObjectOutputStream(
36. new FileOutputStream("C:\\Student.dat")) ){
37. oos.writeObject(stud);
38. }
39.  
40. stud.setName("James");
41. stud.setAge(21);
42.  
43. try( ObjectInputStream ois = new ObjectInputStream(
44. new FileInputStream("C:\\Student.dat")) ){
45. stud = (Student)ois.readObject();
46. System.out.printf("%s : %d", stud.getName(), stud.getAge());
47. }
48. }
49. }

There is full permission to list/create/delete files and directories in C:.

What will be the result of compiling and executing Test class?


Runtime Exception


James : 21


John : 20
(Correct)

Explanation
Student class implements Serializable, hence objects of Student class can be
serialized using ObjectOutputStream.

setName() and setAge() are called after executing 'oos.writeObject(stud);' hence


these are not reflected in the serialized data.

On de-serializing, persisted Student data is printed on to the console.

Question 27: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. class Employee {
6. private String name;
7. private double salary;
8.  
9. public Employee(String name, double salary) {
10. this.name = name;
11. this.salary = salary;
12. }
13.  
14. public String getName() {
15. return name;
16. }
17.  
18. public double getSalary() {
19. return salary;
20. }
21.  
22. public String toString() {
23. return "{" + name + ", " + salary + "}";
24. }
25.  
26. public static int salaryCompare(double d1, double d2) {
27. return new Double(d2).compareTo(d1);
28. }
29. }
30.  
31. public class Test {
32. public static void main(String[] args) {
33. Stream<Employee> employees = Stream.of(new Employee("Jack", 10000),
34. new Employee("Lucy", 12000), new Employee("Tom", 7000));
35.
36. highestSalary(employees);
37. }
38.  
39. private static void highestSalary(Stream<Employee> emp) {
40. System.out.println(emp.map(e ->
e.getSalary()).max(Employee::salaryCompare));
41. }
42. }

What will be the result of compiling and executing Test class?



Optional[10000.0]


Optional[7000.0]
(Correct)


Optional.empty


Optional[12000.0]

Explanation
In real exam, don't predict the output by just looking at the method name.

It is expected that highestSalary(...) method will print 'Optional[12000.0]' on to the


console but if you closely check the definition of Employee.salaryCompare(...)
method you will note that it helps to sort the salary in descending order and not
ascending order.

Rest of the logic is pretty simple.

emp => [{"Jack", 10000.0}, {"Lucy", 12000.0}, {"Tom", 7000.0}]. 

emp.map(e -> e.getSalary()) => [10000.0, 12000.0, 7000.0]. 

max(Employee::salaryCompare) => Optional[7000]. 

NOTE: There are 3 methods in Stream interface, which returns Optional<T> type: 

1. Optional<T> max(Comparator<? super T> comparator); 


2. Optional<T> min(Comparator<? super T> comparator); 

3. Optional<T> reduce(BinaryOperator<T> accumulator); 

Question 28: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. interface I6 {
4. void m6();
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. I6 obj = () -> {
10. int i = 10;
11. i++;
12. System.out.println(i);
13. };
14. obj.m6();
15. }
16. }


11
(Correct)


Compilation error


10


Exception is thrown at runtime

Explanation
No issues with lambda syntax: curly brackets and semicolon are available. 

Variable i is declared within the body of lambda expression so don't confuse it with
local variable of main method. 

i is declared and initialized to 10, i is incremented by 1 (i becomes 11) and finally


value of i is printed.

Question 29: Skipped
F: is accessible for reading and below is the directory structure for F:
1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java
'Book.java' file is available under 'C' directory.

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path file = Paths.get("F:\\A\\.\\B\\C\\D\\..\\Book.java");
9. System.out.println(file.toAbsolutePath());
10. }
11. }

What will be the result of compiling and executing Test class?


NoSuchFileException is thrown at runtime


Compilation Error


Book.java


F:\A\B\C\Book.java


F:\A\.\B\C\D\..\Book.java
(Correct)

Explanation
toAbsolutePath() method doesn't care if given path elements are physically available
or not and hence it doesn't declare to throw IOException.

It just returns the absolute path without any normalization. 

'F:\A\.\B\C\D\..\Book.java' is displayed on to the console.

Question 30: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Stream<String> stream = Stream.of("a", "as", "an", "and");
9. Optional<String> first = stream.findFirst();
10. if(first.ifPresent()) {
11. System.out.println(first.get());
12. }
13. }
14. }

What will be the result of compiling and executing Test class?



Any element from the stream is printed


a


Runtime Exception


Compilation error
(Correct)

Explanation
Method isPresent() returns boolean whereas method ifPresent accepts a Consumer
parameter.

'first.ifPresent()' causes compilation failure.

Question 31: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.io.*;
4.  
5. class Person {
6. private String name;
7. private int age;
8.  
9. public Person(){}
10.
11. public Person(String name, int age) {
12. this.name = name;
13. this.age = age;
14. }
15.  
16. public String getName() {
17. return name;
18. }
19.  
20. public int getAge() {
21. return age;
22. }
23. }
24.  
25. class Student extends Person implements Serializable {
26. private String course;
27.  
28. public Student(String name, int age, String course) {
29. super(name, age);
30. this.course = course;
31. }
32.  
33. public String getCourse() {
34. return course;
35. }
36. }
37.  
38. public class Test {
39. public static void main(String[] args) throws IOException,
ClassNotFoundException {
40. Student stud = new Student("John", 20, "Computer Science");
41. try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(("F:\\stud.ser")));
42. ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("F:\\stud.ser")))
43. {
44. oos.writeObject(stud);
45.  
46. Student s = (Student) ois.readObject();
47. System.out.printf("%s, %d, %s", s.getName(), s.getAge(),
s.getCourse());
48. }
49. }
50. }

F: is accessible for reading/writing and currently doesn't contain any


files/directories. 

What will be the result of compiling and executing Test class?


John, 20, Computer Science


null, 0, Computer Science
(Correct)


Runtime Exception


null, 0, null

Explanation
Class Student implements Serializable but it's super class Person is not Serializable.
While de-serializing of Serializable class, constructor of that class is not invoked.

But if Parent class is not Serializable, then to construct the Parent class object, a no-
argument constructor in Parent class is needed. This no-argument constructor
initializes the properties to their default values.

Person class has no-argument constructor. So while de-serialization name and age
are initialized to their default values: null and 0 respectively.

course refers to "Computer Science" as it belongs to Serializable class, Student.

In the output, you get 'null, 0, Computer Science'.

Question 32: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String [] names = {"Peter", "bonita", "John"};
8. Arrays.stream(names).sorted((s1, s2) -> s1.compareToIgnoreCase(s2))
9. .forEach(System.out::println);
10. }
11. }

What will be the result of compiling and executing Test class?



Peter
bonita
John


John
bonita
Peter


bonita
John
Peter
(Correct)


John
Peter
bonita

Explanation
In this example, Stream<String> is used. sorted method accepts Comparator<? super
String> type.

compareToIgnoreCase is defined in String class and it compares the text by in case-


insensitive manner.

Even though 'b' is in lower case it is printed first, followed by 'J' and 'P'.

Question 33: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. System.out.println(LocalDate.of(2018, 6, 6)
8. .plus(Period.parse("P9M")));
9. }
10. }

What will be the result of compiling and executing Test class?



2018-03-06


2019-3-6


2018-3-6


2019-03-06
(Correct)

Explanation
Period.parse(CharSequence) method accepts the String parameter in "PnYnMnD"
format, over here P,Y,M and D can be in any case.

"P9M" represents period of 9 months.


Signature of plus method of LocalDate is: 'LocalDate plus(TemporalAmount)', Period
implements ChronoPeriod and ChnonoPeriod extends TemporalAmount.

Hence Period type can be passed as an argument of plus method. Adding 9 months
to 6th June 2018 returns 6th March 2019.

Question 34: Skipped
Following resource bundle files are defined for the project: 
ResourceBundle_CA.properties
ResourceBundle_hi.properties
ResourceBundle_IN.properties
ResourceBundle.properties

The default locale of the system is 'fr_CA' 

Which of the resource bundle will be loaded for Locale en_IN?


ResourceBundle_IN.properties


ResourceBundle.properties
(Correct)


ResourceBundle_CA.properties


ResourceBundle_hi.properties

Explanation
Default Locale is: fr_CA and passed Locale to getBundle method is: en_IN

The search order for matching resource bundle is:

ResourceBundle_en_IN.properties [1st: Complete en_IN]. 

ResourceBundle_en.properties [2nd: Only language en]. 

ResourceBundle_fr_CA.properties [3rd: Complete default Locale fr_CA]. 

ResourceBundle_fr.properties [4th: Language of default Locale fr]. 

ResourceBundle.properties [5th: ResourceBundle's name without language or


country]. 
Out of the given resource bundles, 'ResourceBundle.properties' matches.

Question 35: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.time.*;
4. import java.time.format.DateTimeFormatter;
5.  
6. public class Test {
7. public static void main(String [] args) {
8. LocalDate valDay = LocalDate.of(2018, 2, 14);
9. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("DD-MM-uuuu");
10. System.out.println(valDay.format(formatter));
11. }
12. }

What will be the result of compiling and executing Test class?



Runtime Exception


Compilation Error


14-02-2018


45-02-2018
(Correct)

Explanation
New Date/Time API has format method in DateTimeFormatter as well as LocalDate,
LocalTime, LocalDateTime, ZonedDateTime classes, so valDay.format(formatter)
doesn't cause compilation error.

D represents day-of-year and DD is for printing 2 digits. If you calculate, day of the
year for 14th Feb 2018, then it is 45th day of the year (as January has 31 days).

45 is a 2-digit number and hence can be easily parsed by 'DD'. 

Output in this case is: 45-02-2018. 

Question 36: Skipped
Consider below code:
1. package com.udayan.ocp;
2.  
3. import java.text.NumberFormat;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. System.out.println(NumberFormat.____________________.format(5));
8. }
9. }

The default locale of the system is 'en_US'.

Which of the options correctly fills the blank, such that output is $5.00?

Select 2 options.


getInstance(java.util.Locale.US)


getCurrencyInstance()
(Correct)


getInstance()


getCurrencyInstance(java.util.Locale.US)
(Correct)

Explanation
As expected output is: $5.00, which means formatter must be for the currency and
not the number.

NumberFormat.getInstance() and NumberFormat.getInstance(Locale) return the


formatter for the number and hence will display 5 on to the console.

NumberFormat.getCurrencyInstance() returns the currency formatter for default


Locale which is en_US, hence format(5) will display $5.00 on to the console.

NumberFormat.getCurrencyInstance(java.util.Locale.US) returns the currency


formatter for the specified Locale, which is again en_US, hence format(5) will display
$5.00 on to the console.

Question 37: Skipped
F: is accessible for reading/writing and below is the directory structure for F:
1. F:.
2. ├───A
3. │ └───B
4. │ Book.java
5. │
6. └───B
7. abc.txt

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.*;
5.  
6. public class Test {
7. public static void main(String[] args) throws IOException{
8. Path src = Paths.get("F:\\A\\B");
9. Path tgt = Paths.get("F:\\B");
10. Files.move(src, tgt, StandardCopyOption.REPLACE_EXISTING);
11. }
12. }

What will be the result of compiling and executing Test class?


An exception is thrown at runtime
(Correct)


Compilation error


Directory B with its contents will move successfully from 'F:\A\B' to 'F:\B'

Explanation
Files.move(Path source, Path target, CopyOption... options) method throws following
exceptions- 

[Copied from the Javadoc]

1. UnsupportedOperationException - if the array contains a copy option that is not


supported

2. FileAlreadyExistsException - if the target file exists but cannot be replaced


because the REPLACE_EXISTING option is not specified (optional specific exception)

3. DirectoryNotEmptyException - the REPLACE_EXISTING option is specified but the


file cannot be replaced because it is a non-empty directory (optional specific
exception)
4. AtomicMoveNotSupportedException - if the options array contains the
ATOMIC_MOVE option but the file cannot be moved as an atomic file system
operation.

5. IOException - if an I/O error occurs

6. SecurityException - In the case of the default provider, and a security manager is


installed, the checkWrite method is invoked to check write access to both the source
and target file.

As target directory is not empty and StandardCopyOption.REPLACE_EXISTING is


used hence DirectoryNotEmptyException is thrown at runtime.

Question 38: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.LongFunction;
4. import java.util.function.LongUnaryOperator;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. LongFunction<LongUnaryOperator> func = a -> b -> b - a; //Line n1
9. System.out.println(calc(func.apply(100), 50)); //Line n2
10. }
11.
12. private static long calc(LongUnaryOperator op, long val) {
13. return op.applyAsLong(val);
14. }
15. }

What will be the result of compiling and executing Test class?



Line n2 causes compilation error


Line n1 causes compilation error


-100


100


50


-50
(Correct)

Explanation
Though the lambda expression with 2 arrows seems confusing but it is correct
syntax. To understand, Line n1 can be re-written as:
LongFunction<LongUnaryOperator> func = (a) -> {
return (b) -> {
return b - a;
};
};

And corresponding anonymous class syntax is:

LongFunction<LongUnaryOperator> func = new LongFunction<LongUnaryOperator>() {


@Override
public LongUnaryOperator apply(long a) {
LongUnaryOperator operator = new LongUnaryOperator() {
@Override
public long applyAsLong(long b) {
return b - a;
}
};
return operator;
}
};

So, there is no issue with Line n1. Let's check Line n2.

'func.apply(100)' returns an instance of LongUnaryOperator, in which


applyAsLong(long) method has below implementation:

LongUnaryOperator operator = new LongUnaryOperator() {


@Override
public long applyAsLong(long b) {
return b - 100;
}
};

When calc(LongUnaryOperator op, long val) is invoked using calc(func.apply(100),


50), op refers to above LongUnaryOperator instance and val is 50.

op.applyAsLong(50); returns 50 - 100, which is -50.

Question 39: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4. import java.util.stream.IntStream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. IntStream.range(1, 10).forEach(System.out::print);
9. }
10. }

What will be the result of compiling and executing Test class?



123456789
(Correct)


12345678910


13579


246810

Explanation
IntStream.range(int start, int end) => start is inclusive and end is exclusive and
incremental step is 1.

So, stream consists of value from 1 to 9 and these values are printed by forEach
method.

NOTE: For IntStream.rangeClosed(int start, int end), both start and end are inclusive.

Question 40: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.concurrent.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. ExecutorService es = Executors.newSingleThreadExecutor();
8. es.execute(() -> System.out.println("HELLO"));
9. es.shutdown();
10. }
11. }

What will be the result of compiling and executing Test class?



null


An exception is thrown at runtime


HELLO
(Correct)


Compilation error

Explanation
ExecutorService interface extends Executor interface and it has 'void
execute(Runnable command);'.

Runnable is a Functional interface which has single abstract method 'public abstract
void run();'.   

Given lambda expression, '() -> System.out.println("HELLO")' accepts no parameter


and doesn't return anything, hence it matches with the implementation of run()
method.

'HELLO' is printed on to the console.

Question 41: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void checkStatus(boolean flag) {
5. assert flag : flag = true;
6. }
7.  
8. public static void main(String[] args) {
9. checkStatus(false);
10. }
11. }

What will be the result of executing Test class with below command? 

java -ea:com.udayan... com.udayan.ocp.Test  


AssertionError is thrown and program terminates abruptly
(Correct)


No output and program terminates successfully


Compilation error

Explanation
'java -ea:com.udayan...' enables the assertion in com.udayan package and its sub
packages.

Test class is defined under 'com.udayan.ocp' package, hence assertion is enabled


for Test class. 

assert flag : flag = true; => flag is a boolean variable, so 'assert flag' has no issues
and right expression must not be void.

'flag = true' assigns true to flag and true is returned as well. Hence no issues with
right side as well.

On execution, flag is false, hence AssertionError is thrown and program terminates


abruptly.

Question 42: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. class Foo {
4. public static void m1() {
5. System.out.println("Foo : m1()");
6. }
7. class Bar {
8. public static void m1() {
9. System.out.println("Bar : m1()");
10. }
11. }
12. }
13.  
14. public class Test {
15. public static void main(String [] args) {
16. Foo foo = new Foo();
17. Foo.Bar bar = foo.new Bar();
18. bar.m1();
19. }
20. }


Compilation error
(Correct)


Bar : m1()


Foo : m1()


Runtime exception

Explanation
Regular inner class Bar cannot define any static methods.

Method m1() is static and hence compilation error.

NOTE: Regular inner class cannot define anything static, except static final variables.

Question 43: Skipped
Consider the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class Player {
4. String name;
5. int age;
6.  
7. Player() {
8. this.name = "Yuvraj";
9. this.age = 36;
10. }
11.  
12. protected String toString() {
13. return name + ", " + age;
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. System.out.println(new Player());
20. }
21. }
What will be the result of compiling and executing Test class?

Yuvraj, 36


Text containing @ symbol


null, 0


Compilation error
(Correct)

Explanation
The toString() method in Object class has below definition:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

toString() method cannot be overridden using protected modifier.

Question 44: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. public class Test<T> {
4. T [] obj;
5.  
6. public Test() {
7. obj = new T[100];
8. }
9.  
10. public T [] get() {
11. return obj;
12. }
13.  
14. public static void main(String[] args) {
15. Test<String> test = new Test<>();
16. String [] arr = test.get();
17. System.out.println(arr.length);
18. }
19. }

What will be the result of compiling and executing Test class?



Compilation error
(Correct)


100


Runtime exception

Explanation
Instantiation of a type parameter 'new T()' or an array of type parameter 'new T[5]' are
not allowed. 

'obj = new T[100];' causes compilation failure.

Question 45: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. abstract class Animal {}
7. class Dog extends Animal{}
8.  
9. public class Test {
10. public static void main(String [] args) {
11. List<Animal> list = new ArrayList<Dog>();
12. list.add(0, new Dog());
13. System.out.println(list.size() > 0);
14. }
15. }

What will be the result of compiling and executing Test class?



false


Runtime exception


true


Compilation error
(Correct)

Explanation
List is super type and ArrayList is sub type, hence List l = new ArrayList(); is valid
syntax. 

Animal is super type and Dog is sub type, hence Animal a = new Dog(); is valid
syntax. Both depicts Polymorphism.
But in generics syntax, Parameterized types are not polymorhic, this means
ArrayList<Animal> is not super type of ArrayList<Dog>. Remember this point. So
below syntaxes are not allowed: 

ArrayList<Animal> list = new ArrayList<Dog>(); OR List<Animal> list = new


ArrayList<Dog>();

Question 46: Skipped
Given code:
1. package com.udayan.ocp;
2.  
3. class Message {
4. public void printMessage() {
5. System.out.println("Hello!");
6. }
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. Message msg = new Message() {}; //Line 9
12. msg.printMessage(); //Line 10
13. }
14. }

What will be the result of compiling and executing Test class?



Compilation error at Line 9


HELLO!


NullPointerException is thrown by Line 10


Hello!
(Correct)

Explanation
Message msg = new Message() {}; means msg doesn't refer to an instance of
Message class but to an instance of un-named sub class of Message class, which
means to an instance of anonymous inner class.

In this case, anonymous inner class code doesn't override printMessage() method of
super class, Message.
So at runtime, msg.printMessage() method invokes the printMessage() method
defined in super class (Message) and Hello! is printed to the console.

Question 47: Skipped
F: is accessible for reading and below is the directory structure for F:
1. F:.
2. └───A
3. └───B
4. └───C
5. Book.java

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.nio.file.Files;
5. import java.nio.file.Path;
6. import java.nio.file.Paths;
7. import java.nio.file.attribute.BasicFileAttributes;
8.  
9. public class Test {
10. public static void main(String[] args) throws IOException{
11. Path path = Paths.get("F:\\A\\B\\C\\Book.java");
12. /*INSERT*/
13. }
14. }

Which of the following statements, if used to replace /*INSERT*/, will successfully


print creation time of 'Book.java' on to the console?
Select 3 options. 


System.out.println(Files.readAttributes(path, "*").get("creationTime"));  
(Correct)


System.out.println(Files.readAttributes(path, "*").creationTime());  


System.out.println(Files.getAttribute(path, "creationTime"));  
(Correct)


System.out.println(Files.readAttributes(path,
BasicFileAttributes.class).get("creationTime"));  


System.out.println(Files.readAttributes(path,
BasicFileAttributes.class).creationTime());  
(Correct)

Explanation
Files.getAttribute(Path path, String attribute, LinkOption... options) returns the value
corresponding to passed attribute. IllegalArgumentException is thrown if attribute is
not spelled correctly.

Files.getAttribute(path, "creationTime") returns an object containing value for


'creationTime' attribute.

Files.readAttributes is overloaded method:

public static Map<String,Object> readAttributes(Path path, String attributes,


LinkOption... options) throws IOException {...}

public static <A extends BasicFileAttributes> A readAttributes(Path path, Class<A>


type, LinkOption... options) throws IOException {...} 

If 2nd parameter is of String type, readAttributes method returns Map<String, Object>


and if 2nd parameter is of Class<A> type, it returns A. And A should pass IS-A test for
BasicFileAttributes type.

To retrieve value from Map object, use get(key) method.

Files.readAttributes(path, "*").get("creationTime") returns an object containing value


for 'creationTime' attribute. 

Files.readAttributes(path, "*").creationTime() causes compilation error as


creationTime() method is not defined in Map interface. 
Files.readAttributes(path, BasicFileAttributes.class) returns an instance of
BasicFileAttributes class and it has creationTime() method to return the creation
time.

But BaseFileAttributes class doesn't have get(String) method, so


'Files.readAttributes(path, BasicFileAttributes.class).get("creationTime")' causes
compilation error.

NOTE: There are other important methods in BaseFileAttributes class which you
should know for the OCP exam: size(), isDirectory(), isRegularFile(), isSymbolicLink(),
creationTime(), lastAccessedTime() and lastModifiedTime().

Question 48: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. class Resource implements AutoCloseable {
4. public void close() {
5. System.out.println("CLOSE");
6. }
7. }
8.  
9. public class Test {
10. public static void main(String[] args) {
11. try(Resource r = null) {
12. System.out.println("HELLO");
13. }
14. }
15. }

What will be the result of compiling and executing Test class?



NullPointerException is thrown at runtime


HELLO
CLOSE


Compilation error


HELLO
(Correct)

Explanation
For null resources, close() method is not called and hence NullPointerException is
not thrown at runtime. 

HELLO is printed on to the console.

Question 49: Skipped
Consider the code of Test.java file:
1. package com.udayan.ocp;
2.  
3. public class Test {
4. enum Directions {
5. NORTH("N"), SOUTH("S"), EAST("E"), WEST("W")
6.  
7. private String notation;
8.  
9. Directions(String notation) {
10. this.notation = notation;
11. }
12.  
13. public String getNotation() {
14. return notation;
15. }
16. }
17.  
18. public static void main(String[] args) {
19. System.out.println(Test.Directions.NORTH.getNotation());
20. }
21. }

What will be the result of compiling and executing Test class?



N


Compilation error
(Correct)


NORTH


Exception is thrown at runtime

Explanation
As enum Directions contains more code after constant declarations, hence last
constant declaration must be followed by a semicolon.

Correct constant declaration is: 


NORTH("N"), SOUTH("S"), EAST("E"), WEST("W");

Question 50: Skipped
Which of the following methods a class must implement/override to implement
java.io.Serializable interface? 

Select ALL that apply


None of the other options
(Correct)


public Object deserialize();  


public Object readObject();  


public void serialize(Object);  


public void writeObject(Object);  

Explanation
java.io.Serializable is a marker interface and hence classes which implement this
interface are not required to implement any methods for serialization to work.
Question 51: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Deque<Integer> deque = new ArrayDeque<>();
8. deque.add(100);
9. deque.add(200);
10. deque.addFirst(300);
11. deque.addLast(400);
12. deque.remove(200);
13.  
14. System.out.println(deque.getFirst());
15. }
16. }

What will be the result of compiling and executing Test class?



300
(Correct)

100


200


400

Explanation
deque.add(100); => {*100}.  * represents HEAD of the deque. 

deque.add(200); => {*100, 200}.  add(E e) invokes addLast(e) method. 

deque.addFirst(300); => {*300, 100, 200}. 

deque.addLast(400); => {*300, 100, 200, 400}. 

deque.remove(200); => {*300, 100, 400}.  Deque interface doesn't have remove(int
index) method. 

System.out.println(deque.getFirst()); => Prints 300 on to the console. 

You should be aware of other methods from Deque interface as well, such as: 

removeFirst(); => Removes the first element from the Deque. 

removeLast(); => Removes the last element from the Deque. 

Question 52: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.Collections;
5. import java.util.Comparator;
6. import java.util.List;
7.  
8. class Point {
9. private int x;
10. private int y;
11.
12. public Point(int x, int y) {
13. this.x = x;
14. this.y = y;
15. }
16.
17. public int getX() {
18. return x;
19. }
20.  
21. public int getY() {
22. return y;
23. }
24.  
25. @Override
26. public String toString() {
27. return "Point(" + x + ", " + y + ")";
28. }
29. }
30.  
31. public class Test {
32. public static void main(String [] args) {
33. List<Point> points = new ArrayList<>();
34. points.add(new Point(4, 5));
35. points.add(new Point(6, 7));
36. points.add(new Point(2, 2));
37.
38. Collections.sort(points, new Comparator<Point>() {
39. public int compareTo(Point o1, Point o2) {
40. return o1.getX() - o2.getX();
41. }
42. });
43.
44. System.out.println(points);
45. }
46. }


Compilation error
(Correct)


[Point(4, 5), Point(6, 7), Point(2, 2)]


[Point(6, 7), Point(4, 5), Point(2, 2)]


[Point(2, 2), Point(4, 5), Point(6, 7)]

Explanation
Comparator interface has compare(...) method and not compareTo(...) method.

Anonymous inner class's syntax doesn't implement compare(...) method and thus
compilation error.

Make sure to check the accessibility and interface method details before working
with the logic.

Question 53: Skipped
Consider below code:
1. package com.udayan.ocp;
2.  
3. class Animal {
4. void eat() {
5. System.out.println("Animal is eating.");
6. }
7. }
8.  
9. class Dog extends Animal {
10. public void eat() {
11. System.out.println("Dog is eating biscuit.");
12. }
13. }
14.  
15. public class Test {
16. public static void main(String[] args) {
17. Animal [] animals = new Dog[2];
18. animals[0] = new Animal();
19. animals[1] = new Dog();
20.  
21. animals[0].eat();
22. animals[1].eat();
23. }
24. }

What will be the result of compiling and executing Test class?



Compilation error


Animal is eating.
Animal is eating.


Runtime exception
(Correct)


Animal is eating.
Dog is eating biscuit.

Explanation
animals refer to an instance of Dog [] type. Each element of Dog [] can store Dog
instances but not Animal instances(sub type can't refer to super type).

But as we are using reference variable of Animal [] type hence compiler allows to add
both Animal and Dog instances.

So, animals[0] = new Animal(); and animals[1] = new Dog(); don't cause any
compilation error.
But at runtime, while executing the statement: "animals[0] = new Animal();", an
Animal instance is assigned to Dog array's element hence
java.lang.ArrayStoreException is thrown.

Question 54: Skipped
Assume that proper import statements are available, which of the following
statements will compile successfully?

Select 2 options.


Object [][] arr = Locale.getAvailableLocales();  


Locale [] loc = Locale.getAvailableLocales();  
(Correct)


Object [] locale = Locale.getAvailableLocales();  
(Correct)


List<Locale> list = Locale.getAvailableLocales();  


Map<String, String> map = Locale.getAvailableLocales();  

Explanation
'public static Locale[] getAvailableLocales() {...}' returns the Locale [] containing all
the available locales supported by the JVM. Hence, 'Locale [] loc =
Locale.getAvailableLocales();' will compile successfully.

As Object is the ultimate base class, hence 'Object [] locale =


Locale.getAvailableLocales();' also works.

NOTE: Object [] is not the parent of Locale [] but array allows above syntax because it
has ArrayStoreException.

Question 55: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void div(int i, int j) {
5. try {
6. System.out.println(i / j);
7. } catch(ArithmeticException e) {
8. Exception ex = new Exception(e);
9. throw ex;
10. }
11. }
12. public static void main(String[] args) {
13. try {
14. div(5, 0);
15. } catch(Exception e) {
16. System.out.println("END");
17. }
18. }
19. }

What will be the result of compiling and executing Test class?



Compilation error
(Correct)


END is not printed and program terminates abruptly


END is printed and program terminates abruptly


END is printed and program terminates successfully

Explanation
throw ex; causes compilation error as div method doesn't declare to throw Exception
(checked) type.
Question 56: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. public class Test {
4. private static void checkStatus() {
5. assert 1 == 2 : 2 == 2;
6. }
7.  
8. public static void main(String[] args) {
9. try {
10. checkStatus();
11. } catch (AssertionError ae) {
12. System.out.println(ae.getMessage());
13. }
14. }
15. }

What will be the result of executing Test class with below command? 

java -ea com.udayan.ocp.Test  



null


true
(Correct)


false


Compilation error

Explanation
assert 1 == 2 : 2 == 2; => throws AssertionError and as 2 == 2 is true, hence message
is set as true.

main method catches AssertionError (though you are not supposed to handle Error
and its subtype) and 'ae.getMessage()' returns true.

Question 57: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.IOException;
4. import java.sql.SQLException;
5.  
6. class MyResource implements AutoCloseable {
7. @Override
8. public void close() throws IOException{
9.  
10. }
11.  
12. public void execute() throws SQLException {
13. throw new SQLException("SQLException");
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. try(MyResource resource = new MyResource()) {
20. resource.execute();
21. } catch(Exception e) {
22. System.out.println(e.getSuppressed().length);
23. }
24. }
25. }

What will be the result of compiling and executing Test class?



NullPointerException is thrown

1


0
(Correct)

Explanation
execute() method throws an instance of SQLException.

Just before finding the matching handler, Java runtime executes close() method.
This method executes successfully. 

An instance of SQLException is thrown. No exceptions was suppressed so


'e.getSuppressed()' returns Throwable [] of size 0.

'e.getSuppressed().length' prints 0 on to the console.

Question 58: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String s1 = Arrays.asList("A", "E", "I", "O", "U").stream()
8. .reduce("", String::concat);
9. String s2 = Arrays.asList("A", "E", "I", "O", "U").parallelStream()
10. .reduce("", String::concat);
11. System.out.println(s1.equals(s2));
12. }
13. }

What will be the result of compiling and executing Test class?



It will always print false


It will always print true
(Correct)


Output cannot be predicted
Explanation
reduce method in Stream class is declared as: T reduce(T identity,
BinaryOperator<T> accumulator)

By checking the reduce method, 'reduce("", String::concat)', we can say that:

Identity is String type, accumulator is BinaryOperator<String> type.

'String::concat' is equivalent to lambda expression '(s1, s2) -> s1.concat(s2);'.

To get consistent output, there are requirements for reduce method arguments:

1. For each element 't' of the stream, accumulator.apply(identity, t) is equal to t.

   For 1st element of the stream, "A" accumulator.apply("", "A") results in "A", which is
equal to "A" and hence 1st rule is followed. 

2. The accumulator operator (concat) in this case must be associative and stateless.

   concat is associative as (s1.concat(s2)).concat(s3) equals to


s1.concat(s2.concat(s3)). Given method reference syntax is stateless as well.

  

As both the rules are followed, hence reduce will give the same result for both
sequential and parallel stream.

Question 59: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.LocalDate;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDate ocpCouponPurchaseDate = LocalDate.of(2018, 3, 1);
8. System.out.println("Coupon expiry date: "
9. + ocpCouponPurchaseDate.plusDays(10));
10. }
11. }

What will be the result of compiling and executing Test class?



Runtime exception


Coupon expiry date: 2018-3-11


Coupon expiry date: 2018-03-11
(Correct)


Compilation error

Explanation
In LocalDate.of(int, int, int) method, 1st parameter is year, 2nd is month and 3rd is
day of the month. 

ocpCouponPurchaseDate --> {2018-03-01} and


ocpCouponPurchaseDate.plusDays(10) --> {2018-03-11}. 

toString() method of LocalDate class prints the LocalDate object in ISO-8601 format:
"uuuu-MM-dd".

Question 60: Skipped
Given code: 
1. package com.udayan.ocp;
2.  
3. interface I1 {
4. void m1();
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. I1 i1 = new I1() {
10. @Override
11. public void m1() {
12. System.out.println(1234);
13. }
14. }
15. i1.m1();
16. }
17. }

What will be the result of compiling and executing Test class?



Compilation error
(Correct)


No output


Runtime exception


1234

Explanation
Semicolon is missing just before the statement i1.m1();

Wrong syntax of anonymous inner class.

Question 61: Skipped
Which of the below classes help you to define recursive task?

Select 2 options.


RecursiveTask
(Correct)


Recursion


RecursionAction


RecursionTask


RecursiveAction
(Correct)

Explanation
There are no classes in concurrent package with the names 'Recursion',
'RecursionAction' and 'RecursionTask'. 

Both RecursiveAction and RecursiveTask can be used to define a recursive task.

RecursiveTask is used to define tasks which returns a value whereas


RecursiveAction is used to define tasks that don't return a value.
Question 62: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List list = new ArrayList<Integer>();
9. list.add(1);
10. list.add(2);
11. list.add("3"); //Line 11
12. list.removeIf(i -> i % 2 == 1); //Line 12
13. System.out.println(list);
14. }
15. }

What will be the result of compiling and executing Test class?



Runtime Exception


[2]


Compilation error at Line 12
(Correct)


Compilation error at Line 11

Explanation
list is of List (raw) type. So, it can accept any object. Line 11 doesn't cause any
compilation error.

As list is raw list, which means it is of Object type, hence in Predicate's lambda
expression, i is of Object type.

Modulus operator (%) cannot be applied to Object type. So, Line 12 causes
compilation error.

NOTE: This questions checks whether you can find out the issues when raw and
generic types are mixed.

Question 63: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.Collections;
5. import java.util.Comparator;
6. import java.util.List;
7.  
8. public class Test {
9. public static void main(String[] args) {
10. List<String> list = Arrays.asList("#####", "#", "##", "####", "###");
11. Comparator<String> comp = Comparator.comparing(s -> s);
12. Collections.sort(list, comp.reversed());
13. printCodes(list);
14.  
15. }
16.  
17. private static void printCodes(List<String> list) {
18. for (String str : list) {
19. System.out.println(str);
20. }
21. }
22. }

What will be the result of compiling and executing Test class?



#####
#
##
####
###


#
##
###
####
#####


###
####
##
#
#####


#####
####
###
##
#
(Correct)
Explanation
Comparator.comparing(s -> s); compares the passed Strings only. As all the
characters in the String are '#', this means strings are sorted on the basis of their
lengths.

Comparator referred by comp sorts on the basis of strings' lengths.

Default reversed() method just reverses the ordering of the Comparator referred by
comp, which means sorts the strings in descending order of their lengths.

Question 64: Skipped
By default a Connection object is in auto-commit mode.

true
(Correct)


false

Explanation
According to javadoc of java.sql.Connection, "By default a Connection object is in
auto-commit mode, which means that it automatically commits changes after
executing each statement. If auto-commit mode has been disabled, the method
commit must be called explicitly in order to commit changes; otherwise, database
changes will not be saved".
Question 65: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
11.  
12. try (Connection con = DriverManager.getConnection(url, user, password);
13. Statement stmt = con.createStatement();
14. ResultSet rs = stmt.executeQuery(query);) {
15. rs.moveToInsertRow();
16. rs.updateInt(1, 105);
17. rs.updateString(2, "Smita");
18. rs.updateString(3, "Jain");
19. rs.updateDouble(4, 16000);
20. rs.insertRow();
21. }
22. }
23. }

Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


An exception is thrown at runtime
(Correct)


Program executes successfully but no new record is inserted in the database


Program executes successfully and a new record is inserted in the database

Explanation
By default ResultSet is not updatable. 

'rs.moveToInsertRow();' throws an exception at runtime.


To update the ResultSet in any manner (insert, update or delete), the ResultSet must
come from a Statement that was created with a ResultSet type of
ResultSet.CONCUR_UPDATABLE.

NOTE: If you want to successfully insert a new record, then replace


'con.createStatement();' with

'con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);'

OR

'con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);'.

Question 66: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.Predicate;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. printNumbers(i -> i % 2 != 0);
8. }
9.
10. private static void printNumbers(Predicate<Integer> predicate) {
11. for(int i = 1; i <= 10; i++) {
12. if(predicate.test(i)) {
13. System.out.print(i);
14. }
15. }
16. }
17. }

What will be the result of compiling and executing Test class?



12345678910


1357911


246810


1234567891011


13579
(Correct)

Explanation
In the boolean expression (predicate.test(i)): i is of primitive int type but auto-boxing
feature converts it to Integer wrapper type. 

for loops works for the numbers from 1 to 10. test(Integer) method of Predicate
returns true if passed number is an odd number, so given loop prints only odd
numbers.

Question 67: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.stream.Stream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Stream.of(true, false, true).map(b -> b.toString()
8. .toUpperCase()).peek(System.out::println);
9. }
10. }

What will be the result of compiling and executing Test class?



TRUE
FALSE
TRUE


Compilation error


Program executes successfully but nothing is printed on to the console
(Correct)


true
false
true

Explanation
Streams are lazily evaluated, which means for finite streams, if terminal operations
such as: forEach, count, toArray, reduce, collect, findFirst, findAny, anyMatch,
allMatch, sum, min, max, average etc. are not present, the given stream pipeline is
not evaluated and hence peek() method doesn't print anything on to the console.
Question 68: Skipped
What will be the result of compiling and executing Test class?
1. package com.udayan.ocp;
2.  
3. interface Formatter {
4. public abstract String format(String s1, String s2);
5. }
6.  
7. public class Test {
8. public static void main(String[] args) {
9. Formatter f1 = (str1, str2) -> str1 + "_" + str2.toUpperCase();
10. System.out.println(f1.format("Udayan", "Khattry"));
11. }
12. }


Udayan_KHATTRY
(Correct)


Udayan_Khattry


UDAYAN_Khattry


UDAYAN_KHATTRY

Explanation
Dot (.) operator has higher precedence than concatenation operator, hence
toUpperCase() is invoked on str2 and not on the result of (str1 + "_" + str2)
Question 69: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.nio.file.Path;
4. import java.nio.file.Paths;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Path path = Paths.get("F:\\A\\.\\B\\C\\D\\..\\Book.java");
9. path.normalize();
10. System.out.println(path);
11. }
12. }

What will be the result of compiling and executing Test class?



None of the other options


F:\A\B\C\Book.java


F:\A\.\B\C\D\..\Book.java
(Correct)

F:\A\B\C\D\Book.java

Explanation
Implementations of Path interface are immutable, hence path.normalize() method
doesn't make any changes to the Path object referred by reference variable 'path'.

System.out.println(path); prints the original path, 'F:\A\.\B\C\D\..\Book.java' on to the


console.

If you replace 'path.normalize();' with 'path = path.normalize();', then


'F:\A\B\C\Book.java' would be printed on to the console.

Question 70: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.function.Predicate;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String [] arr = {"A", "ab", "bab", "Aa", "bb", "baba", "aba", "Abab"};
8.
9. processStringArray(arr, /*INSERT*/);
10. }
11.
12. private static void processStringArray(String [] arr, Predicate<String>
predicate) {
13. for(String str : arr) {
14. if(predicate.test(str)) {
15. System.out.println(str);
16. }
17. }
18. }
19. }

Which of the following options can replace /*INSERT*/ such that on executing Test
class all the array elements are displayed in the output?

Select ALL that apply.


p -> p.length() >= 1  
(Correct)


p -> !false  
(Correct)

p -> true  
(Correct)


p -> p.length() < 10  
(Correct)

Explanation
p -> true means test method returns true for the passed String. 

p -> !false means test method returns true for the passed String. 

p -> p.length() >= 1 means test method returns true if passed String's length is
greater than or equal to 1 and this is true for all the array elements. 

p -> p.length() < 10 means test method returns true if passed String's length is less
than 10 and this is true for all the array elements.

Question 71: Skipped
Which of the following operator is used in lambda expressions?

=>


->
(Correct)


->


=>

Explanation
Arrow operator (->) was added in JDK 8 for lambda expressions.

NOTE: there should not be any space between - and >.

Question 72: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. class Book {
7. String isbn;
8. double price;
9.  
10. Book(String isbn, double price) {
11. this.isbn = isbn;
12. this.price = price;
13. }
14.  
15. public String toString() {
16. return "Book[" + isbn + ":" + price + "]";
17. }
18. }
19.  
20. public class Test {
21. public static void main(String[] args) {
22. List<Book> books = new ArrayList<>();
23. books.add(new Book("9781976704031", 9.99));
24. books.add(new Book("9781976704032", 15.99));
25.  
26. Book b = books.stream().reduce(new Book("9781976704033", 0.0), (b1, b2) ->
{
27. b1.price = b1.price + b2.price;
28. return new Book(b1.isbn, b1.price);
29. });
30.  
31. books.add(b);
32. books.parallelStream().reduce((x, y) -> x.price > y.price ? x : y)
33. .ifPresent(System.out::println);
34. }
35. }

What will be the result of compiling and executing Test class?



Book[9781976704031:9.99]


Book[9781976704033:15.99]


Book[9781976704033:9.99]


Book[9781976704032:15.99]


Book[9781976704033:25.98]
(Correct)

Explanation
books --> [Book[9781976704031:9.99], Book[9781976704032:15.99]]. 

books.stream() --> {Book[9781976704031:9.99], Book[9781976704032:15.99]}. It is


sequential stream. 

To understand, first reduce() method can be somewhat written as:


Book book = new Book("9781976704033", 0.0);
for(Book element : stream) {
book = accumulator.apply(book, element);
}
return book;

Above code is just for understanding purpose, you can't iterate a stream using given
loop.

apply(book, element) invokes the code of lambda expression:

(b1, b2) -> {


b1.price = b1.price + b2.price;
return new Book(b1.isbn, b1.price);
}

This means, price of Book object referred by book will be the addition of 9.99 and
15.99, which is 25.98 and its isbn will remain 9781976704033.

b --> Book[9781976704033:25.98].

Above book is added to the books list.

books --> [Book[9781976704031:9.99], Book[9781976704032:15.99],


Book[9781976704033:25.98]].

books.parallelStream().reduce((x, y) -> x.price > y.price ? x : y) returns


Optional<Book>, the Book object inside Optional has highest price.

Hence, output is: Book[9781976704033:25.98].


Question 73: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. class Employee {
6. private String name;
7. private double salary;
8.  
9. public Employee(String name, double salary) {
10. this.name = name;
11. this.salary = salary;
12. }
13.  
14. public String getName() {
15. return name;
16. }
17.  
18. public double getSalary() {
19. return salary;
20. }
21.  
22. public void setSalary(double salary) {
23. this.salary = salary;
24. }
25.  
26. public String toString() {
27. return "{" + name + ", " + salary + "}";
28. }
29. }
30.  
31. public class Test {
32. public static void main(String[] args) {
33. List<Employee> employees = Arrays.asList(new Employee("Jack", 10000), new
Employee("Lucy", 12000));
34. employees.forEach(e -> e.setSalary(e.getSalary() + (e.getSalary() * .2)));
35. employees.forEach(System.out::println);
36. }
37. }

What will be the result of compiling and executing Test class?



{Jack, 12000}
{Lucy, 14400}


{Jack, 10000.0}
{Lucy, 12000.0}


{Jack, 12000.0}
{Lucy, 14400.0}
(Correct)


{Jack, 10000}
{Lucy, 12000}
Explanation
Iterator<T> interface has forEach(Consumer) method. As Consumer is a Functional
Interface and it has 'void accept(T t)' method, hence a lambda expression for 1
parameter can be passed as argument to forEach(...) method.

'e -> e.setSalary(e.getSalary() + (e.getSalary() * .2))' => increments the salary of all
the employees by 20%. 

'System.out::println' => prints employee object on to the console. 

As salary is of double type, so decimal point (.) is shown in the output.

Question 74: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.time.LocalDateTime;
4.  
5. public class Test {
6. public static void main(String [] args) {
7. LocalDateTime dt = LocalDateTime.parse("2018-03-16t10:15:30.22");
8. System.out.println(dt);
9. }
10. }

What will be the result of compiling and executing Test class?



2018-03-16T10:15:30.22


2018-03-16t10:15:30.220


2018-03-16T10:15:30.220
(Correct)


2018-03-16t10:15:30.22

Explanation
LocalDateTime.parse(text); => text is parsed using
DateTimeFormatter.ISO_LOCAL_DATE_TIME.
ISO_LOCAL_DATE_TIME is a combination of ISO_LOCAL_DATE and
ISO_LOCAL_TIME, and it parses the date-time in following format: 

[ISO_LOCAL_DATE][T][ISO_LOCAL_TIME]: T is case-insensitive.

ISO_LOCAL_DATE represents date in following format:

uuuu-MM-dd

Valid values for year (uuuu) is: 0000 to 9999.   

Valid values for month-of-year (MM) is: 01 to 12. 

Valid values for day-of-month (dd) is: 01 to 31 (At runtime this value is validated
against month/year). 

ISO_LOCAL_TIME represents time in following format:

HH:mm (if second-of-minute is not available), 

HH:mm:ss (if second-of-minute is available), 

HH:mm:ss.SSS (if nano-of-second is 3 digit or less), 

HH:mm:ss.SSSSSS (if nano-of-second is 4 to 6 digits), 

HH:mm:ss.SSSSSSSSS (if nano-of-second is 7 to 9 digits). 

Valid values for hour-of-day (HH) is: 00 to 23. 

Valid values for minute-of-hour (mm) is: 00 to 59. 

Valid values for second-of-minute (ss) is: 00 to 59. 

Valid values for nano-of-second is: 0 to 999999999. 

toString() method of LocalDateTime class has following definition: return


date.toString() + 'T' + time.toString();
NOTE: 'T' is in upper case and as nano-of-second is of 2 digit, hence single zero is
appended to its value.

Question 75: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.*;
4.  
5. class Student {
6. private String name;
7. private int age;
8.  
9. Student(String name, int age) {
10. this.name = name;
11. this.age = age;
12. }
13.  
14. public int hashCode() {
15. return name.hashCode() + age;
16. }
17.  
18. public String toString() {
19. return "Student[" + name + ", " + age + "]";
20. }
21.  
22. public boolean equals(Object obj) {
23. if(obj instanceof Student) {
24. Student stud = (Student)obj;
25. return this.name.equals(stud.name) && this.age == stud.age;
26. }
27. return false;
28. }
29. }
30.  
31. public class Test {
32. public static void main(String[] args) {
33. Set<Student> students = new TreeSet<>();
34. students.add(new Student("James", 20));
35. students.add(new Student("James", 20));
36. students.add(new Student("James", 22));
37.  
38. System.out.println(students.size());
39. }
40. }

What will be the result of compiling and executing Test class?



Runtime Exception
(Correct)


3


2
Explanation
TreeSet requires you to provide either Comparable or Comparator.

If you don't provide Comparator explicitly, then for natural ordering your class should
implement Comparable interface.

Student class doesn't use Comparable, hence ClassCastException is thrown at


runtime.

Question 76: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Locale;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Locale loc = Locale.ENGLISH;
8. System.out.println(loc.getDisplayCountry());
9. }
10. }

What will be the result of compiling and executing Test class?



No text is displayed in the output
(Correct)


en


United States


US


English

Explanation
Locale.ENGLISH is equivalent to new Locale("en", ""); 

So, language is 'en' and country is blank.

loc.getDisplayCountry() returns blank string, hence no text is displayed in the output.


Question 77: Skipped
Consider below statement:

Any __________________ drivers that are found in your class path are automatically
loaded.

Which of the following options correctly fills the blank space?


JDBC 1 and later


JDBC 4 and later
(Correct)


JDBC 3 and later


JDBC 2 and later

Explanation
Starting with JDBC 4, there is no need to manually load the driver class.

For JDBC 3 drivers, java.lang.Class.forName method is used to load the driver class.

Question 78: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. public class Test {
4. public static void main(String[] args) {
5. System.out.printf("%2$d + %1$d", 10, 20, 30);
6. }
7. }

What will be the result of compiling and executing Test class?



None of the other options


10 + 20


30

20 + 10
(Correct)

Explanation
In format string, format specifier are just replaced.

2$ means 2nd argument, which is 20 and 1$ means 1st argument, which is 10.

Hence 'System.out.printf("%2$d + %1$d", 10, 20);' prints '20 + 10' on to the console.

Having more arguments than the format specifiers is OK, extra arguments are
ignored but having less number of arguments than format specifiers throws
MissingFormatArgumentException at runtime.

NOTE: System.out.printf(...) is same as  System.out.format(...).

Question 79: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. import java.util.ArrayList;
4. import java.util.List;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. List<StringBuilder> list = new ArrayList<>();
9. list.add(new StringBuilder("abc"));
10. list.add(new StringBuilder("xyz"));
11. list.stream().map(x -> x.reverse());
12. System.out.println(list);
13. }
14. }

What will be the result of compiling and executing Test class?



Runtime Exception


[abc, xyz]
(Correct)


[cba, zyx]


Compilation error
Explanation
Streams are lazily evaluated, which means if terminal operations such as: forEach,
count, toArray, reduce, collect, findFirst, findAny, anyMatch, allMatch, sum, min, max,
average etc. are not present, the given stream pipeline is not evaluated and hence
map() method doesn't reverse the stream elements.

'[abc, xyz]' is printed on to the console.

If you replace 'list.stream().map(x -> x.reverse());' with 'list.stream().map(x ->


x.reverse()).count();' then output will be: '[cba, zyx]'.

Question 80: Skipped
Given code of Test.java file:
1. package com.udayan.ocp;
2.  
3. class Printer<T extends String> {}
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Printer<String> printer = new Printer<>();
8. System.out.println(printer);
9. }
10. }

What will be the result of compiling and executing Test class?



Compilation error for Printer class


Some text containing @ symbol
(Correct)


Compilation error for Test class

Explanation
Even though String is a final class but T extends String is a valid syntax.

As no class extends from java.lang.String class so parameterized type will always be


Printer<String>. 

Generic class Printer doesn't override toString() method, hence Object version is
invoked.
Question 81: Skipped
Which of the following are Functional Interface in JDK 8?

Select 3 options.


java.util.Comparator
(Correct)


java.io.Serializable


java.lang.Cloneable


java.lang.Runnable
(Correct)


java.awt.event.ActionListener
(Correct)

Explanation
Comparator has only one non-overriding abstract method, compare. Runnable has
only one non-overriding abstract method, run.

ActionListener has only one non-overriding abstract method, actionPerformed.


Serializable and Cloneable are marker interfaces.

Question 82: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Arrays;
4. import java.util.stream.Stream;
5.  
6. public class Test {
7. public static void main(String[] args) {
8. Stream<Double> stream = Arrays.asList(1.8, 2.2, 3.5).stream();
9. System.out.println(stream.reduce((d1, d2) -> d1 + d2)); //Line 9
10. }
11. }

What will be the result of compiling and executing Test class?



Line 9 causes Compilation error

Optional[7.5]
(Correct)


7.5

Explanation
'stream.reduce((d1, d2) -> d1 + d2)' returns 'Optional<Double>' type whereas
'stream.reduce(0.0, (d1, d2) -> d1 + d2)' returns 'Double'.
Question 83: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.stream.LongStream;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. LongStream stream = LongStream.empty();
8. System.out.println(stream.average());
9. }
10. }

What will be the result of compiling and executing Test class?



Runtime exception


OptionalDouble.empty
(Correct)


0.0


null

Explanation
average() method in IntStream, LongStream and DoubleStream returns
OptionalDouble.

As stream is an empty stream, hence 'stream.average()' returns an empty optional.

OptionalDouble.empty is printed on to the console for empty Optional.

Question 84: Skipped
Below the code of A.java file:
1. package com.udayan.ocp;
2.  
3. public class A {
4. private static class B {
5. private void log() {
6. System.out.println("static nested class");
7. }
8. }
9.
10. public static void main(String[] args) {
11. /*INSERT*/
12. }
13. }

Which of the following options can replace /*INSERT*/ such that there on executing
class A, output is: static nested class?

Select 2 options.


1. A.B obj4 = new A().new B();
2. obj4.log();


1. A.B obj2 = new A.B();
2. obj2.log();

(Correct)


1. B obj3 = new A().new B();
2. obj3.log();


1. B obj1 = new B();
2. obj1.log();

(Correct)

Explanation
static nested class can use all 4 access modifiers (public, protected, default and
private) and 2 non-access modifiers (final and abstract).

static nested class can contain all type of members, static as well as non-static. This
behavior is different from other inner classes as other inner classes don't allow to
define anything static, except static final variables. This is the reason static nested
class is not considered as inner class.

There are 2 parts in accessing static nested class: 1st one to access the static
nested class's name and 2nd one to instantiate the static nested class.
Within the top-level class, a static nested class can be referred by 2 ways: TOP-
LEVEL-CLASS.STATIC-NESTED-CLASS and STATIC-NESTED-CLASS.

In this case, either use A.B or simply use B. Now for instantiating the static nested
class, an instance of enclosing class cannot be used, which means in this case, I
can't write new A().new B(). Correct way to instance static nested class is: new A.B();
but as main method is inside class A, hence I can even write new B(); as well.

Top-level class can easily access private members of inner or static nested class, so
no issues in invoking log() method from within the definition of class A.

Question 85: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.io.FileNotFoundException;
4. import java.io.IOException;
5.  
6. abstract class Super {
7. public abstract void m1() throws IOException;
8. }
9.  
10. class Sub extends Super {
11. @Override
12. public void m1() throws IOException {
13. throw new FileNotFoundException();
14. }
15. }
16.  
17. public class Test {
18. public static void main(String[] args) {
19. Super s = new Sub();
20. try {
21. s.m1();
22. } catch (IOException e) {
23. System.out.print("A");
24. } catch(FileNotFoundException e) {
25. System.out.print("B");
26. } finally {
27. System.out.print("C");
28. }
29. }
30. }

What will be the result of compiling and executing Test class?



AC


class Test causes compilation error
(Correct)

class Sub causes compilation error


BC

Explanation
FileNotFoundException extends IOException and hence catch block of
FileNotFoundException should appear before the catch block of IOException.

Hence, class Test causes compilation error.

Question 86: Skipped
Does below code compile successfully?
1. package com.udayan.ocp;
2.  
3. @FunctionalInterface
4. interface I1 {
5. void print();
6. boolean equals();
7. }


No
(Correct)


Yes

Explanation
@FunctionalInterface annotation cannot be used here as interface I1 specifies two
non-overriding abstract methods.

This code causes compilation error.

Question 87: Skipped
Given structure of EMPLOYEE table: 

EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),


SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600
Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE WHERE
SALARY > 14900 ORDER BY ID";
11.  
12. try (Connection con = DriverManager.getConnection(url, user, password);
13. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
14. ResultSet rs = stmt.executeQuery(query);) {
15. rs.absolute(-1);
16. rs.updateDouble("SALARY", 20000);
17. rs.updateRow();
18. } catch (SQLException ex) {
19. System.out.println("Error");
20. }
21. }
22. }

Also assume: 
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


Program executes successfully and salary of Regina Williams is updated to
20000
(Correct)


Program executes successfully and salary of Sean Smith is updated to 20000


'Error' is printed on to the console


Program executes successfully but no record is updated in the database
Explanation
Given sql statement returns below records:

102 Sean    Smith   15000       

103 Regina  Williams    15500

'rs.absolute(-1);' moves the cursor pointer to 2nd record (1st record from the
bottom). 

'rs.updateDouble("SALARY", 20000);' updates the salary of 2nd record to 20000.

'rs.updateRow();' statement updates the record in the database.

Hence, Program executes successfully and salary of Regina Williams is updated to


20000.

Please note: there is no need to invoke con.commit(); method as by default


Connection object is in auto-commit mode.

Question 88: Skipped
Given structure of MESSAGES table:

MESSAGES (msg1 varchar(100), msg2 varchar(100))  

MESSAGES table contains below records: 


'Happy New Year!', 'Happy Holidays!'

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4.  
5. public class Test {
6. public static void main(String[] args) throws SQLException {
7. String url = "jdbc:mysql://localhost:3306/ocp";
8. String user = "root";
9. String password = "password";
10. String query = "DELETE FROM MESSAGES";
11. try (Connection con = new Connection(url, user, password);
12. Statement stmt = con.createStatement())
13. {
14. System.out.println(stmt.executeUpdate(query));
15. }
16. }
17. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


0


An exception is thrown at runtime


1


Compilation error
(Correct)

Explanation
Connection is an interface, hence 'new Connection(url, user, password);' causes
compilation error.

Correct way to create Connection object in this case will be:


'DriverManager.getConnection(url, user, password);'

Question 89: Skipped
Given structure of EMPLOYEE table: 
EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))  

EMPLOYEE table contains below records: 

1. 101 John Smith 12000


2. 102 Sean Smith 15000
3. 103 Regina Williams 15500
4. 104 Natasha George 14600

Given code of Test.java file: 

1. package com.udayan.ocp;
2.  
3. import java.sql.*;
4. import java.util.Properties;
5.  
6. public class Test {
7. public static void main(String[] args) throws Exception {
8. String url = "jdbc:mysql://localhost:3306/ocp";
9. Properties prop = new Properties();
10. prop.put("user", "root");
11. prop.put("password", "password");
12. String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER
BY ID";
13. Class.forName(url);
14.  
15. try (Connection con = DriverManager.getConnection(url, prop);
16. Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
17. ResultSet rs = stmt.executeQuery(query);) {
18. rs.relative(1);
19. System.out.println(rs.getString(2));
20. }
21. }
22. }

Also assume: 
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.

What will be the result of compiling and executing Test class?


Sean

Smith


John


An exception is thrown at runtime
(Correct)

Explanation
It is assumed that JDBC 4.2 driver is configured in the classpath, hence
Class.forName(String) is not required. But no harm in using Class.forName(String).

Class.forName(String) expects fully qualified name of the class but in this case url
refers to database url and not fully qualified name of the class, hence
ClassNotFoundException is thrown at runtime.

Question 90: Skipped
Given code of Test.java file: 
1. package com.udayan.ocp;
2.  
3. import java.util.Optional;
4.  
5. public class Test {
6. public static void main(String[] args) {
7. Optional<Integer> optional = Optional.of(null);
8. System.out.println(optional);
9. }
10. }

What will be the result of compiling and executing Test class?



Optional.empty


NullPointerException is thrown at runtime
(Correct)


Optional[null]


Optional[0]

Explanation
If null argument is passed to of method, then NullPointerException is thrown at
runtime.

You might also like