Java8 Professional Udamy Practice Test 1
Java8 Professional Udamy Practice Test 1
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. }
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.
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. }
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. }
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.
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. }
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. }
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. }
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.
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.
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. }
{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.
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. }
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.
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. }
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:
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. }
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.
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. }
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.
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. }
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.
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. }
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.
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.
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
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. }
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".
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. }
{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).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.
{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. }
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.
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. }
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.
Question 20: Skipped
Given structure of EMPLOYEE table:
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.
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. }
1st4th
Optional[2nd3rd]
(Correct)
2nd3rd
Explanation
filter method filters all the strings ending with "d".
Question 22: Skipped
Consider the following interface declaration:
1. public interface I1 {
2. void m1() throws java.io.IOException;
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.
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.
Next second: 3:00:00 [Time is not 2:00:00 rather it is 3:00:00. It is 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].
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).
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.
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:
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. }
Runtime Exception
(Correct)
Compilation error
Explanation
Signature of between method defined in Duration class is: 'Duration
between(Temporal startInclusive, Temporal endExclusive)'.
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.
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. }
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.
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. }
2
1
(Correct)
0
Explanation
This is an example of Singleton class. static fields are initialize once, when class loads
in the memory.
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. }
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.
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.
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. }
-1
1
(Correct)
Compilation error
Explanation
'text::indexOf' is equivalent to lambda expression 'search -> text.indexOf(search)'.
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. }
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.
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. }
NullPointerException is thrown at runtime
Optional.empty
(Correct)
Optional[null]
Explanation
ofNullable method creates an empty Optional object if passed argument is null.
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. }
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)'.
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
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
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. }
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.
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'.
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. }
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.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. }
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.
Question 41: Skipped
Imagine below path exists:
1. F:.
2. └───A
3. └───B
4.
Compilation error
NullPointerException is thrown at runtime
F:\
(Correct)
Explanation
File class has below 2 methods:
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. }
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:
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.
An exception is thrown at runtime.
104
101
(Correct)
102
103
Explanation
Given query returns below records:
'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.
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. }
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.
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. }
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.
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. }
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.
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. }
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.
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. }
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.
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. }
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.
and
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. }
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()'.
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. }
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.
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.
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.
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.
'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. }
{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.
Question 55: Skipped
Given structure of EMPLOYEE table:
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.
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.
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. }
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.
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. }
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).
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. }
true
(Correct)
Runtime Exception
Explanation
Definition of plus method is: 'public LocalDate plus(long amountToAdd,
TemporalUnit unit) {...}'.
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. }
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.
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. }
01-12-2018
2018-12-01
Runtime Exception
(Correct)
Compilation error
Explanation
There is no compilation error in this code.
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. }
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:
or
or
Based on above JLS statement, ground target type of above lambda expression will
be: Supplier<Document> and this means above expression is equivalent to:
or
or
Based on above JLS statement, ground target type of above lambda expression will
be: Supplier<Document> and this means above expression is equivalent to:
or
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.
or
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:
or
or
Based on above JLS statement, ground target type of above lambda expression will
be: Supplier<RFP> and this means above expression is equivalent to:
or
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.
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. }
Runtime Exception
Compilation error
(Correct)
Explanation
Wrong syntax for multi-catch block, only one reference variable is allowed.
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.
'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.
'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. }
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!
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. }
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.
1. String getProperty(String key) => Returns value of the specified key and null if
value is not found.
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.
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. }
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.
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. }
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.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].
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. }
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:
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.
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.
rs.getString(1) would return 'Happy New Year!' and rs.getString(2) would return
'Happy Holidays!'.
Question 74: Skipped
Given structure of EMPLOYEE table:
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.
'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
Question 75: Skipped
Given structure of MESSAGES table:
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.
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.
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. }
Closing
Compilation error in MyResource class
Explanation
close() method in AutoCloseable interface has below declaration:
void close() throws Exception;
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.
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:
//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. }
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.
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:
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'.
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
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. }
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.
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
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.
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 [].
for loop iterates through each File object and if the File object is a Directory, then it
recursively invokes deleteFiles method.
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.
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. }
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.
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. }
[{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().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}}}].
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.
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. }
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):
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. }
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.
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.
res stores the number of bytes read into the arr. So to get exact copy replace line 12
with 'fos.write(arr, 0, res)'.
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:
To make Greet class immutable, delete the setter and add modifier 'final' for variable
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. }
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>.
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.
Question 4: Skipped
Given structure of LOG table:
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.
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.
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.
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. }
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'.
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.
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].
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. }
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).
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.
Next second: 3:00:00 [Time is not 2:00:00 rather it is 3:00:00. It is Daylight saving
time].
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. }
[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.
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. }
[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.
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).
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) {...}
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.
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. }
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.
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. }
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'.
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. }
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. }
[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.
The lambda expression is applied for all the elements of the list. Let's check it for first
element "north".
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. }
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::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. }
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. }
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.
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:
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. }
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).
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. }
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.
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.
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. }
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.
As date1 and date2 are not logically same, equals and isEqual methods return false.
Question 29: Skipped
Given structure of EMPLOYEE table:
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.
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. }
[]
(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'.
[{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. }
0
(Correct)
9
10
Explanation
IntStream.range(int start, int end) => start is inclusive and end is exclusive and
incremental step is 1.
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. }
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. }
[{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.
return o.age - this.age; => This will help to sort the Employee objects in descending
order of age and not in ascending order.
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:
toString() method of File class prints the abstract path of file object on to the
console.
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.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.
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. }
[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
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. }
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. }
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.
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. }
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. }
0
-1
(Correct)
Optional.empty
Explanation
Stream.of() creates an empty stream.
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. }
Runtime Exception
(Correct)
Compilation error
Explanation
Signature of between method defined in Duration class is: 'Duration
between(Temporal startInclusive, Temporal endExclusive)'.
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. }
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.
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
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. }
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.
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. }
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.
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. }
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(85); => Instance variable t refers to Integer object, 85. Auto-boxing converts
int literal to Integer 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. }
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.
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. }
Test
Resource2
Resource1
(Correct)
Compilation Error
Explanation
Resources are closed in the reverse order of their declaration.
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. }
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'.
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. }
{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:
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'.
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. }
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. }
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.
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. }
Runtime Exception
Compilation error
(Correct)
Explanation
Generic Stream<T> interface has following methods:
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. }
3
(Correct)
1
2
Runtime Exception
Explanation
Counter class implements Serializable, hence objects of Counter class can be
serialized using ObjectOutputStream.
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.
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. }
temp:UNKNOWN
temp_UNKNOWN
(Correct)
Line 7 throws exception at runtime
Compilation error
Explanation
Locale class has overloaded constructors:
Locale(String language)
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. }
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.
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. }
24
(Correct)
48
12
Compilation error as res should be effectively final
Explanation
IntStream.rangeClosed(1, 4); => [1, 2, 3, 4]
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'.
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. }
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.
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
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:
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.
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.
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.
'return Instant.ofEpochMilli(getTime());'
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.
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. }
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.
'(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. }
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 invoke print() method of Parent interfaces from within the overriding method, you
can use below syntax:
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.
Question 69: Skipped
Given structure of EMPLOYEE table:
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:
John Smith
Natasha George
Regina Williams
Regina Gales
(Correct)
Explanation
Given query returns below records:
'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.
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.
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.
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(...);
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. }
1
0
Explanation
TreeSet cannot contain null values.
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. }
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.
Line 8 doesn't cause any compilation error and on execution it sets the default locale
to 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.
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. }
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. }
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".
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. }
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.
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. }
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.
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
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. }
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.
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.
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. }
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>.
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();
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.
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. }
[]
Runtime Exception
(Correct)
Explanation
Deque's add() method invokes addLast(E) method and remove() method invokes
removeFirst() method.
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:
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.
Question 87: Skipped
Given structure of EMPLOYEE table:
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.
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. }
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.
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. }
Program ends abruptly
ONE
No output and program terminates successfully
(Correct)
Explanation
Assertions are disabled by default, so assert false; statement is not executed.
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. }
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.
Return to review
Attempt 1
All knowledge areas
All questions
Question 1: Skipped
[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.
Question 2: Skipped
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.
Question 3: Skipped
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.
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.
OR
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.
Question 5: Skipped
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.
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.
Question 6: Skipped
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(String language)
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.
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
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.
Lambda expression 'i -> -i++' is correctly defined for apply method.
Unary post increment(++) operator has higher precedence than unary minus(-)
operator.
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
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).
Below code will correctly override equals(Object) method in the Player class:
Question 9: Skipped
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.
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.
Question 10: Skipped
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.
If you want to invoke static method defined in Printer2 interface, then use:
Printer2.print();
Question 11: Skipped
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.
Question 12: Skipped
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".
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.
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]}.
System.out.println(Duration.between(zUS.toLocalDateTime(),
zIndia.toLocalDateTime())); // would print 'PT13H30M'.
Question 14: Skipped
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
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
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
No
Yes
(Correct)
Explanation
'GenericPrinter<T>' is generic type and is defined correctly.
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>'.
Question 18: Skipped
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'.
Question 19: Skipped
None of the other options
(Correct)
IllegalArgumentException is thrown
STOP
Explanation
case labels accept constant names only.
Question 20: Skipped
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'.
Question 21: Skipped
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.
But before exception instance is forwarded to outer catch block, inner finally gets
executed and prints "Finally 1" to the console.
Question 22: Skipped
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.
Question 23: Skipped
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. }
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
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
[email protected]
[email protected]
[email protected]
[email protected]
Explanation
Comparator is comparing on the basis of email domain: gmail.com and outlook.com.
[email protected]
gmail records should appear before outlook records. So sorting order is:
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
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.
Question 27: Skipped
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.
Question 28: Skipped
OneTwoThreenull
NullPointerException is thrown at runtime
OneTwoThree
Explanation
Given reduce method concatenates null + "One" + "Two" + "Three" and hence the
output is: 'nullOneTwoThree'.
OR
Question 29: Skipped
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.read(); => Reads 'a' and prints it. Available Stream: "leteftdeagncedk".
reader.read(); => Reads 't' and prints it. Available Stream: "eftdeagncedk".
Question 30: Skipped
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
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.
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
Line 8 and Line 10 cause compilation error
Explanation
getDisplayCountry() and getDisplayLanguage() methods are overloaded to accept
Locale type.
Question 34: Skipped
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);'.
Question 35: Skipped
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.
Question 36: Skipped
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.
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.
Question 37: Skipped
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.
equals(Object) method accepts any instance which Object can refer to, which means
all the instances.
Question 38: Skipped
A
B
C
(Correct)
Runtime Exception
A
Explanation
Format specifier, 'n' is for newline.
Question 39: Skipped
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.
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
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.
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:
'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.
Next while loop simply prints the updated salaries on to the console.
Question 41: Skipped
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. }
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.
Question 42: Skipped
Hello
Bye
Explanation
On execution, 'args.length == 0' returns true and 'assert false : changeMsg("Bye");' is
executed.
NOTE: Though this class compiles successfully but Assertion mechanism is not
implemented appropriately. There are 2 issues:
2. changeMsg("Bye") method causes side effect as it changes the class variable, 'msg'.
Question 43: Skipped
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.
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.
Question 44: Skipped
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. }
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.
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
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
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.
Question 48: Skipped
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.
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);
Question 49: Skipped
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:
System.out.println(operator);
Or you can typecast lambda expression to target type. e.g. following works:
Question 50: Skipped
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.
If you debug the code, you would find that internal routine for throwing null
exception causes NullPointerException.
Question 51: Skipped
3
Runtime Exception
Explanation
stream.mapToInt(i -> i) => returns an instance of IntStream.
Question 52: Skipped
null
Good Morning!
(Correct)
Text containing @ symbol
Explanation
optional --> [null]
'msg' filed of this object refers to "Good Morning!", which is returned by toString()
method.
Question 53: Skipped
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.
Question 54: Skipped
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.
Question 55: Skipped
No
Yes
(Correct)
Explanation
interface I2 is implicitly public and static (Nested interface).
You cannot explicitly specify protected, default and private for nested classes and
nested interfaces inside an interface.
Question 56: Skipped
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.
Question 59: Skipped
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)'.
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.
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
[TWO]
[TWO]
[ONE]
[ONE]
Explanation
LinkedList implements both List and Queue. In this example reference type controls
the LinkedList behavior.
Question 61: Skipped
{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.
Note, this compare method will sort in descending order of Student's name.
list.sort(...) accepts an argument of Comparator<Student> type.
Output is:
{Rob, OCP}
{John, OCA}
{Jack, OCP}
Question 62: Skipped
No
(Correct)
Explanation
static declaration of type parameter is not allowed, only instance declaration is
possible.
Question 63: Skipped
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.
Question 64: Skipped
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
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.
add.accept(10) is executed first and it increments the count variable by 10, so count
becomes 11.
Question 66: Skipped
>World!Hello <
> olleHWorld!<
> olleH!dlroW<
>Hello World!<
Explanation
Syntax is correct and without any errors. Methods are chained from left to right.
Question 67: Skipped
HELLO
(Correct)
Compilation error
Explanation
For null resources, close() method is not called and hence NullPointerException is not
thrown at runtime.
Question 68: Skipped
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.
Question 69: Skipped
Runtime exception
8
27
64
2
3
4
Explanation
replaceAll(UnaryOperator<E> operator) is the default method added in List
interface.
Question 70: Skipped
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
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.
Question 72: Skipped
@FI
@Functional
@FunctionalInterface
(Correct)
@Functional Interface
Explanation
@FunctionalInterface annotation is used to tag a functional interface.
Question 73: Skipped
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 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
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
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();
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.
[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
AE
(Correct)
Compilation error
RE
Explanation
Any RuntimeException can be thrown without any need it to be declared in throws
clause of surrounding method.
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
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
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
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
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.
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'.
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
-1
Line 8 throws NullPointerException
(Correct)
null
Explanation
Optional.of(null); throws NullPointerException if null arguments is passes.
Question 86: Skipped
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
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.
Question 88: Skipped
Given statement:
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:
Question 89: Skipped
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.
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:
Question 90: Skipped
Apple
Banana
An exception is thrown at runtime
Compilation error
Explanation
removeIf method accepts Predicate, hence no compilation error.
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
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
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.
Question 3: Skipped
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. }
false
An exception is thrown at runtime.
true
(Correct)
Explanation
path1 --> [F:\Other\Logs].
This is interesting, if you are at the root directory, and give the command cd .., then
nothing happens, you stay at the root only.
As path3 and path4 refer to same location, hence path3.equals(path4) returns true.
Question 4: Skipped
Executing
Closing
(Correct)
Runtime Exception
Compilation Error
Explanation
close() method in AutoCloseable interface has below declaration:
Output is:
Executing
Closing
Question 5: Skipped
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
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
Compilation error for Printer class
(Correct)
Compilation error for Test class
Explanation
For bounds, extends keyword is used for both class and interface.
Question 8: Skipped
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.
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.
Question 9: Skipped
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
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.
Question 11: Skipped
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. }
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 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
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
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
blue
(Correct)
red
yellow
Explanation
Stream.of("red", "green", "blue", "yellow") => ["red", "green", "blue", "yellow"].
Question 15: Skipped
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.
Question 16: Skipped
Compilation error
It will always print ABCDEFGHIJ
Explanation
list.parallelStream() returns a parallel stream.
Question 17: Skipped
true
(Correct)
NullPointerException is thrown at runtime
Explanation
path refers to 'F:\A', path.getRoot() refers to 'F:\' and path.getParent() refers to 'F:\'.
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
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.
Question 20: Skipped
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.
Question 21: Skipped
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.
Question 22: Skipped
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.
Initially F: is blank.
Question 23: Skipped
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:
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
{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.
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
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.
Question 28: Skipped
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.
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.
Question 29: Skipped
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
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
Question 31: Skipped
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.
Player class doesn't override the hashCode() method, rather it defines a new method
hashcode() [NOTE: c in lower case in the method name].
Question 32: Skipped
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.
Question 34: Skipped
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.err.println("TWO"); => Prints 'TWO' on to the console, default err Stream. err
PrintStream was not changed using System.setErr(PrintStream) method.
Question 35: Skipped
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.
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
It will print 0 on to the console
Explanation
stream --> {1, 2, 3, 4, 5}.
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.
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.
Question 39: Skipped
[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
HELLO is printed once
Explanation
Enum constructors are implicitly private, even though you can provide private access
modifier but it will be redundant.
Question 41: Skipped
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
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.
Question 43: Skipped
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.
Question 44: Skipped
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.
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
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.
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
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
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.
Question 48: Skipped
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.
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.
Question 50: Skipped
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
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. }
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.
"F:\\A\\.\\B\\C\\D\\..\\Book.java"
Question 52: Skipped
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.
Double Stream:
IntStream:
LongStream:
For exams, you will have to remember some of the important methods and their
signature.
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
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.
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
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:
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
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.
104
103
101
102
(Correct)
Explanation
Given sql query returns below records:
'rs.relative(-1);' moves the cursor to 2nd record (1 up from the current cursor
position).
'rs.getInt(1)' returns 102.
Question 57: Skipped
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
{Lucy, 13000.0}
{Jack, 11000.0}
{Lucy, 12000.0}
{Jack, 10000.0}
Explanation
employees.stream() => [{"Jack",10000.0},{"Lucy",12000.0}].
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
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.
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.
Question 60: Skipped
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
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) {...}
Question 62: Skipped
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 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
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();
Rest of the built-in functional interfaces are either similar to or dependent upon
these four interfaces.
Question 64: Skipped
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
Compilation error
Runtime Exception
Explanation
Signature of between method defined in Duration class is: 'Duration
between(Temporal startInclusive, Temporal endExclusive)'.
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.
Question 66: Skipped
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.
Question 67: Skipped
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:
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
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.
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
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>.
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)'.
Question 70: Skipped
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
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:
Question 73: Skipped
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
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.
Hence 'dt.toLocalDate() + " " + dt.toLocalTime()' doesn't cause any compilation error
as '+' operator is Left to Right associative.
= "2018-03-16 10:15:30.220"
Question 75: Skipped
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
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
Yes
(Correct)
No
Explanation
All streams in Java implements BaseStream interface and this interface has parallel()
and sequential() methods.
Question 78: Skipped
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.
Question 79: Skipped
not
(Correct)
binary
Or
Explanation
stream => ["and", "Or", "not", "Equals", "unary", "binary"].
Question 80: Skipped
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.properties (Available)
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
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.
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
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
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.
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.
Question 85: Skipped
XYZ
Compilation Error
YZ
Explanation
Even though method m1() declares to throw IOException but at runtime an instance
of FileNotFoundException is thrown.
Question 86: Skipped
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
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.
Question 88: Skipped
NullPointerException is thrown at runtime
true
Explanation
Constructor of Boolean class accepts String argument.
So list contains 4 elements and all are Boolean objects for false.
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.
Question 89: Skipped
db:
database:
jdbc:
(Correct)
url:
Explanation
database url has the form: protocol:subprotocol:subname.
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.
Return to review
Attempt 1
All knowledge areas
All questions
Question 1: Skipped
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
Question 2: Skipped
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.
As Book.java is a text file and accessible, hence its contents are printed on to the
console.
Question 3: Skipped
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.
Question 4: Skipped
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
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.
NOTE: Constructors of FileWriter and PrintWriter can create a new file but not
directory.
Question 6: Skipped
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.
Question 7: Skipped
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'.
System.getProperty("file.separator") OR File.separator.
Question 8: Skipped
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
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.
Question 10: Skipped
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.
(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
{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.
Question 12: Skipped
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
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.
But once Scanner object is closed, other search operations should not be invoked. If
invoked on closed scanner, IllegalStateException is thrown.
Question 14: Skipped
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.
HashSet in this case cannot find out duplicate Student objects and 3 Student objects
are added to the Set.
To avoid duplicate in the given Set, override hashCode() method in Student class:
Question 15: Skipped
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.
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
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:
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("Y", "1")
= "Y1"
and
accumulator.apply(u, t)
= accumulator.apply("Y", 1)
= "Y1"
As all the rules are followed in this case, hence str1 refers to "12345678910" and str2
refers to "12345678910"
Question 17: Skipped
Compilation error
(Correct)
Runtime Exception
2.3
Explanation
stream is of Stream<Double> type, which is a generic stream and not primitive
stream.
Question 18: Skipped
GO
(Correct)
NullPointerException is thrown at runtime
IllegalArgumentException is thrown at runtime
Explanation
args[0] refers to "GREEN" and args[1] refers to "AMBER".
GREEN is a valid enum constant, hence case label for GREEN is executed and "GO" is
printed to the console.
Question 19: Skipped
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(opr2.operation(10, 40)); => Prints 50. Over here int literals 10 and
40 are converted to Integer instances by auto-boxing.
Question 20: Skipped
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.
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.
Question 22: Skipped
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)'.
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.
Question 24: Skipped
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][T][ISO_LOCAL_TIME]: T is case-insensitive.
uuuu-MM-dd
Valid values for year (uuuu) is: 0000 to 9999.
Valid values for day-of-month (dd) is: 01 to 31 (At runtime this value is validated
against month/year).
Question 25: Skipped
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
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.
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
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.
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.getInt("IDD")' statement has wrong column name but as this statement is not
executed, hence SQLException is not thrown at runtime.
Question 28: Skipped
[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
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
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).
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
****
*****
******
*
**
Explanation
Lambda expression for Predicate is: s -> s.length() > 3. This means return true if
passed string's length is > 3.
Question 33: Skipped
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)
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 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.
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.
Question 35: Skipped
[]
[{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.
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
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
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:
So, there is no issue with Line n2. Let's check Line n3.
Question 38: Skipped
24681012
246810
13579
Explanation
IntStream.iterate(1, i -> i + 1) => [1,2,3,4,5,6,7,...]. This is an infinite stream.
Question 39: Skipped
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.
Question 40: Skipped
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.
After that JVM prints the stack trace and terminates the program abruptly.
Question 41: Skipped
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
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
Compilation Error
(Correct)
Runtime Exception
Executing
Closing
Explanation
close() method in AutoCloseable interface has below declaration:
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
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
Compilation error
Runtime exception
(Correct)
2019-01-02
Explanation
Duration works with time component and not Date component.
Question 46: Skipped
Amount 10.00 is in USD
Explanation
As Locale instance is for en_US, hence 'NumberFormat.getCurrencyInstance(loc);'
returns NumberFormat instance for US.
nf.getCurrency() returns the Currency object with currency Code "USD" and
nf.format(10) returns $10.00
Question 47: Skipped
12345
54321
(Correct)
Compilation error
Explanation
f1.compose(f2) means first apply f2 and then f1.
Question 48: Skipped
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.
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.
Question 49: Skipped
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
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
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.
Question 52: Skipped
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.
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.
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
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.
Question 54: Skipped
throw
(Correct)
catch
throws
thrown
Explanation
catch is for catching the exception and not throwing it.
To manually throw an exception, throw keyword is used. e.g., throw new Exception();
Question 55: Skipped
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.
Stream class has parallel() method to convert to parallel stream and sequential()
method to convert to sequential stream.
Question 56: Skipped
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
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.
Question 58: Skipped
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
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.
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
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.
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.
"A" and "A" are same, "b" and "B" are different & "c" and "c" are same.
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.
Question 63: Skipped
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. }
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);
Question 64: Skipped
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. }
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
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.
Question 67: Skipped
CONCUR_BOTH
CONCUR_READ_WRITE
CONCUR_WRITE_ONLY
Explanation
There are 2 ResultSet concur types: CONCUR_READ_ONLY and
CONCUR_UPDATABLE.
Question 68: Skipped
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.
Question 69: Skipped
Explanation
IntStream.range(int start, int end) => start is inclusive and end is exclusive. If start >=
end, then empty stream is returned.
IntStream.rangeClosed(int start, int end) => Both start and end are inclusive. If start
> end, then empty stream is returned.
Question 70: Skipped
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:
An exception is raised by rs.refreshRow();
105
An exception is raised by rs.deleteRow();
(Correct)
102
104
Explanation
Given query returns below records:
Question 71: Skipped
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;
};
};
So, there is no issue with Line n1. Let's check Line n2.
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();
Rest of the built-in functional interfaces are either similar to or dependent upon
these four interfaces.
Question 73: Skipped
true
true
false
true
Explanation
Builder is a static nested class added in Locale class in JDK 7.
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'.
Question 74: Skipped
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
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.
String result is stored in str variable and same is printed using System.out.println
statement.
Question 76: Skipped
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.
Question 78: Skipped
Compilation error
(Correct)
HELLO
Explanation
Resources used in try-with-resources statement must be initialized.
Question 79: Skipped
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
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.
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
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. }
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:
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
false : 2018-1-1
true : 2018-01-01
(Correct)
false : 2018-01-01
Explanation
stream => [{2018-1-1}, {2018-1-1}].
optional.isPresent() => true. isPresent method returns true if optional is not empty
otherwise false.
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
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
Compilation error
The sum is: 1525
(Correct)
Explanation
Operator + is left to right associative, so given expression can be grouped as:
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.
Question 86: Skipped
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:
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.
Question 88: Skipped
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.
NOTE: Java allows to catch Exception type. catch(Exception ex) {} will never cause
compilation error.
Question 89: Skipped
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.
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.
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.
'con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);'
OR
'con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);'
Question 90: Skipped
true
(Correct)
false
Compilation error
Explanation
static method Files.size(path) method is equivalent to instance method length()
defined in java.io.File class.
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. }
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(optional.isPresent()) {
System.out.println(optional.getAsLong());
}
Optional<T>:
Optional<T> empty(),
T get(),
boolean isPresent(),
Optional<T> of(T),
T orElse(T),
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. }
None of the other options
Output cannot be predicted
Explanation
reduce method in Stream class is declared as: 'Optional<T>
reduce(BinaryOperator<T> accumulator);'
Hence, reduce will give the same result for both sequential and parallel stream.
Question 3: Skipped
F: is currently blank and accessible for Reading/Writing.
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. }
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); => 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.
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.
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. }
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.
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. }
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.
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. }
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.
limit(4) => Returns a stream consisting of 4 elements [0,2,4,6] from the given
stream.
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'.
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.
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. }
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. }
-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'.
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. }
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. }
Compilation error
(Correct)
225
100
Explanation
IntConsumer has single abstract method, 'void accept(int value);'.
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. }
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"}, {}].
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. }
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.
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. }
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.
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. }
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.
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. }
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);
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.
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. }
Runtime Exception
James : 21
John : 20
(Correct)
Explanation
Student class implements Serializable, hence objects of Student class can be
serialized using ObjectOutputStream.
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. }
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.
NOTE: There are 3 methods in Stream interface, which returns Optional<T> type:
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.
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.
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. }
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.
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. }
a
Runtime Exception
Compilation error
(Correct)
Explanation
Method isPresent() returns boolean whereas method ifPresent accepts a Consumer
parameter.
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. }
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.
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. }
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.
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. }
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.
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
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
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. }
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).
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. }
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.
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
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. }
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-
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. }
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;
};
};
So, there is no issue with Line n1. Let's check Line n2.
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. }
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. }
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();'.
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?
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.
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.
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.
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());
}
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. }
100
Runtime exception
Explanation
Instantiation of a type parameter 'new T()' or an array of type parameter 'new T[5]' are
not allowed.
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. }
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:
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. }
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
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. }
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.
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. }
HELLO
CLOSE
Compilation error
HELLO
(Correct)
Explanation
For null resources, close() method is not called and hence NullPointerException is
not thrown at runtime.
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. }
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.
Question 50: Skipped
Which of the following methods a class must implement/override to implement
java.io.Serializable interface?
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. }
200
400
Explanation
deque.add(100); => {*100}. * represents HEAD of the deque.
deque.remove(200); => {*300, 100, 400}. Deque interface doesn't have remove(int
index) method.
You should be aware of other methods from Deque interface as well, such as:
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. }
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.
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. }
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?
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. }
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.
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. }
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)
To get consistent output, there are requirements for reduce method arguments:
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.
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. }
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.
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. }
No output
Runtime exception
1234
Explanation
Semicolon is missing just before the statement i1.m1();
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'.
[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. }
#
##
###
####
#####
###
####
##
#
#####
#####
####
###
##
#
(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.
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:
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.
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.
'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. }
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. }
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. }
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'.
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?
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.
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. }
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]].
Above code is just for understanding purpose, you can't iterate a stream using given
loop.
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].
{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%.
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. }
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.
uuuu-MM-dd
Valid values for day-of-month (dd) is: 01 to 31 (At runtime this value is validated
against month/year).
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. }
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.
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. }
en
United States
US
English
Explanation
Locale.ENGLISH is equivalent to new Locale("en", "");
Any __________________ drivers that are found in your class path are automatically
loaded.
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. }
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.
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. }
[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.
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. }
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.
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.
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. }
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. }
OptionalDouble.empty
(Correct)
0.0
null
Explanation
average() method in IntStream, LongStream and DoubleStream returns
OptionalDouble.
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. }
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.
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.
Question 87: Skipped
Given structure of EMPLOYEE table:
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.
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:
'rs.absolute(-1);' moves the cursor pointer to 2nd record (1st record from the
bottom).
Question 88: Skipped
Given structure of MESSAGES table:
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.
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.
Question 89: Skipped
Given structure of EMPLOYEE table:
EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100),
SALARY real, PRIMARY KEY (ID))
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.
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. }
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.