You have already completed the Test before. Hence you can not start it again.
Test is loading...
You must sign in or sign up to start the Test.
You have to finish following quiz, to start this Test:
Your results are here!! for" OCP Java SE 11 Programmer I 1Z0-815 Practice Test 8 "
0 of 65 questions answered correctly
Your time:
Time has elapsed
Your Final Score is : 0
You have attempted : 0
Number of Correct Questions : 0 and scored 0
Number of Incorrect Questions : 0 and Negative marks 0
Average score
Your score
OCP Java SE 11 Programmer I 1Z0-815
You have attempted: 0
Number of Correct Questions: 0 and scored 0
Number of Incorrect Questions: 0 and Negative marks 0
You can review your answers by clicking view questions. Important Note : Open Reference Documentation Links in New Tab (Right Click and Open in New Tab).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Answered
Review
Question 1 of 65
1. Question
Consider below code of “Util.txt” file:
package com.udayankhattry.ocp1;
public class Util {
public static void main(String [] args) {
System.out.println(args[0] + args[1]);
}
}
And the command:
java –source 11 Util.txt 10 20
What is the result?
Correct
SCP72141:
Starting with JDK 11, it is possible to launch single-file source-code Programs.
If you execute ‘java –help’ command, you would find below option was added for Java 11:
java [options][args]
(to execute a single source-file program)
Single-file program is the file where the whole program fits in a single source file and it is very useful in the early stages of learning Java.
If you pass a file name with .java extension to java command, then java command consider the passed file as ‘single-file source-code program’. But if any other file name is passed, then it considers the passed file as the class name. So, in this case, if you run the command `java Util.txt 10 20`, then java command searches for the class with the name ‘Util.txt’ and would thrown an error.
F:\>java Util.txt 10 20
Error: Could not find or load main class Util.txt
Caused by: java.lang.ClassNotFoundException: Util.txt
If the file does not have the .java extension, the –source option must be used to force source-file mode.
`java –source 11 Util.txt 10 20` instructs the java command to process the Util.txt as Java 11 source code. Two command line arguments (“10” and “20”) are passed. args[0] refers to “10” and args[1] refers to “20” hence the expression args[0] + args[1] evaluates to “1020”.
Please note that source-file can contain package statement and multiple classes (even public) but first class found must have special main method ‘public static void main(String [])’.
SCP72141:
Starting with JDK 11, it is possible to launch single-file source-code Programs.
If you execute ‘java –help’ command, you would find below option was added for Java 11:
java [options][args]
(to execute a single source-file program)
Single-file program is the file where the whole program fits in a single source file and it is very useful in the early stages of learning Java.
If you pass a file name with .java extension to java command, then java command consider the passed file as ‘single-file source-code program’. But if any other file name is passed, then it considers the passed file as the class name. So, in this case, if you run the command `java Util.txt 10 20`, then java command searches for the class with the name ‘Util.txt’ and would thrown an error.
F:\>java Util.txt 10 20
Error: Could not find or load main class Util.txt
Caused by: java.lang.ClassNotFoundException: Util.txt
If the file does not have the .java extension, the –source option must be used to force source-file mode.
`java –source 11 Util.txt 10 20` instructs the java command to process the Util.txt as Java 11 source code. Two command line arguments (“10” and “20”) are passed. args[0] refers to “10” and args[1] refers to “20” hence the expression args[0] + args[1] evaluates to “1020”.
Please note that source-file can contain package statement and multiple classes (even public) but first class found must have special main method ‘public static void main(String [])’.
SCP72141:
Starting with JDK 11, it is possible to launch single-file source-code Programs.
If you execute ‘java –help’ command, you would find below option was added for Java 11:
java [options][args]
(to execute a single source-file program)
Single-file program is the file where the whole program fits in a single source file and it is very useful in the early stages of learning Java.
If you pass a file name with .java extension to java command, then java command consider the passed file as ‘single-file source-code program’. But if any other file name is passed, then it considers the passed file as the class name. So, in this case, if you run the command `java Util.txt 10 20`, then java command searches for the class with the name ‘Util.txt’ and would thrown an error.
F:\>java Util.txt 10 20
Error: Could not find or load main class Util.txt
Caused by: java.lang.ClassNotFoundException: Util.txt
If the file does not have the .java extension, the –source option must be used to force source-file mode.
`java –source 11 Util.txt 10 20` instructs the java command to process the Util.txt as Java 11 source code. Two command line arguments (“10” and “20”) are passed. args[0] refers to “10” and args[1] refers to “20” hence the expression args[0] + args[1] evaluates to “1020”.
Please note that source-file can contain package statement and multiple classes (even public) but first class found must have special main method ‘public static void main(String [])’.
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(“B”); //Line n1
sb.append(sb.append(“A”)); //Line n2
System.out.println(sb); //Line n3
}
}
What will be the result of compiling and executing Test class?
Correct
SCP13349:
At Line n1:
sb –> {“B”}
append(…) method in StringBuilder class is overloaded to accept various arguments and 2 such arguments are String and CharSequence. It’s return type is StringBuilder and as StringBuilder class implements CharSequence interface, hence ‘sb.append(“A”)’ can easily be passed as and argument to sb.append(…) method. Line n2 compiles successfully.
At Line n2:
sb.append(sb.append(“A”)); //sb –> {“B”}
sb.append({“BA”}); //sb –> {“BA”}
{“BABA”}
Hence, Line n3 prints BABA
Incorrect
SCP13349:
At Line n1:
sb –> {“B”}
append(…) method in StringBuilder class is overloaded to accept various arguments and 2 such arguments are String and CharSequence. It’s return type is StringBuilder and as StringBuilder class implements CharSequence interface, hence ‘sb.append(“A”)’ can easily be passed as and argument to sb.append(…) method. Line n2 compiles successfully.
At Line n2:
sb.append(sb.append(“A”)); //sb –> {“B”}
sb.append({“BA”}); //sb –> {“BA”}
{“BABA”}
Hence, Line n3 prints BABA
Unattempted
SCP13349:
At Line n1:
sb –> {“B”}
append(…) method in StringBuilder class is overloaded to accept various arguments and 2 such arguments are String and CharSequence. It’s return type is StringBuilder and as StringBuilder class implements CharSequence interface, hence ‘sb.append(“A”)’ can easily be passed as and argument to sb.append(…) method. Line n2 compiles successfully.
At Line n2:
sb.append(sb.append(“A”)); //sb –> {“B”}
sb.append({“BA”}); //sb –> {“BA”}
{“BABA”}
Hence, Line n3 prints BABA
Question 3 of 65
3. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String [] args) {
boolean flag = false;
System.out.println((flag = true) | (flag = false) || (flag = true));
System.out.println(flag);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP77847:
Given statement:
System.out.println((flag = true) | (flag = false) || (flag = true)); //flag = false
System.out.println(((flag = true) | (flag = false)) || (flag = true)); //bitwise inclusive OR | has higher precedence over logical OR ||. flag = false
|| has two operands, Left: ((flag = true) | (flag = false)) and Right: (flag = true). Left operand needs to be evaluated first.
System.out.println((true | (flag = false)) || (flag = true)); //flag = true
System.out.println((true | false) || (flag = true)); //flag = false
System.out.println(true || (flag = true)); //flag = false
|| is a short-circuit operator and as left operand evaluates to true, hence right operand is not evaluated.
Above statement prints true on to the console.
And
System.out.println(flag); prints false on to the console as flag variable is false.
Incorrect
SCP77847:
Given statement:
System.out.println((flag = true) | (flag = false) || (flag = true)); //flag = false
System.out.println(((flag = true) | (flag = false)) || (flag = true)); //bitwise inclusive OR | has higher precedence over logical OR ||. flag = false
|| has two operands, Left: ((flag = true) | (flag = false)) and Right: (flag = true). Left operand needs to be evaluated first.
System.out.println((true | (flag = false)) || (flag = true)); //flag = true
System.out.println((true | false) || (flag = true)); //flag = false
System.out.println(true || (flag = true)); //flag = false
|| is a short-circuit operator and as left operand evaluates to true, hence right operand is not evaluated.
Above statement prints true on to the console.
And
System.out.println(flag); prints false on to the console as flag variable is false.
Unattempted
SCP77847:
Given statement:
System.out.println((flag = true) | (flag = false) || (flag = true)); //flag = false
System.out.println(((flag = true) | (flag = false)) || (flag = true)); //bitwise inclusive OR | has higher precedence over logical OR ||. flag = false
|| has two operands, Left: ((flag = true) | (flag = false)) and Right: (flag = true). Left operand needs to be evaluated first.
System.out.println((true | (flag = false)) || (flag = true)); //flag = true
System.out.println((true | false) || (flag = true)); //flag = false
System.out.println(true || (flag = true)); //flag = false
|| is a short-circuit operator and as left operand evaluates to true, hence right operand is not evaluated.
Above statement prints true on to the console.
And
System.out.println(flag); prints false on to the console as flag variable is false.
public class Test {
public static void main(String[] args) {
List list = new ArrayList<>();
byte b = 10;
list.add(b); //Line n1
var mul = list.get(0) * list.get(0); //Line n2
System.out.println(mul);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP59970:
list is of Integer type and variable ‘b’ is of byte type.
At Line n1, b is auto-boxed to Byte and not Integer and List can’t store Byte objects, therefore Line n1 causes compilation error.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
list.get(0) returns Integer and `list.get(0) * list.get(0)` is evaluated to int, therefore variable ‘mul’ infers to int. Line n2 compiles successfully.
Incorrect
SCP59970:
list is of Integer type and variable ‘b’ is of byte type.
At Line n1, b is auto-boxed to Byte and not Integer and List can’t store Byte objects, therefore Line n1 causes compilation error.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
list.get(0) returns Integer and `list.get(0) * list.get(0)` is evaluated to int, therefore variable ‘mul’ infers to int. Line n2 compiles successfully.
Unattempted
SCP59970:
list is of Integer type and variable ‘b’ is of byte type.
At Line n1, b is auto-boxed to Byte and not Integer and List can’t store Byte objects, therefore Line n1 causes compilation error.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
list.get(0) returns Integer and `list.get(0) * list.get(0)` is evaluated to int, therefore variable ‘mul’ infers to int. Line n2 compiles successfully.
Question 5 of 65
5. Question
Consider below codes of 3 java files:
//Sellable.java
package com.udayankhattry.ocp1;
public interface Sellable {
double getPrice();
default String symbol() {
return “$”;
}
}
//Chair.java
package com.udayankhattry.ocp1;
public class Chair implements Sellable {
public double getPrice() {
return 35;
}
public String symbol() {
return “£”;
}
}
//Test.java
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
Sellable obj = new Chair(); //Line n1
System.out.println(obj.symbol() + obj.getPrice()); //Line n2
}
}
What will be the result of compiling and executing Test class?
Correct
SCP72941:
default methods were added in Java 8. Class Chair correctly implements Sellable interface and it also overrides the default symbol() method of Sellable interface.
At Line n1, ‘obj’ refers to an instance of Chair class, so obj.symbol() and obj.getPrice() invoke the overriding methods of Chair class only.
obj.symbol() returns “£” and obj.getPrice() returns 35.0
At Line n2, ‘+’ operator behaves as concatenation operator and Line n2 prints £35.0 on to the console.
Incorrect
SCP72941:
default methods were added in Java 8. Class Chair correctly implements Sellable interface and it also overrides the default symbol() method of Sellable interface.
At Line n1, ‘obj’ refers to an instance of Chair class, so obj.symbol() and obj.getPrice() invoke the overriding methods of Chair class only.
obj.symbol() returns “£” and obj.getPrice() returns 35.0
At Line n2, ‘+’ operator behaves as concatenation operator and Line n2 prints £35.0 on to the console.
Unattempted
SCP72941:
default methods were added in Java 8. Class Chair correctly implements Sellable interface and it also overrides the default symbol() method of Sellable interface.
At Line n1, ‘obj’ refers to an instance of Chair class, so obj.symbol() and obj.getPrice() invoke the overriding methods of Chair class only.
obj.symbol() returns “£” and obj.getPrice() returns 35.0
At Line n2, ‘+’ operator behaves as concatenation operator and Line n2 prints £35.0 on to the console.
Question 6 of 65
6. Question
Given code:
package com.udayankhattry.ocp1;
public class Pen {
public static void main(String[] args) {
Pen p1 = new Pen(); //Line n1
Pen p2 = new Pen(); //Line n2
p1 = p2; //Line n3
p1 = null; //Line n4
}
}
When is the Pen object, created at Line n1, will be eligible for Garbage Collection?
Correct
SCP50787:
At Line n3, p1 starts referring to the object referred by p2(Created at Line n2).
So, after Line n3, object created at Line n1 becomes unreachable and thus eligible for Garbage Collection.
Incorrect
SCP50787:
At Line n3, p1 starts referring to the object referred by p2(Created at Line n2).
So, after Line n3, object created at Line n1 becomes unreachable and thus eligible for Garbage Collection.
Unattempted
SCP50787:
At Line n3, p1 starts referring to the object referred by p2(Created at Line n2).
So, after Line n3, object created at Line n1 becomes unreachable and thus eligible for Garbage Collection.
Question 7 of 65
7. Question
Consider below codes of 3 java files:
//Shrinkable.java
package com.udayankhattry.ocp1;
public interface Shrinkable {
public static void shrinkPercentage() {
System.out.println(“80%”);
}
}
//AntMan.java
package com.udayankhattry.ocp1;
public class AntMan implements Shrinkable { }
//Test.java
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
AntMan.shrinkPercentage();
}
}
Which of the following statements is correct?
Correct
SCP65178:
As per Java 8, default and static methods were added in the interface and as per Java 9, private methods were added in the interface. There is no issue in Shrinkable.java file.
class AntMan implements Shrinkable interface but as there is no abstract method in Shrinkable interface, hence AntMan class is not needed to implement any method. AntMan.java file compiles successfully.
static method of Shrinkable interface can only be accessed by using Shrinkable.shrinkPercentage(). `AntMan.shrinkPercentage();` causes compilation error.
Incorrect
SCP65178:
As per Java 8, default and static methods were added in the interface and as per Java 9, private methods were added in the interface. There is no issue in Shrinkable.java file.
class AntMan implements Shrinkable interface but as there is no abstract method in Shrinkable interface, hence AntMan class is not needed to implement any method. AntMan.java file compiles successfully.
static method of Shrinkable interface can only be accessed by using Shrinkable.shrinkPercentage(). `AntMan.shrinkPercentage();` causes compilation error.
Unattempted
SCP65178:
As per Java 8, default and static methods were added in the interface and as per Java 9, private methods were added in the interface. There is no issue in Shrinkable.java file.
class AntMan implements Shrinkable interface but as there is no abstract method in Shrinkable interface, hence AntMan class is not needed to implement any method. AntMan.java file compiles successfully.
static method of Shrinkable interface can only be accessed by using Shrinkable.shrinkPercentage(). `AntMan.shrinkPercentage();` causes compilation error.
abstract class Parent {
public abstract void find() throws IOException;
}
class Child extends Parent {
@Override
public void find() throws IOException {
throw new FileNotFoundException();
}
}
public class Test {
public static void main(String[] args) {
Parent p = new Child();
try {
p.find();
} catch (FileNotFoundException e) {
System.out.print(“X”);
} catch (IOException e) {
System.out.print(“Y”);
} finally {
System.out.print(“Z”);
}
}
}
What will be the result of compiling and executing Test class?
Correct
SCP14635:
Method find() of Child class correctly overrides the method find() of Parent class, so there is no compilation error in Child class.
Code in Test class doesn’t cause any error as well.
java.io.FileNotFoundException extends java.io.IOException
and
java.io.IOException extends java.lang.Exception
Even though method find() declares to throw IOException but at runtime an instance of FileNotFoundException is thrown.
A catch handler for FileNotFoundException is available and hence X is printed on to the console.
After that finally block is executed, which prints Z to the console.
Incorrect
SCP14635:
Method find() of Child class correctly overrides the method find() of Parent class, so there is no compilation error in Child class.
Code in Test class doesn’t cause any error as well.
java.io.FileNotFoundException extends java.io.IOException
and
java.io.IOException extends java.lang.Exception
Even though method find() declares to throw IOException but at runtime an instance of FileNotFoundException is thrown.
A catch handler for FileNotFoundException is available and hence X is printed on to the console.
After that finally block is executed, which prints Z to the console.
Unattempted
SCP14635:
Method find() of Child class correctly overrides the method find() of Parent class, so there is no compilation error in Child class.
Code in Test class doesn’t cause any error as well.
java.io.FileNotFoundException extends java.io.IOException
and
java.io.IOException extends java.lang.Exception
Even though method find() declares to throw IOException but at runtime an instance of FileNotFoundException is thrown.
A catch handler for FileNotFoundException is available and hence X is printed on to the console.
After that finally block is executed, which prints Z to the console.
Question 9 of 65
9. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
class Super {
Super() {
System.out.print(“Reach”);
}
}
class Sub extends Super {
Sub() {
Super();
System.out.print(“Out”);
}
}
public class Test {
public static void main(String[] args) {
new Sub();
}
}
What will be the result of compiling and executing above code?
Correct
SCP85870:
Parent (Super) class constructor is invoked by `super();` (all letters in lowercase) from within the constructor of subclass.
First statement inside no-argument constructor of Sub class is: `Super();` (Letter ‘S’ is in uppercase) and hence it causes compilation error.
Incorrect
SCP85870:
Parent (Super) class constructor is invoked by `super();` (all letters in lowercase) from within the constructor of subclass.
First statement inside no-argument constructor of Sub class is: `Super();` (Letter ‘S’ is in uppercase) and hence it causes compilation error.
Unattempted
SCP85870:
Parent (Super) class constructor is invoked by `super();` (all letters in lowercase) from within the constructor of subclass.
First statement inside no-argument constructor of Sub class is: `Super();` (Letter ‘S’ is in uppercase) and hence it causes compilation error.
SCP73187:
Starting with JDK 11, it is possible to launch single-file source-code Programs.
If you execute ‘java –help’ command, you would find below option was added for Java 11:
java [options][args]
(to execute a single source-file program)
Single-file program is the file where the whole program fits in a single source file and it is very useful in the early stages of learning Java.
The effect of `java Test.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence, `java Test.java` is equivalent to (but not exactly same as):
javac -d Test.java
java -cp Test
As command-line argument is not passed, hence Line n1 throws ArrayIndexOutOfBoundsException (subclass of RuntimeException), handler is available in inner catch block, it executes Line n1 and prints INHALE- on to the console.
throw e; re-throws the exception.
But before exception instance is forwarded to outer catch-block, inner finally-block gets executed and prints EXHALE- on to the console.
In outer try-catch block, handler for RuntimeException is available, so outer catch-block gets executed and prints INHALE- on to the console.
After that outer finally-block gets executed and prints EXHALE- on to the console.
Hence, the output is: INHALE-EXHALE-INHALE-EXHALE
Incorrect
SCP73187:
Starting with JDK 11, it is possible to launch single-file source-code Programs.
If you execute ‘java –help’ command, you would find below option was added for Java 11:
java [options][args]
(to execute a single source-file program)
Single-file program is the file where the whole program fits in a single source file and it is very useful in the early stages of learning Java.
The effect of `java Test.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence, `java Test.java` is equivalent to (but not exactly same as):
javac -d Test.java
java -cp Test
As command-line argument is not passed, hence Line n1 throws ArrayIndexOutOfBoundsException (subclass of RuntimeException), handler is available in inner catch block, it executes Line n1 and prints INHALE- on to the console.
throw e; re-throws the exception.
But before exception instance is forwarded to outer catch-block, inner finally-block gets executed and prints EXHALE- on to the console.
In outer try-catch block, handler for RuntimeException is available, so outer catch-block gets executed and prints INHALE- on to the console.
After that outer finally-block gets executed and prints EXHALE- on to the console.
Hence, the output is: INHALE-EXHALE-INHALE-EXHALE
Unattempted
SCP73187:
Starting with JDK 11, it is possible to launch single-file source-code Programs.
If you execute ‘java –help’ command, you would find below option was added for Java 11:
java [options][args]
(to execute a single source-file program)
Single-file program is the file where the whole program fits in a single source file and it is very useful in the early stages of learning Java.
The effect of `java Test.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence, `java Test.java` is equivalent to (but not exactly same as):
javac -d Test.java
java -cp Test
As command-line argument is not passed, hence Line n1 throws ArrayIndexOutOfBoundsException (subclass of RuntimeException), handler is available in inner catch block, it executes Line n1 and prints INHALE- on to the console.
throw e; re-throws the exception.
But before exception instance is forwarded to outer catch-block, inner finally-block gets executed and prints EXHALE- on to the console.
In outer try-catch block, handler for RuntimeException is available, so outer catch-block gets executed and prints INHALE- on to the console.
After that outer finally-block gets executed and prints EXHALE- on to the console.
Hence, the output is: INHALE-EXHALE-INHALE-EXHALE
Question 11 of 65
11. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String [] args) {
String str = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
System.out.println(subtext(str, 3, 8)); //Line n1
}
/*INSERT*/
}
Line n1 causes compilation error as subtext method is not found.
Which of the following method definitions, if used to replace /*INSERT*/, will resolve the compilation error?
Select ALL that apply.
Correct
SCP37568:
It is clear from Line n1 that, method name should be subtext, it should be static method, it should accept 3 parameters (String, int, int).
As subtext(str, 3, 8) is passed as an argument of System.out.println method, hence subtext method’s return type can be anything apart from void. println method is overloaded to accept all primitive types, char [], String type and Object type. int[] are String [] are of Object type.
In the given options, method specifying int as return type cannot return null as null can’t be assigned to primitive type. int subtext(…) would give compilation error.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
The identifier var is not a keyword, hence var can still be used as variable name, method name or package name but it cannot be used as a class or interface name.
var type cannot be used as method parameters or method return type.
Incorrect
SCP37568:
It is clear from Line n1 that, method name should be subtext, it should be static method, it should accept 3 parameters (String, int, int).
As subtext(str, 3, 8) is passed as an argument of System.out.println method, hence subtext method’s return type can be anything apart from void. println method is overloaded to accept all primitive types, char [], String type and Object type. int[] are String [] are of Object type.
In the given options, method specifying int as return type cannot return null as null can’t be assigned to primitive type. int subtext(…) would give compilation error.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
The identifier var is not a keyword, hence var can still be used as variable name, method name or package name but it cannot be used as a class or interface name.
var type cannot be used as method parameters or method return type.
Unattempted
SCP37568:
It is clear from Line n1 that, method name should be subtext, it should be static method, it should accept 3 parameters (String, int, int).
As subtext(str, 3, 8) is passed as an argument of System.out.println method, hence subtext method’s return type can be anything apart from void. println method is overloaded to accept all primitive types, char [], String type and Object type. int[] are String [] are of Object type.
In the given options, method specifying int as return type cannot return null as null can’t be assigned to primitive type. int subtext(…) would give compilation error.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
The identifier var is not a keyword, hence var can still be used as variable name, method name or package name but it cannot be used as a class or interface name.
var type cannot be used as method parameters or method return type.
Question 12 of 65
12. Question
What will be the result of compiling and executing Test class?
package com.udayankhattry.ocp1;
“public class Test {
public static void main(String [] args) {
int i = 2;
boolean res = false;
res = i++ == 2 || –i == 2 && –i == 2;
System.out.println(i);
}
}
“
Correct
SCP67806:
i++ == 2 || –i == 2 && –i == 2; [Given expression].
(i++) == 2 || –i == 2 && –i == 2; [Postfix has got higher precedence than other operators].
(i++) == 2 || (–i) == 2 && (–i) == 2; [After postfix, precedence is given to prefix].
((i++) == 2) || ((–i) == 2) && ((–i) == 2); [== has higher precedence over && and ||].
((i++) == 2) || (((–i) == 2) && ((–i) == 2)); [&& has higher precedence over ||].
Let’s start solving it:
((i++) == 2) || (((–i) == 2) && ((–i) == 2)); [i=2, res=false].
(2 == 2) || (((–i) == 2) && ((–i) == 2)); [i=3, res=false].
true || (((–i) == 2) && ((–i) == 2)); [i=3, res=false]. || is a short-circuit operator, hence no need to evaluate expression on the right.
res is true and i is 3.
Incorrect
SCP67806:
i++ == 2 || –i == 2 && –i == 2; [Given expression].
(i++) == 2 || –i == 2 && –i == 2; [Postfix has got higher precedence than other operators].
(i++) == 2 || (–i) == 2 && (–i) == 2; [After postfix, precedence is given to prefix].
((i++) == 2) || ((–i) == 2) && ((–i) == 2); [== has higher precedence over && and ||].
((i++) == 2) || (((–i) == 2) && ((–i) == 2)); [&& has higher precedence over ||].
Let’s start solving it:
((i++) == 2) || (((–i) == 2) && ((–i) == 2)); [i=2, res=false].
(2 == 2) || (((–i) == 2) && ((–i) == 2)); [i=3, res=false].
true || (((–i) == 2) && ((–i) == 2)); [i=3, res=false]. || is a short-circuit operator, hence no need to evaluate expression on the right.
res is true and i is 3.
Unattempted
SCP67806:
i++ == 2 || –i == 2 && –i == 2; [Given expression].
(i++) == 2 || –i == 2 && –i == 2; [Postfix has got higher precedence than other operators].
(i++) == 2 || (–i) == 2 && (–i) == 2; [After postfix, precedence is given to prefix].
((i++) == 2) || ((–i) == 2) && ((–i) == 2); [== has higher precedence over && and ||].
((i++) == 2) || (((–i) == 2) && ((–i) == 2)); [&& has higher precedence over ||].
Let’s start solving it:
((i++) == 2) || (((–i) == 2) && ((–i) == 2)); [i=2, res=false].
(2 == 2) || (((–i) == 2) && ((–i) == 2)); [i=3, res=false].
true || (((–i) == 2) && ((–i) == 2)); [i=3, res=false]. || is a short-circuit operator, hence no need to evaluate expression on the right.
res is true and i is 3.
Question 13 of 65
13. Question
Given code of TestRectangle.java file:
package com.udayankhattry.ocp1;
class Rectangle {
private int height;
private int width;
public Rectangle(int height, int width) {
this.height = height;
this.width = width;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
}
public class TestRectangle {
public static void main(String[] args) {
private int i = 100;
private int j = 200;
Rectangle rect = new Rectangle(i, j);
System.out.println(rect.getHeight() + “, ” + rect.getWidth());
}
}
What will be the result of compiling and executing above code?
Correct
SCP51656:
i and j cannot be declared private as i and j are local variables.
Only final modifier can be used with local variables.
Incorrect
SCP51656:
i and j cannot be declared private as i and j are local variables.
Only final modifier can be used with local variables.
Unattempted
SCP51656:
i and j cannot be declared private as i and j are local variables.
Only final modifier can be used with local variables.
Question 14 of 65
14. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) {
try {
System.out.println(args[1].length());
} catch (RuntimeException ex) {
System.out.println(“ONE”);
} catch (FileNotFoundException ex) {
System.out.println(“TWO”);
}
System.out.println(“THREE”);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP52005:
java.io.FileNotFoundException exception is a checked exception.
Java doesn’t allow to catch specific checked exceptions if these are not thrown by the statements inside try block. catch(FileNotFoundException ex) {} causes compilation error in this case as System.out.println(1); will never throw FileNotFoundException.
NOTE: Java allows to catch Exception type. catch(Exception ex) {} will never cause compilation error.
Incorrect
SCP52005:
java.io.FileNotFoundException exception is a checked exception.
Java doesn’t allow to catch specific checked exceptions if these are not thrown by the statements inside try block. catch(FileNotFoundException ex) {} causes compilation error in this case as System.out.println(1); will never throw FileNotFoundException.
NOTE: Java allows to catch Exception type. catch(Exception ex) {} will never cause compilation error.
Unattempted
SCP52005:
java.io.FileNotFoundException exception is a checked exception.
Java doesn’t allow to catch specific checked exceptions if these are not thrown by the statements inside try block. catch(FileNotFoundException ex) {} causes compilation error in this case as System.out.println(1); will never throw FileNotFoundException.
NOTE: Java allows to catch Exception type. catch(Exception ex) {} will never cause compilation error.
void divide() {
try {
res = num / den;
} catch(RuntimeException e) {}
}
public String toString() {
if (den == 0)
return num + “/” + den + ” = ” + “Infinity”;
else
return num + “/” + den + ” = ” + res;
}
}
public class Test {
public static void main(String[] args) {
var list = List.of(new Division(100, 4), new Division(27, 0), new Division(25, 5));
list.forEach(d -> d.divide()); //Line n1
list.forEach(d -> System.out.println(d)); //Line n2
}
}
What will be the result of compiling and executing Test class?
Correct
SCP47548:
There is no compilation error in the given code.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
Given statement:
var list = List.of(new Division(100, 4), new Division(27, 0), new Division(25, 5)); => list refers to a List of Division type.
Static List.of() overloaded methods were added in Java 9 and these return an unmodifiable list containing passed elements. So, above list object referred by ‘list’ is unmodifiable. It is not allowed to invoke add/remove/set methods on the list object returned by List.of() method (no compilation error but an exception is thrown at runtime on invoking add/remove/set methods on list reference) but 3 Division instances are modifiable.
Iterable interface has forEach(Consumer) method. List extends Collection & Collection extends Iterable, therefore forEach(Consumer) can easily be invoked on reference variable of List type.
As Consumer is a Functional Interface, hence a lambda expression can be passed as argument to forEach() method.
forEach(Consumer) method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Lambda expression at Line n1: `d -> d.divide()` is the correct implementation of `void accept(Division t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to divide ‘num’ by ‘den’ and store the result in ‘res’ variable. Hence, statement at Line n1 will populate ‘res’ variable of the three Division objects.
Please note that for the 2nd Division object [num = 27, den = 0], divide() method throws a RuntimeException but it is handled. If you don’t handle it, then stack trace will be printed and program will terminate abruptly.
Lambda expression at Line n2: `d -> System.out.println(d)` is also the correct implementation of `void accept(Division t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to print the Division object on to the console. toString() method of Division object is invoked which prints the state of Division object, in case if den == 0, then “Infinity” is used in place of the value of variable ‘res’.
Statement at Line n2 will print the details of 3 Division instances available in the list.
SCP47548:
There is no compilation error in the given code.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
Given statement:
var list = List.of(new Division(100, 4), new Division(27, 0), new Division(25, 5)); => list refers to a List of Division type.
Static List.of() overloaded methods were added in Java 9 and these return an unmodifiable list containing passed elements. So, above list object referred by ‘list’ is unmodifiable. It is not allowed to invoke add/remove/set methods on the list object returned by List.of() method (no compilation error but an exception is thrown at runtime on invoking add/remove/set methods on list reference) but 3 Division instances are modifiable.
Iterable interface has forEach(Consumer) method. List extends Collection & Collection extends Iterable, therefore forEach(Consumer) can easily be invoked on reference variable of List type.
As Consumer is a Functional Interface, hence a lambda expression can be passed as argument to forEach() method.
forEach(Consumer) method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Lambda expression at Line n1: `d -> d.divide()` is the correct implementation of `void accept(Division t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to divide ‘num’ by ‘den’ and store the result in ‘res’ variable. Hence, statement at Line n1 will populate ‘res’ variable of the three Division objects.
Please note that for the 2nd Division object [num = 27, den = 0], divide() method throws a RuntimeException but it is handled. If you don’t handle it, then stack trace will be printed and program will terminate abruptly.
Lambda expression at Line n2: `d -> System.out.println(d)` is also the correct implementation of `void accept(Division t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to print the Division object on to the console. toString() method of Division object is invoked which prints the state of Division object, in case if den == 0, then “Infinity” is used in place of the value of variable ‘res’.
Statement at Line n2 will print the details of 3 Division instances available in the list.
SCP47548:
There is no compilation error in the given code.
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
Given statement:
var list = List.of(new Division(100, 4), new Division(27, 0), new Division(25, 5)); => list refers to a List of Division type.
Static List.of() overloaded methods were added in Java 9 and these return an unmodifiable list containing passed elements. So, above list object referred by ‘list’ is unmodifiable. It is not allowed to invoke add/remove/set methods on the list object returned by List.of() method (no compilation error but an exception is thrown at runtime on invoking add/remove/set methods on list reference) but 3 Division instances are modifiable.
Iterable interface has forEach(Consumer) method. List extends Collection & Collection extends Iterable, therefore forEach(Consumer) can easily be invoked on reference variable of List type.
As Consumer is a Functional Interface, hence a lambda expression can be passed as argument to forEach() method.
forEach(Consumer) method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Lambda expression at Line n1: `d -> d.divide()` is the correct implementation of `void accept(Division t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to divide ‘num’ by ‘den’ and store the result in ‘res’ variable. Hence, statement at Line n1 will populate ‘res’ variable of the three Division objects.
Please note that for the 2nd Division object [num = 27, den = 0], divide() method throws a RuntimeException but it is handled. If you don’t handle it, then stack trace will be printed and program will terminate abruptly.
Lambda expression at Line n2: `d -> System.out.println(d)` is also the correct implementation of `void accept(Division t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to print the Division object on to the console. toString() method of Division object is invoked which prints the state of Division object, in case if den == 0, then “Infinity” is used in place of the value of variable ‘res’.
Statement at Line n2 will print the details of 3 Division instances available in the list.
public class Test {
public static void main(String[] args) {
List list = new ArrayList<>(4);
list.add(0, “MOVE”);
list.add(2, “ON”);
System.out.println(list);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP45567:
ArrayList are different than arrays, though behind the scene ArrayList uses Object[] to store its elements.
There are 2 things related to ArrayList, one is capacity and another is actual elements stored in the list, returned by size() method. If you don’t pass anything to the ArrayList constructor, then default capacity is 10 but this doesn’t mean that an ArrayList instance will be created containing 10 elements and all will be initialized to null.
In fact, size() method will still return 0 for this list. This list still doesn’t contain even a single element. You need to use add method or its overloaded counterpart to add items to the list. Even if you want to add null values, you should still invoke some methods, nothing happens automatically.
In this question, new ArrayList<>(4); creates an ArrayList instance which can initially store 4 elements but currently it doesn’t store any data.
Another point you should remember for the certification exam: Addition of elements in ArrayList should be continuous. If you are using add(index, Element) method to add items to the list, then index should be continuous, you simply can’t skip any index.
In this case, list.add(0, “MOVE”); adds “MOVE” to 0th index. so after this operation list –> [MOVE]. You can now add at 0th index (existing elements will be shifted right) or you can add at index 1 but not at index 2. list.add(2, “ON”); throws an instance of java.lang.IndexOutOfBoundsException.
Incorrect
SCP45567:
ArrayList are different than arrays, though behind the scene ArrayList uses Object[] to store its elements.
There are 2 things related to ArrayList, one is capacity and another is actual elements stored in the list, returned by size() method. If you don’t pass anything to the ArrayList constructor, then default capacity is 10 but this doesn’t mean that an ArrayList instance will be created containing 10 elements and all will be initialized to null.
In fact, size() method will still return 0 for this list. This list still doesn’t contain even a single element. You need to use add method or its overloaded counterpart to add items to the list. Even if you want to add null values, you should still invoke some methods, nothing happens automatically.
In this question, new ArrayList<>(4); creates an ArrayList instance which can initially store 4 elements but currently it doesn’t store any data.
Another point you should remember for the certification exam: Addition of elements in ArrayList should be continuous. If you are using add(index, Element) method to add items to the list, then index should be continuous, you simply can’t skip any index.
In this case, list.add(0, “MOVE”); adds “MOVE” to 0th index. so after this operation list –> [MOVE]. You can now add at 0th index (existing elements will be shifted right) or you can add at index 1 but not at index 2. list.add(2, “ON”); throws an instance of java.lang.IndexOutOfBoundsException.
Unattempted
SCP45567:
ArrayList are different than arrays, though behind the scene ArrayList uses Object[] to store its elements.
There are 2 things related to ArrayList, one is capacity and another is actual elements stored in the list, returned by size() method. If you don’t pass anything to the ArrayList constructor, then default capacity is 10 but this doesn’t mean that an ArrayList instance will be created containing 10 elements and all will be initialized to null.
In fact, size() method will still return 0 for this list. This list still doesn’t contain even a single element. You need to use add method or its overloaded counterpart to add items to the list. Even if you want to add null values, you should still invoke some methods, nothing happens automatically.
In this question, new ArrayList<>(4); creates an ArrayList instance which can initially store 4 elements but currently it doesn’t store any data.
Another point you should remember for the certification exam: Addition of elements in ArrayList should be continuous. If you are using add(index, Element) method to add items to the list, then index should be continuous, you simply can’t skip any index.
In this case, list.add(0, “MOVE”); adds “MOVE” to 0th index. so after this operation list –> [MOVE]. You can now add at 0th index (existing elements will be shifted right) or you can add at index 1 but not at index 2. list.add(2, “ON”); throws an instance of java.lang.IndexOutOfBoundsException.
class TravelBlogger implements Blogger {
public void blog() {
System.out.println(“TRAVEL”);
}
}
public class Test {
public static void main(String[] args) {
Blogger blogger = new TravelBlogger(); //Line n1
((TravelBlogger)blogger).blog(); //Line n2
}
}
What will be the result of compiling and executing Test class?
Correct
SCP64697:
According to overriding rules, if super class / interface method declares to throw a checked exception, then overriding method of sub class / implementer class has following options:
1. May not declare to throw any checked exception.
2. May declare to throw the same checked exception thrown by super class / interface method.
3. May declare to throw the sub class of the exception thrown by super class / interface method.
4. Cannot declare to throw the super class of the exception thrown by super class / interface method.
5. Cannot declare to throw unrelated checked exception.
6. May declare to throw any RuntimeException or Error.
default methods were added in Java 8 and TravelBlogger class correctly overrides the default method blog() of Blogger interface. Blogger class compiles successfully.
At Line n1, ‘blogger’ is of Blogger type (supertype) and it refers to an instance of TravelBlogger class (subtype), this is polymorphism and allowed in Java. Line n1 compiles successfully.
At Line n2, blog() method is being invoked on typecasting ‘blogger’ to TravelBlogger and as TravelBlogger class doesn’t declare to throw any checked exception, hence Line n2 compiles successfully.
As instance is of TravelBlogger type, therefore on execution, Line n2 invokes blog() method of TravelBlogger instance, which prints TRAVEL on to the console.
Incorrect
SCP64697:
According to overriding rules, if super class / interface method declares to throw a checked exception, then overriding method of sub class / implementer class has following options:
1. May not declare to throw any checked exception.
2. May declare to throw the same checked exception thrown by super class / interface method.
3. May declare to throw the sub class of the exception thrown by super class / interface method.
4. Cannot declare to throw the super class of the exception thrown by super class / interface method.
5. Cannot declare to throw unrelated checked exception.
6. May declare to throw any RuntimeException or Error.
default methods were added in Java 8 and TravelBlogger class correctly overrides the default method blog() of Blogger interface. Blogger class compiles successfully.
At Line n1, ‘blogger’ is of Blogger type (supertype) and it refers to an instance of TravelBlogger class (subtype), this is polymorphism and allowed in Java. Line n1 compiles successfully.
At Line n2, blog() method is being invoked on typecasting ‘blogger’ to TravelBlogger and as TravelBlogger class doesn’t declare to throw any checked exception, hence Line n2 compiles successfully.
As instance is of TravelBlogger type, therefore on execution, Line n2 invokes blog() method of TravelBlogger instance, which prints TRAVEL on to the console.
Unattempted
SCP64697:
According to overriding rules, if super class / interface method declares to throw a checked exception, then overriding method of sub class / implementer class has following options:
1. May not declare to throw any checked exception.
2. May declare to throw the same checked exception thrown by super class / interface method.
3. May declare to throw the sub class of the exception thrown by super class / interface method.
4. Cannot declare to throw the super class of the exception thrown by super class / interface method.
5. Cannot declare to throw unrelated checked exception.
6. May declare to throw any RuntimeException or Error.
default methods were added in Java 8 and TravelBlogger class correctly overrides the default method blog() of Blogger interface. Blogger class compiles successfully.
At Line n1, ‘blogger’ is of Blogger type (supertype) and it refers to an instance of TravelBlogger class (subtype), this is polymorphism and allowed in Java. Line n1 compiles successfully.
At Line n2, blog() method is being invoked on typecasting ‘blogger’ to TravelBlogger and as TravelBlogger class doesn’t declare to throw any checked exception, hence Line n2 compiles successfully.
As instance is of TravelBlogger type, therefore on execution, Line n2 invokes blog() method of TravelBlogger instance, which prints TRAVEL on to the console.
Question 18 of 65
18. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
interface MyInterface {
void calculate();
}
public class Test {
public static void main(String[] args) {
MyInterface obj = () -> {
int i = 10;
i++;
System.out.println(i);
return;
};
obj.calculate();
}
}
What will be the result of compiling and executing Test class?
Correct
SCP62949:
No issues with lambda syntax: curly brackets and semicolon are available.
As calculate()) method of MyInterface interface returns void, hence `return;` statement works even though it is not mandatory.
Variable ‘i’ is declared within the body of lambda expression so don’t confuse it with local variable of main method. i is declared and initialized to 10, i is incremented by 1 (i becomes 11) and finally value of ‘i’ is printed.
Incorrect
SCP62949:
No issues with lambda syntax: curly brackets and semicolon are available.
As calculate()) method of MyInterface interface returns void, hence `return;` statement works even though it is not mandatory.
Variable ‘i’ is declared within the body of lambda expression so don’t confuse it with local variable of main method. i is declared and initialized to 10, i is incremented by 1 (i becomes 11) and finally value of ‘i’ is printed.
Unattempted
SCP62949:
No issues with lambda syntax: curly brackets and semicolon are available.
As calculate()) method of MyInterface interface returns void, hence `return;` statement works even though it is not mandatory.
Variable ‘i’ is declared within the body of lambda expression so don’t confuse it with local variable of main method. i is declared and initialized to 10, i is incremented by 1 (i becomes 11) and finally value of ‘i’ is printed.
Question 19 of 65
19. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
boolean[] arr1 = { true, false, true, false };
boolean[] arr2 = { true, true, true, false };
if (!Arrays.equals(arr1, arr2)) {
System.out.println(Arrays.compare(arr1, arr2));
} else {
System.out.println(Arrays.mismatch(arr1, arr2));
}
}
}
What will be the result of compiling and executing above code?
Correct
SCP65587:
Arrays class has following overloaded equals methods for primitive type arrays:
boolean equals?(boolean[] a, boolean[] b)
boolean equals?(byte[] a, byte[] b)
boolean equals?(short[] a, short[] b)
boolean equals?(char[] a, char[] b)
boolean equals?(int[] a, int[] b)
boolean equals?(long[] a, long[] b)
boolean equals?(float[] a, float[] b)
boolean equals?(double[] a, double[] b)
Above methods return true if both of the arrays are null or both contain the same elements in the same order, otherwise return false.
Arrays class has following overloaded compare methods for primitive type arrays:
int compare?(boolean[] a, boolean[] b)
int compare?(byte[] a, byte[] b)
int compare?(short[] a, short[] b)
int compare?(char[] a, char[] b)
int compare?(int[] a, int[] b)
int compare?(long[] a, long[] b)
int compare?(float[] a, float[] b)
int compare?(double[] a, double[] b)
All of these compare methods of Arrays class compare the arrays lexicographically and return below values:
0: if the first and second array are equal and contain the same elements in the same order
<0: if the first array is lexicographically less than the second array
>0: if the first array is lexicographically greater than the second array
For comparing the array contents, these methods take help of static compare(x, y) method defined in respective Wrapper classes. For example, Arrays.compare(boolean[] a, boolean[] b) uses Boolean.compare(boolean x, boolean y) to compare array contents.
So, for the exam, you need to have an idea of how static compare(…) methods are implemented in these wrapper classes:
For Character, Byte & Short; compare method returns x – y.
For Integer and Long; compare method returns -1 if x < y, it returns 1 if x > y and it returns 0 if x == y.
For Float and Double; logic is almost same as Integer type but logic is bit complex for finding equality of two floats or two doubles (not part of the exam).
For Boolean; compare method returns 0 if x == y, 1 if x is true and -1 if x is false.
Arrays class has following overloaded mismatch methods for primitive type arrays:
int mismatch?(boolean[] a, boolean[] b)
int mismatch?(byte[] a, byte[] b)
int mismatch?(short[] a, short[] b)
int mismatch?(char[] a, char[] b)
int mismatch?(int[] a, int[] b)
int mismatch?(long[] a, long[] b)
int mismatch?(float[] a, float[] b)
int mismatch?(double[] a, double[] b)
Above methods find and return the index of the first mismatch between two primitive arrays, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array. It throws NullPointerException, if either array is null.
Based on above statements let’s check given codes:
2nd element (at index 1) of the arrays are not same, therefore Arrays.equals(arr1, arr2) returns false.
But the boolean expression of if-block starts with !, which translates the if-block as below:
if (!Arrays.equals(arr1, arr2)) => if (!false) => if (true)
Therefore code inside if-block is executed, which is
System.out.println(Arrays.compare(arr1, arr2)); This returns -1, which is the result of Boolean.compare(false, true).
Incorrect
SCP65587:
Arrays class has following overloaded equals methods for primitive type arrays:
boolean equals?(boolean[] a, boolean[] b)
boolean equals?(byte[] a, byte[] b)
boolean equals?(short[] a, short[] b)
boolean equals?(char[] a, char[] b)
boolean equals?(int[] a, int[] b)
boolean equals?(long[] a, long[] b)
boolean equals?(float[] a, float[] b)
boolean equals?(double[] a, double[] b)
Above methods return true if both of the arrays are null or both contain the same elements in the same order, otherwise return false.
Arrays class has following overloaded compare methods for primitive type arrays:
int compare?(boolean[] a, boolean[] b)
int compare?(byte[] a, byte[] b)
int compare?(short[] a, short[] b)
int compare?(char[] a, char[] b)
int compare?(int[] a, int[] b)
int compare?(long[] a, long[] b)
int compare?(float[] a, float[] b)
int compare?(double[] a, double[] b)
All of these compare methods of Arrays class compare the arrays lexicographically and return below values:
0: if the first and second array are equal and contain the same elements in the same order
<0: if the first array is lexicographically less than the second array
>0: if the first array is lexicographically greater than the second array
For comparing the array contents, these methods take help of static compare(x, y) method defined in respective Wrapper classes. For example, Arrays.compare(boolean[] a, boolean[] b) uses Boolean.compare(boolean x, boolean y) to compare array contents.
So, for the exam, you need to have an idea of how static compare(…) methods are implemented in these wrapper classes:
For Character, Byte & Short; compare method returns x – y.
For Integer and Long; compare method returns -1 if x < y, it returns 1 if x > y and it returns 0 if x == y.
For Float and Double; logic is almost same as Integer type but logic is bit complex for finding equality of two floats or two doubles (not part of the exam).
For Boolean; compare method returns 0 if x == y, 1 if x is true and -1 if x is false.
Arrays class has following overloaded mismatch methods for primitive type arrays:
int mismatch?(boolean[] a, boolean[] b)
int mismatch?(byte[] a, byte[] b)
int mismatch?(short[] a, short[] b)
int mismatch?(char[] a, char[] b)
int mismatch?(int[] a, int[] b)
int mismatch?(long[] a, long[] b)
int mismatch?(float[] a, float[] b)
int mismatch?(double[] a, double[] b)
Above methods find and return the index of the first mismatch between two primitive arrays, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array. It throws NullPointerException, if either array is null.
Based on above statements let’s check given codes:
2nd element (at index 1) of the arrays are not same, therefore Arrays.equals(arr1, arr2) returns false.
But the boolean expression of if-block starts with !, which translates the if-block as below:
if (!Arrays.equals(arr1, arr2)) => if (!false) => if (true)
Therefore code inside if-block is executed, which is
System.out.println(Arrays.compare(arr1, arr2)); This returns -1, which is the result of Boolean.compare(false, true).
Unattempted
SCP65587:
Arrays class has following overloaded equals methods for primitive type arrays:
boolean equals?(boolean[] a, boolean[] b)
boolean equals?(byte[] a, byte[] b)
boolean equals?(short[] a, short[] b)
boolean equals?(char[] a, char[] b)
boolean equals?(int[] a, int[] b)
boolean equals?(long[] a, long[] b)
boolean equals?(float[] a, float[] b)
boolean equals?(double[] a, double[] b)
Above methods return true if both of the arrays are null or both contain the same elements in the same order, otherwise return false.
Arrays class has following overloaded compare methods for primitive type arrays:
int compare?(boolean[] a, boolean[] b)
int compare?(byte[] a, byte[] b)
int compare?(short[] a, short[] b)
int compare?(char[] a, char[] b)
int compare?(int[] a, int[] b)
int compare?(long[] a, long[] b)
int compare?(float[] a, float[] b)
int compare?(double[] a, double[] b)
All of these compare methods of Arrays class compare the arrays lexicographically and return below values:
0: if the first and second array are equal and contain the same elements in the same order
<0: if the first array is lexicographically less than the second array
>0: if the first array is lexicographically greater than the second array
For comparing the array contents, these methods take help of static compare(x, y) method defined in respective Wrapper classes. For example, Arrays.compare(boolean[] a, boolean[] b) uses Boolean.compare(boolean x, boolean y) to compare array contents.
So, for the exam, you need to have an idea of how static compare(…) methods are implemented in these wrapper classes:
For Character, Byte & Short; compare method returns x – y.
For Integer and Long; compare method returns -1 if x < y, it returns 1 if x > y and it returns 0 if x == y.
For Float and Double; logic is almost same as Integer type but logic is bit complex for finding equality of two floats or two doubles (not part of the exam).
For Boolean; compare method returns 0 if x == y, 1 if x is true and -1 if x is false.
Arrays class has following overloaded mismatch methods for primitive type arrays:
int mismatch?(boolean[] a, boolean[] b)
int mismatch?(byte[] a, byte[] b)
int mismatch?(short[] a, short[] b)
int mismatch?(char[] a, char[] b)
int mismatch?(int[] a, int[] b)
int mismatch?(long[] a, long[] b)
int mismatch?(float[] a, float[] b)
int mismatch?(double[] a, double[] b)
Above methods find and return the index of the first mismatch between two primitive arrays, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array. It throws NullPointerException, if either array is null.
Based on above statements let’s check given codes:
2nd element (at index 1) of the arrays are not same, therefore Arrays.equals(arr1, arr2) returns false.
But the boolean expression of if-block starts with !, which translates the if-block as below:
if (!Arrays.equals(arr1, arr2)) => if (!false) => if (true)
Therefore code inside if-block is executed, which is
System.out.println(Arrays.compare(arr1, arr2)); This returns -1, which is the result of Boolean.compare(false, true).
Question 20 of 65
20. Question
Consider below code of Test.java file:
public class Test {
public static void main(String[] args) {
System.out.println(“Welcome ” + args[0] +”!”);
}
}
And the commands:
javac Test.java
java Test “James Gosling” “Bill Joy”
What is the result?
Correct
SCP53849:
Please note, if passed command line arguments contain space(s) in between, then it is a common practice to enclosed within double quotes. In this case “James Gosling” is passed as one String object and “Bill Joy” is also passed as one String object.
java Test “James Gosling” “Bill Joy” passes new String [] {“James Gosling”, “Bill Joy”} to args of main method. args[0] refers to “James Gosling” and args[1] refers to “Bill Joy”.
Hence, Welcome James Gosling! is printed on to the console. While printing the String object, enclosing quotes are not shown.
To use quotes as part of the String, you can escape those using backslash, such as:
java Test “\”James Gosling”\” “\”Bill Joy”\”
Above command will print Welcome “James Gosling”! on to the console.
Incorrect
SCP53849:
Please note, if passed command line arguments contain space(s) in between, then it is a common practice to enclosed within double quotes. In this case “James Gosling” is passed as one String object and “Bill Joy” is also passed as one String object.
java Test “James Gosling” “Bill Joy” passes new String [] {“James Gosling”, “Bill Joy”} to args of main method. args[0] refers to “James Gosling” and args[1] refers to “Bill Joy”.
Hence, Welcome James Gosling! is printed on to the console. While printing the String object, enclosing quotes are not shown.
To use quotes as part of the String, you can escape those using backslash, such as:
java Test “\”James Gosling”\” “\”Bill Joy”\”
Above command will print Welcome “James Gosling”! on to the console.
Unattempted
SCP53849:
Please note, if passed command line arguments contain space(s) in between, then it is a common practice to enclosed within double quotes. In this case “James Gosling” is passed as one String object and “Bill Joy” is also passed as one String object.
java Test “James Gosling” “Bill Joy” passes new String [] {“James Gosling”, “Bill Joy”} to args of main method. args[0] refers to “James Gosling” and args[1] refers to “Bill Joy”.
Hence, Welcome James Gosling! is printed on to the console. While printing the String object, enclosing quotes are not shown.
To use quotes as part of the String, you can escape those using backslash, such as:
java Test “\”James Gosling”\” “\”Bill Joy”\”
Above command will print Welcome “James Gosling”! on to the console.
public class Test {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(0, ‘V’);
list.add(‘T’);
list.add(1, ‘E’);
list.add(3, ‘O’);
if(list.contains(‘O’)) {
list.remove(3);
}
for(char ch : list) {
System.out.print(ch);
}
}
}
What will be the result of compiling and executing Test class?
Correct
SCP26829:
list.add(0, ‘V’); => char ‘V’ is converted to Character object and stored as the first element in the list. list –> [V].
list.add(‘T’); => char ‘T’ is auto-boxed to Character object and stored at the end of the list. list –> [V,T].
list.add(1, ‘E’); => char ‘E’ is auto-boxed to Character object and inserted at index 1 of the list, this shifts T to the right. list –> [V,E,T].
list.add(3, ‘O’); => char ‘O’ is auto-boxed to Character object and added at index 3 of the list. list –> [V,E,T,O].
list.contains(‘O’) => char ‘O’ is auto-boxed to Character object and as Character class overrides equals(String) method this expression returns true. Control goes inside if-block and executes: list.remove(3);.
list.remove(3); => Removes last element of the list. list –> [V,E,T].
for(char ch : list) => First list item is Character object, which is auto-unboxed and assigned to ch. This means in first iteration ch = ‘V’; And after this it is simple enhanced for loop. Output is VET.
Incorrect
SCP26829:
list.add(0, ‘V’); => char ‘V’ is converted to Character object and stored as the first element in the list. list –> [V].
list.add(‘T’); => char ‘T’ is auto-boxed to Character object and stored at the end of the list. list –> [V,T].
list.add(1, ‘E’); => char ‘E’ is auto-boxed to Character object and inserted at index 1 of the list, this shifts T to the right. list –> [V,E,T].
list.add(3, ‘O’); => char ‘O’ is auto-boxed to Character object and added at index 3 of the list. list –> [V,E,T,O].
list.contains(‘O’) => char ‘O’ is auto-boxed to Character object and as Character class overrides equals(String) method this expression returns true. Control goes inside if-block and executes: list.remove(3);.
list.remove(3); => Removes last element of the list. list –> [V,E,T].
for(char ch : list) => First list item is Character object, which is auto-unboxed and assigned to ch. This means in first iteration ch = ‘V’; And after this it is simple enhanced for loop. Output is VET.
Unattempted
SCP26829:
list.add(0, ‘V’); => char ‘V’ is converted to Character object and stored as the first element in the list. list –> [V].
list.add(‘T’); => char ‘T’ is auto-boxed to Character object and stored at the end of the list. list –> [V,T].
list.add(1, ‘E’); => char ‘E’ is auto-boxed to Character object and inserted at index 1 of the list, this shifts T to the right. list –> [V,E,T].
list.add(3, ‘O’); => char ‘O’ is auto-boxed to Character object and added at index 3 of the list. list –> [V,E,T,O].
list.contains(‘O’) => char ‘O’ is auto-boxed to Character object and as Character class overrides equals(String) method this expression returns true. Control goes inside if-block and executes: list.remove(3);.
list.remove(3); => Removes last element of the list. list –> [V,E,T].
for(char ch : list) => First list item is Character object, which is auto-unboxed and assigned to ch. This means in first iteration ch = ‘V’; And after this it is simple enhanced for loop. Output is VET.
public class Test {
public static void main(String[] args) {
X1 obj = new X();
obj.print();
}
}
Which of the following statements is correct?
Correct
SCP24627:
As per Java 8, default methods were added in the interface. Interface X1 defines default method print(), there is no compilation error in interface X1. Method print() is implicitly public in X1.
interface X2 extends X1 and it overrides the default method print() of X1, overriding method in X2 is implicitly abstract and public. An interface in java can override the default method of super type with abstract modifier. interface X2 compiles successfully.
interface X3 extends X2 and it implements the abstract method print() of X2, overriding method in X3 is default and implicitly public. An interface in java can implement the abstract method of super type with default modifier. interface X3 compiles successfully.
class X implements X3 and therefore it inherits the default method print() defined in interface X3.
`X1 obj = new X();` compiles successfully as X1 is of super type (X implements X3, X3 extends X2 and X2 extends X1).
`obj.print();` invokes the default method print() defined in interface X3 and hence X3 is printed on to the console.
Incorrect
SCP24627:
As per Java 8, default methods were added in the interface. Interface X1 defines default method print(), there is no compilation error in interface X1. Method print() is implicitly public in X1.
interface X2 extends X1 and it overrides the default method print() of X1, overriding method in X2 is implicitly abstract and public. An interface in java can override the default method of super type with abstract modifier. interface X2 compiles successfully.
interface X3 extends X2 and it implements the abstract method print() of X2, overriding method in X3 is default and implicitly public. An interface in java can implement the abstract method of super type with default modifier. interface X3 compiles successfully.
class X implements X3 and therefore it inherits the default method print() defined in interface X3.
`X1 obj = new X();` compiles successfully as X1 is of super type (X implements X3, X3 extends X2 and X2 extends X1).
`obj.print();` invokes the default method print() defined in interface X3 and hence X3 is printed on to the console.
Unattempted
SCP24627:
As per Java 8, default methods were added in the interface. Interface X1 defines default method print(), there is no compilation error in interface X1. Method print() is implicitly public in X1.
interface X2 extends X1 and it overrides the default method print() of X1, overriding method in X2 is implicitly abstract and public. An interface in java can override the default method of super type with abstract modifier. interface X2 compiles successfully.
interface X3 extends X2 and it implements the abstract method print() of X2, overriding method in X3 is default and implicitly public. An interface in java can implement the abstract method of super type with default modifier. interface X3 compiles successfully.
class X implements X3 and therefore it inherits the default method print() defined in interface X3.
`X1 obj = new X();` compiles successfully as X1 is of super type (X implements X3, X3 extends X2 and X2 extends X1).
`obj.print();` invokes the default method print() defined in interface X3 and hence X3 is printed on to the console.
Question 23 of 65
23. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
var: while (true) { //Line n1
i: for (int i = 0; i <= 2; i++) {
if(i == 2) {
/*INSERT*/
}
}
}
System.out.println("THINK DIFFERENT"); //Line n2
}
}
Which of the following options, if used to replace /*INSERT*/, will compile successfully and on execution will print THINK DIFFERENT on to the console?
Correct
SCP37766:
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
The identifier var is not a keyword, hence var can still be used as variable name, method name, package name or loop’s label but it cannot be used as a class or interface name.
At Line n1, ‘var’ is used as while loop’s label, so no issues at Line n1.
while(true) is and infinite loop and compiler is aware of that, so unless and until you provide the logic to break out of the loop, compiler considers Line n2 as unreachable code, which causes compilation failure.
continue statements don’t break out of the loop so even if you use `continue;`, `continue i;` or `continue var;` to replace /*INSERT*/, unreachable code error will still be there.
`break;` and `break i;` statements are same and will break out to the inner for loop, Line n2 will still be unreachable.
`break var;` will successfully break out of the outer while loop.
On execution, control will come out of the while loop, when i equals to 2 and THINK DIFFERENT will be printed on to the console.
Incorrect
SCP37766:
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
The identifier var is not a keyword, hence var can still be used as variable name, method name, package name or loop’s label but it cannot be used as a class or interface name.
At Line n1, ‘var’ is used as while loop’s label, so no issues at Line n1.
while(true) is and infinite loop and compiler is aware of that, so unless and until you provide the logic to break out of the loop, compiler considers Line n2 as unreachable code, which causes compilation failure.
continue statements don’t break out of the loop so even if you use `continue;`, `continue i;` or `continue var;` to replace /*INSERT*/, unreachable code error will still be there.
`break;` and `break i;` statements are same and will break out to the inner for loop, Line n2 will still be unreachable.
`break var;` will successfully break out of the outer while loop.
On execution, control will come out of the while loop, when i equals to 2 and THINK DIFFERENT will be printed on to the console.
Unattempted
SCP37766:
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = “Java”; //x infers to String
var m = 10; //m infers to int
The identifier var is not a keyword, hence var can still be used as variable name, method name, package name or loop’s label but it cannot be used as a class or interface name.
At Line n1, ‘var’ is used as while loop’s label, so no issues at Line n1.
while(true) is and infinite loop and compiler is aware of that, so unless and until you provide the logic to break out of the loop, compiler considers Line n2 as unreachable code, which causes compilation failure.
continue statements don’t break out of the loop so even if you use `continue;`, `continue i;` or `continue var;` to replace /*INSERT*/, unreachable code error will still be there.
`break;` and `break i;` statements are same and will break out to the inner for loop, Line n2 will still be unreachable.
`break var;` will successfully break out of the outer while loop.
On execution, control will come out of the while loop, when i equals to 2 and THINK DIFFERENT will be printed on to the console.
Question 24 of 65
24. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
class Paper {
static String getType() { //Line n1
return “GENERIC”;
}
}
class RuledPaper extends Paper {
String getType() { //Line n2
return “RULED”;
}
}
public class Test {
public static void main(String[] args) {
Paper paper = new RuledPaper(); //Line n3
System.out.println(paper.getType()); //Line n4
}
}
Which of the following statements is true for above code?
Correct
SCP20256:
Instance method of subclass cannot override the static method of superclass.
Instance method at Line n2 tries to override the static method at Line n1 and hence Line n2 causes compilation error.
There is no issue with Line n3 as reference variable of superclass can refer to an instance of subclass.
At Line n4, paper.getType() doesn’t cause compilation error but as this syntax creates confusion, so it is not a good practice to access the static variables or static methods using reference variable, instead class name should be used. Paper.getType() is the preferred syntax.
Incorrect
SCP20256:
Instance method of subclass cannot override the static method of superclass.
Instance method at Line n2 tries to override the static method at Line n1 and hence Line n2 causes compilation error.
There is no issue with Line n3 as reference variable of superclass can refer to an instance of subclass.
At Line n4, paper.getType() doesn’t cause compilation error but as this syntax creates confusion, so it is not a good practice to access the static variables or static methods using reference variable, instead class name should be used. Paper.getType() is the preferred syntax.
Unattempted
SCP20256:
Instance method of subclass cannot override the static method of superclass.
Instance method at Line n2 tries to override the static method at Line n1 and hence Line n2 causes compilation error.
There is no issue with Line n3 as reference variable of superclass can refer to an instance of subclass.
At Line n4, paper.getType() doesn’t cause compilation error but as this syntax creates confusion, so it is not a good practice to access the static variables or static methods using reference variable, instead class name should be used. Paper.getType() is the preferred syntax.
What will be the result of compiling and executing Test class?
Correct
SCP34007:
Though Predicate is a generic interface but raw type is also allowed. Type of the variable in lambda expression is inferred by the generic type of Predicate interface.
In this case, Predicate pr1 = s -> s.length() < 4; Predicate is considered of Object type so variable 's' is of Object type and Object class doesn't have length() method. So, `s.length()` causes compilation error.
Incorrect
SCP34007:
Though Predicate is a generic interface but raw type is also allowed. Type of the variable in lambda expression is inferred by the generic type of Predicate interface.
In this case, Predicate pr1 = s -> s.length() < 4; Predicate is considered of Object type so variable 's' is of Object type and Object class doesn't have length() method. So, `s.length()` causes compilation error.
Unattempted
SCP34007:
Though Predicate is a generic interface but raw type is also allowed. Type of the variable in lambda expression is inferred by the generic type of Predicate interface.
In this case, Predicate pr1 = s -> s.length() < 4; Predicate is considered of Object type so variable 's' is of Object type and Object class doesn't have length() method. So, `s.length()` causes compilation error.
Which of the following statements are correct about above snippets?
Select ALL that apply.
Correct
SCP16013:
Static overloaded method join(…) was added in JDK 1.8 and has below declarations:
1. public static String join(CharSequence delimiter, CharSequence… elements) {…}: It returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example,
String.join(“.”, “A”, “B”, “C”); returns “A.B.C”
String.join(“+”, new String[]{“1”, “2”, “3”}); returns “1+2+3”
String.join(“-“, “HELLO”); returns “HELLO”
If delimiter is null or elements refer to null, then NullPointerException is thrown. e.g.,
String.join(null, “A”, “B”); throws NullPointerException
String [] arr = null; String.join(“-“, arr); throws NullPointerException
But if single element is null, then “null” is considered. e.g.,
String str = null; String.join(“-“, str); returns “null”
String.join(“::”, new String[] {“James”, null, “Gosling”}); returns “James::null::Gosling”
2. public static String join?(CharSequence delimiter, Iterable extends CharSequence> elements) {…}: It returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example,
String.join(“.”, List.of(“A”, “B”, “C”)); returns “A.B.C”
String.join(“.”, List.of(“HELLO”)); returns “HELLO”
If delimiter is null or elements refer to null, then NullPointerException is thrown. e.g.,
String.join(null, List.of(“HELLO”)); throws NullPointerException
List list = null; String.join(“-“, list); throws NullPointerException
But if single element is null, then “null” is considered. e.g.,
List list = new ArrayList<>(); list.add(“A”); list.add(null); String.join(“::”, list); returns “A::null”
Please note: String.join(“-“, null); causes compilation error as compiler is unable to tag this call to specific join(…) method. It is an ambiguous call.
Based on above points:
Snippet 1 compiles successfully and on execution prints “1. null::null” on to the console.
Snippet 2 compiles successfully and on execution prints “2. ” on to the console.
Snippet 3 compiles successfully and on execution throws NullPointerException as elements refer to null
Snippet 4 causes compilation error as `String.join(“.”, null)` is an ambiguous call and compiler is not sure about which overloaded join(…) method should be tagged for this call.
Incorrect
SCP16013:
Static overloaded method join(…) was added in JDK 1.8 and has below declarations:
1. public static String join(CharSequence delimiter, CharSequence… elements) {…}: It returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example,
String.join(“.”, “A”, “B”, “C”); returns “A.B.C”
String.join(“+”, new String[]{“1”, “2”, “3”}); returns “1+2+3”
String.join(“-“, “HELLO”); returns “HELLO”
If delimiter is null or elements refer to null, then NullPointerException is thrown. e.g.,
String.join(null, “A”, “B”); throws NullPointerException
String [] arr = null; String.join(“-“, arr); throws NullPointerException
But if single element is null, then “null” is considered. e.g.,
String str = null; String.join(“-“, str); returns “null”
String.join(“::”, new String[] {“James”, null, “Gosling”}); returns “James::null::Gosling”
2. public static String join?(CharSequence delimiter, Iterable extends CharSequence> elements) {…}: It returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example,
String.join(“.”, List.of(“A”, “B”, “C”)); returns “A.B.C”
String.join(“.”, List.of(“HELLO”)); returns “HELLO”
If delimiter is null or elements refer to null, then NullPointerException is thrown. e.g.,
String.join(null, List.of(“HELLO”)); throws NullPointerException
List list = null; String.join(“-“, list); throws NullPointerException
But if single element is null, then “null” is considered. e.g.,
List list = new ArrayList<>(); list.add(“A”); list.add(null); String.join(“::”, list); returns “A::null”
Please note: String.join(“-“, null); causes compilation error as compiler is unable to tag this call to specific join(…) method. It is an ambiguous call.
Based on above points:
Snippet 1 compiles successfully and on execution prints “1. null::null” on to the console.
Snippet 2 compiles successfully and on execution prints “2. ” on to the console.
Snippet 3 compiles successfully and on execution throws NullPointerException as elements refer to null
Snippet 4 causes compilation error as `String.join(“.”, null)` is an ambiguous call and compiler is not sure about which overloaded join(…) method should be tagged for this call.
Unattempted
SCP16013:
Static overloaded method join(…) was added in JDK 1.8 and has below declarations:
1. public static String join(CharSequence delimiter, CharSequence… elements) {…}: It returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example,
String.join(“.”, “A”, “B”, “C”); returns “A.B.C”
String.join(“+”, new String[]{“1”, “2”, “3”}); returns “1+2+3”
String.join(“-“, “HELLO”); returns “HELLO”
If delimiter is null or elements refer to null, then NullPointerException is thrown. e.g.,
String.join(null, “A”, “B”); throws NullPointerException
String [] arr = null; String.join(“-“, arr); throws NullPointerException
But if single element is null, then “null” is considered. e.g.,
String str = null; String.join(“-“, str); returns “null”
String.join(“::”, new String[] {“James”, null, “Gosling”}); returns “James::null::Gosling”
2. public static String join?(CharSequence delimiter, Iterable extends CharSequence> elements) {…}: It returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example,
String.join(“.”, List.of(“A”, “B”, “C”)); returns “A.B.C”
String.join(“.”, List.of(“HELLO”)); returns “HELLO”
If delimiter is null or elements refer to null, then NullPointerException is thrown. e.g.,
String.join(null, List.of(“HELLO”)); throws NullPointerException
List list = null; String.join(“-“, list); throws NullPointerException
But if single element is null, then “null” is considered. e.g.,
List list = new ArrayList<>(); list.add(“A”); list.add(null); String.join(“::”, list); returns “A::null”
Please note: String.join(“-“, null); causes compilation error as compiler is unable to tag this call to specific join(…) method. It is an ambiguous call.
Based on above points:
Snippet 1 compiles successfully and on execution prints “1. null::null” on to the console.
Snippet 2 compiles successfully and on execution prints “2. ” on to the console.
Snippet 3 compiles successfully and on execution throws NullPointerException as elements refer to null
Snippet 4 causes compilation error as `String.join(“.”, null)` is an ambiguous call and compiler is not sure about which overloaded join(…) method should be tagged for this call.
public abstract class Profit implements Profitable1, Profitable2 {
/*INSERT*/
}
Which of the following needs to be done so that there is no compilation error?
Correct
SCP72708:
Profit class causes compilation error as it complains about duplicate default methods: Profitable1.profit() and Profitable2.profit(). To rectify this error abstract class Profit must override the profit() method.
default keyword for method is allowed only inside the interface and default methods are implicitly public. So overriding method should use public modifier and shouldn’t use default keyword.
If you want to invoke the default method implementation from the overriding method, then the correct syntax is: [Interface_name].super.[default_method_name].
Hence, `Profitable1.super.profit();` will invoke the default method of Profitable1 interface and `Profitable2.super.profit();` will invoke the default method of Profitable2 interface.
Based on above points, let’s check all the options one by one:
No need for any modifications, code compiles as is: ?
Replace /*INSERT*/ with below code:
double profit() {
return 50.0;
}: ?
profit() method must be declared with public access modifier.
Replace /*INSERT*/ with below code:
public default double profit() {
return 50.0;
}: ?
default keyword for method is allowed only inside the interface.
Replace /*INSERT*/ with below code:
protected double profit() {
return 50.0;
}: ?
profit() method must be declared with public access modifier.
Replace /*INSERT*/ with below code:
public double profit() {
return Profitable1.profit();
}: ?
Profitable1.profit(); causes compilation error as correct syntax is: Profitable1.super.profit();
Replace /*INSERT*/ with below code:
public double profit() {
return Profitable2.super.profit();
}: ?
It compiles successfully.
Incorrect
SCP72708:
Profit class causes compilation error as it complains about duplicate default methods: Profitable1.profit() and Profitable2.profit(). To rectify this error abstract class Profit must override the profit() method.
default keyword for method is allowed only inside the interface and default methods are implicitly public. So overriding method should use public modifier and shouldn’t use default keyword.
If you want to invoke the default method implementation from the overriding method, then the correct syntax is: [Interface_name].super.[default_method_name].
Hence, `Profitable1.super.profit();` will invoke the default method of Profitable1 interface and `Profitable2.super.profit();` will invoke the default method of Profitable2 interface.
Based on above points, let’s check all the options one by one:
No need for any modifications, code compiles as is: ?
Replace /*INSERT*/ with below code:
double profit() {
return 50.0;
}: ?
profit() method must be declared with public access modifier.
Replace /*INSERT*/ with below code:
public default double profit() {
return 50.0;
}: ?
default keyword for method is allowed only inside the interface.
Replace /*INSERT*/ with below code:
protected double profit() {
return 50.0;
}: ?
profit() method must be declared with public access modifier.
Replace /*INSERT*/ with below code:
public double profit() {
return Profitable1.profit();
}: ?
Profitable1.profit(); causes compilation error as correct syntax is: Profitable1.super.profit();
Replace /*INSERT*/ with below code:
public double profit() {
return Profitable2.super.profit();
}: ?
It compiles successfully.
Unattempted
SCP72708:
Profit class causes compilation error as it complains about duplicate default methods: Profitable1.profit() and Profitable2.profit(). To rectify this error abstract class Profit must override the profit() method.
default keyword for method is allowed only inside the interface and default methods are implicitly public. So overriding method should use public modifier and shouldn’t use default keyword.
If you want to invoke the default method implementation from the overriding method, then the correct syntax is: [Interface_name].super.[default_method_name].
Hence, `Profitable1.super.profit();` will invoke the default method of Profitable1 interface and `Profitable2.super.profit();` will invoke the default method of Profitable2 interface.
Based on above points, let’s check all the options one by one:
No need for any modifications, code compiles as is: ?
Replace /*INSERT*/ with below code:
double profit() {
return 50.0;
}: ?
profit() method must be declared with public access modifier.
Replace /*INSERT*/ with below code:
public default double profit() {
return 50.0;
}: ?
default keyword for method is allowed only inside the interface.
Replace /*INSERT*/ with below code:
protected double profit() {
return 50.0;
}: ?
profit() method must be declared with public access modifier.
Replace /*INSERT*/ with below code:
public double profit() {
return Profitable1.profit();
}: ?
Profitable1.profit(); causes compilation error as correct syntax is: Profitable1.super.profit();
Replace /*INSERT*/ with below code:
public double profit() {
return Profitable2.super.profit();
}: ?
It compiles successfully.
Question 28 of 65
28. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
final int i1 = 1;
final Integer i2 = 1;
final String s1 = “:ONE”;
What will be the result of compiling and executing Test class?
Correct
SCP64502:
Please note that Strings computed by concatenation at compile time, will be referred by String Pool during execution. Compile time String concatenation happens when both of the operands are compile time constants, such as literal, final variable etc.
Whereas, Strings computed by concatenation at run time (if the resultant expression is not constant expression) are newly created and therefore distinct.
For the statement, String str1 = i1 + s1;, i1 is a final variable of int type and s1 is a final variable of String type. Hence, `i1 + s1` is a constant expression which is computed at compile-time and results in String literal “1:ONE”.
This means during compilation, Java compiler translates the statement
String str1 = i1 + s1;
to
String str1 = “1:ONE”;
As “1:ONE” is a String literal, hence at runtime it will be referred by String Pool.
On the other hand, for the statement, String str2 = i2 + s1;, `i2 + s1` is not a constant expression because i2 is neither of primitive type nor of String type, hence it is computed at run-time and returns a non-pool String object “1:ONE”.
As, str1 refers to String Pool object “1:ONE”, hence `str1 == “1:ONE”` returns true, whereas str2 refers to non-Pool String object “1:ONE” and hence `str2 == “1:ONE”` returns false.
Incorrect
SCP64502:
Please note that Strings computed by concatenation at compile time, will be referred by String Pool during execution. Compile time String concatenation happens when both of the operands are compile time constants, such as literal, final variable etc.
Whereas, Strings computed by concatenation at run time (if the resultant expression is not constant expression) are newly created and therefore distinct.
For the statement, String str1 = i1 + s1;, i1 is a final variable of int type and s1 is a final variable of String type. Hence, `i1 + s1` is a constant expression which is computed at compile-time and results in String literal “1:ONE”.
This means during compilation, Java compiler translates the statement
String str1 = i1 + s1;
to
String str1 = “1:ONE”;
As “1:ONE” is a String literal, hence at runtime it will be referred by String Pool.
On the other hand, for the statement, String str2 = i2 + s1;, `i2 + s1` is not a constant expression because i2 is neither of primitive type nor of String type, hence it is computed at run-time and returns a non-pool String object “1:ONE”.
As, str1 refers to String Pool object “1:ONE”, hence `str1 == “1:ONE”` returns true, whereas str2 refers to non-Pool String object “1:ONE” and hence `str2 == “1:ONE”` returns false.
Unattempted
SCP64502:
Please note that Strings computed by concatenation at compile time, will be referred by String Pool during execution. Compile time String concatenation happens when both of the operands are compile time constants, such as literal, final variable etc.
Whereas, Strings computed by concatenation at run time (if the resultant expression is not constant expression) are newly created and therefore distinct.
For the statement, String str1 = i1 + s1;, i1 is a final variable of int type and s1 is a final variable of String type. Hence, `i1 + s1` is a constant expression which is computed at compile-time and results in String literal “1:ONE”.
This means during compilation, Java compiler translates the statement
String str1 = i1 + s1;
to
String str1 = “1:ONE”;
As “1:ONE” is a String literal, hence at runtime it will be referred by String Pool.
On the other hand, for the statement, String str2 = i2 + s1;, `i2 + s1` is not a constant expression because i2 is neither of primitive type nor of String type, hence it is computed at run-time and returns a non-pool String object “1:ONE”.
As, str1 refers to String Pool object “1:ONE”, hence `str1 == “1:ONE”` returns true, whereas str2 refers to non-Pool String object “1:ONE” and hence `str2 == “1:ONE”` returns false.
What will be the result of compiling and executing Test class?
Correct
SCP83854:
Let us suppose test string is “aba”.
Lambda expression s.toUpperCase().substring(0,1).equals(“A”); means: “aba”.toUpperCase().substring(0,1).equals(“A”); => “ABA”.substring(0,1).equals(“A”); => “A”.equals(“A”); => true.
This lambda expression returns true for any string starting with a (in lower or upper case). Based on the lambda expression, 5 array elements passes the Predicate’s test and are printed on to the console.
Incorrect
SCP83854:
Let us suppose test string is “aba”.
Lambda expression s.toUpperCase().substring(0,1).equals(“A”); means: “aba”.toUpperCase().substring(0,1).equals(“A”); => “ABA”.substring(0,1).equals(“A”); => “A”.equals(“A”); => true.
This lambda expression returns true for any string starting with a (in lower or upper case). Based on the lambda expression, 5 array elements passes the Predicate’s test and are printed on to the console.
Unattempted
SCP83854:
Let us suppose test string is “aba”.
Lambda expression s.toUpperCase().substring(0,1).equals(“A”); means: “aba”.toUpperCase().substring(0,1).equals(“A”); => “ABA”.substring(0,1).equals(“A”); => “A”.equals(“A”); => true.
This lambda expression returns true for any string starting with a (in lower or upper case). Based on the lambda expression, 5 array elements passes the Predicate’s test and are printed on to the console.
Question 30 of 65
30. Question
Consider the following class:
public class Employee {
public int passportNo; //line 2
}
Which of the following is the correct way to make the variable ‘passportNo’ read only for any other class?
Correct
SCP75824:
‘passportNo’ should be read-only for any other class.
This means make ‘passportNo’ private and provide public getter method. Don’t provide public setter as then ‘passportNo’ will be read-write property.
If passportNo is declared with default scope, then other classes in the same package will be able to access passportNo for read-write operation.
Incorrect
SCP75824:
‘passportNo’ should be read-only for any other class.
This means make ‘passportNo’ private and provide public getter method. Don’t provide public setter as then ‘passportNo’ will be read-write property.
If passportNo is declared with default scope, then other classes in the same package will be able to access passportNo for read-write operation.
Unattempted
SCP75824:
‘passportNo’ should be read-only for any other class.
This means make ‘passportNo’ private and provide public getter method. Don’t provide public setter as then ‘passportNo’ will be read-write property.
If passportNo is declared with default scope, then other classes in the same package will be able to access passportNo for read-write operation.
public class Test {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(100);
list.add(200);
list.add(100);
list.add(200);
list.remove(100);
System.out.println(list);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP45356:
List cannot accept primitives, it can accept objects only. So, when 100 and 200 are added to the list, then auto-boxing feature converts these to wrapper objects of Integer type.
So, 4 items gets added to the list. One can expect the same behavior with remove method as well that 100 will be auto-boxed to Integer object.
But remove method is overloaded in List interface: remove(int) => Removes the element from the specified position in this list.
and remove(Object) => Removes the first occurrence of the specified element from the list.
As remove(int) version is available, which perfectly matches with the call remove(100); hence compiler does not do auto-boxing in this case.
But at runtime remove(100) tries to remove the element at 100th index and this throws IndexOutOfBoundsException.
Incorrect
SCP45356:
List cannot accept primitives, it can accept objects only. So, when 100 and 200 are added to the list, then auto-boxing feature converts these to wrapper objects of Integer type.
So, 4 items gets added to the list. One can expect the same behavior with remove method as well that 100 will be auto-boxed to Integer object.
But remove method is overloaded in List interface: remove(int) => Removes the element from the specified position in this list.
and remove(Object) => Removes the first occurrence of the specified element from the list.
As remove(int) version is available, which perfectly matches with the call remove(100); hence compiler does not do auto-boxing in this case.
But at runtime remove(100) tries to remove the element at 100th index and this throws IndexOutOfBoundsException.
Unattempted
SCP45356:
List cannot accept primitives, it can accept objects only. So, when 100 and 200 are added to the list, then auto-boxing feature converts these to wrapper objects of Integer type.
So, 4 items gets added to the list. One can expect the same behavior with remove method as well that 100 will be auto-boxed to Integer object.
But remove method is overloaded in List interface: remove(int) => Removes the element from the specified position in this list.
and remove(Object) => Removes the first occurrence of the specified element from the list.
As remove(int) version is available, which perfectly matches with the call remove(100); hence compiler does not do auto-boxing in this case.
But at runtime remove(100) tries to remove the element at 100th index and this throws IndexOutOfBoundsException.
Question 32 of 65
32. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
do {
System.out.print(100);
} while (true); //Line n1
System.out.println(200); //Line n2
}
}
Which of the following statements is correct for above code?
Correct
SCP71685:
Boolean expression of do-while loop uses literal true (compile-time constant), hence Java compiler knows that this loop is an infinite loop.
It also knows that once at runtime Java Control enters an infinite loop, none of the statements after loop block will get executed.
Hence it marks all the codes after the infinite do-while loop as Unreachable Code, which results in compilation error.
If boolean variable was used instead of boolean literal, then this program would have compiled and executed successfully.
public class Test {
public static void main(String[] args) {
boolean flag = true;
do {
System.out.println(100);
} while (flag);
System.out.println(200);
}
}
Above program prints 100 in infinite loop and 200 never gets printed.
Incorrect
SCP71685:
Boolean expression of do-while loop uses literal true (compile-time constant), hence Java compiler knows that this loop is an infinite loop.
It also knows that once at runtime Java Control enters an infinite loop, none of the statements after loop block will get executed.
Hence it marks all the codes after the infinite do-while loop as Unreachable Code, which results in compilation error.
If boolean variable was used instead of boolean literal, then this program would have compiled and executed successfully.
public class Test {
public static void main(String[] args) {
boolean flag = true;
do {
System.out.println(100);
} while (flag);
System.out.println(200);
}
}
Above program prints 100 in infinite loop and 200 never gets printed.
Unattempted
SCP71685:
Boolean expression of do-while loop uses literal true (compile-time constant), hence Java compiler knows that this loop is an infinite loop.
It also knows that once at runtime Java Control enters an infinite loop, none of the statements after loop block will get executed.
Hence it marks all the codes after the infinite do-while loop as Unreachable Code, which results in compilation error.
If boolean variable was used instead of boolean literal, then this program would have compiled and executed successfully.
public class Test {
public static void main(String[] args) {
boolean flag = true;
do {
System.out.println(100);
} while (flag);
System.out.println(200);
}
}
Above program prints 100 in infinite loop and 200 never gets printed.
Question 33 of 65
33. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
class Vehicle {
public int getRegistrationNumber() {
return 1;
}
}
class Car {
public double getRegistrationNumber() {
return 2;
}
}
public class Test {
public static void main(String[] args) {
Vehicle obj = new Car();
System.out.println(obj.getRegistrationNumber());
}
}
What will be the result of compiling and executing above code?
Correct
SCP61669:
class Car doesn’t extend from Vehicle class, this means Vehicle is not super type of Car.
Hence, Vehicle obj = new Car(); causes compilation error.
As Vehicle and Car classes are not related, hence these don’t cause any compilation error.
Incorrect
SCP61669:
class Car doesn’t extend from Vehicle class, this means Vehicle is not super type of Car.
Hence, Vehicle obj = new Car(); causes compilation error.
As Vehicle and Car classes are not related, hence these don’t cause any compilation error.
Unattempted
SCP61669:
class Car doesn’t extend from Vehicle class, this means Vehicle is not super type of Car.
Hence, Vehicle obj = new Car(); causes compilation error.
As Vehicle and Car classes are not related, hence these don’t cause any compilation error.
Question 34 of 65
34. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
import java.sql.SQLException;
public class Test {
private static void getReport() throws SQLException {
try {
throw new SQLException();
} catch (Exception e) {
throw null; //Line 10
}
}
What will be the result of compiling and executing Test class?
Correct
SCP66663:
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 getReport() declares to throw SQLException and main(String []) method code correctly handles it.
Program compiles successfully but on execution, NullPointerException is thrown, stack trace is printed on to the console and program ends abruptly.
If you debug the code, you would find that internal routine for throwing null exception causes NullPointerException.
Incorrect
SCP66663:
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 getReport() declares to throw SQLException and main(String []) method code correctly handles it.
Program compiles successfully but on execution, NullPointerException is thrown, stack trace is printed on to the console and program ends abruptly.
If you debug the code, you would find that internal routine for throwing null exception causes NullPointerException.
Unattempted
SCP66663:
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 getReport() declares to throw SQLException and main(String []) method code correctly handles it.
Program compiles successfully but on execution, NullPointerException is thrown, stack trace is printed on to the console and program ends abruptly.
If you debug the code, you would find that internal routine for throwing null exception causes NullPointerException.
Question 35 of 65
35. Question
For the class Test, which options, if used to replace /*INSERT*/, will print “Lucky no. 7” on to the console?
Select ALL that apply.
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
/*INSERT*/
switch(var) {
case 7:
System.out.println(“Lucky no. 7”);
break;
default:
System.out.println(“DEFAULT”);
}
}
}
Correct
SCP15503:
switch can accept primitive types: byte, short, int, char; wrapper types: Byte, Short, Integer, Character; String and enums. In this case, all are valid values but only 3 executes “case 7:”.
case is comparing integer value 7. NOTE: character seven, ‘7’ is different from integer value seven, 7. So “char var = ‘7’;” and “Character var = ‘7’;” will print DEFAULT on to the console.
Please also note that the identifier var is not a keyword, hence var can still be used as variable name, method name or package name but it cannot be used as a class or interface name.
Incorrect
SCP15503:
switch can accept primitive types: byte, short, int, char; wrapper types: Byte, Short, Integer, Character; String and enums. In this case, all are valid values but only 3 executes “case 7:”.
case is comparing integer value 7. NOTE: character seven, ‘7’ is different from integer value seven, 7. So “char var = ‘7’;” and “Character var = ‘7’;” will print DEFAULT on to the console.
Please also note that the identifier var is not a keyword, hence var can still be used as variable name, method name or package name but it cannot be used as a class or interface name.
Unattempted
SCP15503:
switch can accept primitive types: byte, short, int, char; wrapper types: Byte, Short, Integer, Character; String and enums. In this case, all are valid values but only 3 executes “case 7:”.
case is comparing integer value 7. NOTE: character seven, ‘7’ is different from integer value seven, 7. So “char var = ‘7’;” and “Character var = ‘7’;” will print DEFAULT on to the console.
Please also note that the identifier var is not a keyword, hence var can still be used as variable name, method name or package name but it cannot be used as a class or interface name.
Question 36 of 65
36. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
double [] arr = new int[2]; //Line n1
System.out.println(arr[0]); //Line n2
}
}
What will be the result of compiling and executing Test class?
Correct
SCP61869:
int variable can easily be assigned to double type but double [] and int [] are not compatible. Hence, int [] object cannot be assigned to double [] type. Line n1 causes compilation error.
Incorrect
SCP61869:
int variable can easily be assigned to double type but double [] and int [] are not compatible. Hence, int [] object cannot be assigned to double [] type. Line n1 causes compilation error.
Unattempted
SCP61869:
int variable can easily be assigned to double type but double [] and int [] are not compatible. Hence, int [] object cannot be assigned to double [] type. Line n1 causes compilation error.
Question 37 of 65
37. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
class Calculator {
int calculate(int i1, int i2) {
return i1 + i2;
}
public class Test {
public static void main(String[] args) {
byte b = 100;
int i = 20;
System.out.println(new Calculator().calculate(b, i));
}
}
What will be the result of compiling and executing Test class?
Correct
SCP28860:
calculate method is correctly overloaded as both the methods have different signature: calculate(int, int) and calculate(byte, byte). Please note that there is no rule regarding return type for overloaded methods, return type can be same or different.
`new Calculator().calculate(b, i)` tags to `calculate(int, int)` as byte value is implicitly casted to int type.
Given code compiles successfully and on execution prints 120 on to the console.
Incorrect
SCP28860:
calculate method is correctly overloaded as both the methods have different signature: calculate(int, int) and calculate(byte, byte). Please note that there is no rule regarding return type for overloaded methods, return type can be same or different.
`new Calculator().calculate(b, i)` tags to `calculate(int, int)` as byte value is implicitly casted to int type.
Given code compiles successfully and on execution prints 120 on to the console.
Unattempted
SCP28860:
calculate method is correctly overloaded as both the methods have different signature: calculate(int, int) and calculate(byte, byte). Please note that there is no rule regarding return type for overloaded methods, return type can be same or different.
`new Calculator().calculate(b, i)` tags to `calculate(int, int)` as byte value is implicitly casted to int type.
Given code compiles successfully and on execution prints 120 on to the console.
Question 38 of 65
38. Question
Given:
public class Test {
public Test() {
text3 = text2 + “c”; // Line 1
}
String text1 = “a” + text2; // Line 2
String text2 = “b”; // Line 3
String text3;
}
Which line fails to compile?
Correct
When a class is compiled, a field initialization statement can be considered an initialization block, and all initialization block bodies are copied to the beginning of each constructor. As a result, at the bytecode level, a constructor body always follows the initialization of any field, hence can reference that field.
Outside of the constructors, however, a field can only reference other fields that have been defined before it; otherwise we’ll have an illegal forward reference error.
On line 2, the text1 field references text2, which hasn’t been defined until line 3. Therefore, the compilation fails on line 2.
Incorrect
When a class is compiled, a field initialization statement can be considered an initialization block, and all initialization block bodies are copied to the beginning of each constructor. As a result, at the bytecode level, a constructor body always follows the initialization of any field, hence can reference that field.
Outside of the constructors, however, a field can only reference other fields that have been defined before it; otherwise we’ll have an illegal forward reference error.
On line 2, the text1 field references text2, which hasn’t been defined until line 3. Therefore, the compilation fails on line 2.
Unattempted
When a class is compiled, a field initialization statement can be considered an initialization block, and all initialization block bodies are copied to the beginning of each constructor. As a result, at the bytecode level, a constructor body always follows the initialization of any field, hence can reference that field.
Outside of the constructors, however, a field can only reference other fields that have been defined before it; otherwise we’ll have an illegal forward reference error.
On line 2, the text1 field references text2, which hasn’t been defined until line 3. Therefore, the compilation fails on line 2.
Question 39 of 65
39. Question
Given:
float f1 = _12.345F; // Line 1
float f2 = 12_.345F; // Line 2
float f3 = 12._345F; // Line 3
float f4 = 12.345_F; // Line 4
float f5 = 12.345F_; // Line 5
Which line is a valid variable declaration?
Correct
We can use the underscore character to separate groups of digits in numeric literals, which can improve the readability of your code. However, such a character cannot be used at:
The beginning or end of a number
Adjacent to a decimal point in a floating-point literal
Prior to a suffix
All the numeric literals in the given code violate one requirement or another, hence none of them are valid.
Incorrect
We can use the underscore character to separate groups of digits in numeric literals, which can improve the readability of your code. However, such a character cannot be used at:
The beginning or end of a number
Adjacent to a decimal point in a floating-point literal
Prior to a suffix
All the numeric literals in the given code violate one requirement or another, hence none of them are valid.
Unattempted
We can use the underscore character to separate groups of digits in numeric literals, which can improve the readability of your code. However, such a character cannot be used at:
The beginning or end of a number
Adjacent to a decimal point in a floating-point literal
Prior to a suffix
All the numeric literals in the given code violate one requirement or another, hence none of them are valid.
Question 40 of 65
40. Question
Given:
String[] array = new String[5];
Arrays.fill(array, “Hello”);
System.out.println(array[2]);
What is the output when executing the given code fragment?
Correct
As per the JDK API Specification, the Arrays#fill method assigns the specified Object reference to each element of the specified array of Objects.
In the given code, the fill method sets all elements in the array to the string “Hello”. Therefore, no matter which element is read, the output is always “Hello”.
Incorrect
As per the JDK API Specification, the Arrays#fill method assigns the specified Object reference to each element of the specified array of Objects.
In the given code, the fill method sets all elements in the array to the string “Hello”. Therefore, no matter which element is read, the output is always “Hello”.
Unattempted
As per the JDK API Specification, the Arrays#fill method assigns the specified Object reference to each element of the specified array of Objects.
In the given code, the fill method sets all elements in the array to the string “Hello”. Therefore, no matter which element is read, the output is always “Hello”.
Question 41 of 65
41. Question
Given:
class Foo {
protected String myField = “Foo”;
protected static Object myMethod() {
return “Foo”;
}
}
public class Bar extends Foo {
public String myField = “Bar”;
public String myMethod() {
return “Bar”;
}
public static void main(String[] args) {
Foo foo = new Bar();
System.out.println(foo.myField);
System.out.println(foo.myMethod());
}
}
What is the program’s output?
Correct
As per section 8.4.8.1 of the Java Language Specification, it’s a compile-time error if an instance method overrides a static method.
In the given code, myMethod is a static method in the class Foo, but is an instance method in class Bar, hence the compilation fails.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.8.1
Incorrect
As per section 8.4.8.1 of the Java Language Specification, it’s a compile-time error if an instance method overrides a static method.
In the given code, myMethod is a static method in the class Foo, but is an instance method in class Bar, hence the compilation fails.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.8.1
Unattempted
As per section 8.4.8.1 of the Java Language Specification, it’s a compile-time error if an instance method overrides a static method.
In the given code, myMethod is a static method in the class Foo, but is an instance method in class Bar, hence the compilation fails.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.8.1
Question 42 of 65
42. Question
Given:
public class Foo {
String a, b, c, d;
void setA(String b) {
a = b;
}
void setB(String b) {
b = this.a;
}
void setC(String d) {
this.c = this.d;
}
void setD(String a) {
this.d = d ;
}
}
Which methods modify a field of the Foo class?
Correct
Method setB sets the argument to the value of field a, while method setD sets field d to its own value. These two methods don’t change any field value.
Method setA sets field a to its argument, and method setC sets field c to the value of field d. These methods modify fields’ value.
Incorrect
Method setB sets the argument to the value of field a, while method setD sets field d to its own value. These two methods don’t change any field value.
Method setA sets field a to its argument, and method setC sets field c to the value of field d. These methods modify fields’ value.
Unattempted
Method setB sets the argument to the value of field a, while method setD sets field d to its own value. These two methods don’t change any field value.
Method setA sets field a to its argument, and method setC sets field c to the value of field d. These methods modify fields’ value.
Question 43 of 65
43. Question
Given:
public class Test {
static boolean x;
static boolean y;
public static void main(String[] args) {
x = x || y && !x;
y = y && x || y;
System.out.println(x);
System.out.println(y);
}
}
What is the program’s output?
Correct
If a boolean field isn’t explicitly specified, the complier will set it to false.
When solving questions related to boolean values, just notice their precedence order: first is the NOT (!) operator, then AND (&&), and at the bottom is the OR (||) operator.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Incorrect
If a boolean field isn’t explicitly specified, the complier will set it to false.
When solving questions related to boolean values, just notice their precedence order: first is the NOT (!) operator, then AND (&&), and at the bottom is the OR (||) operator.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Unattempted
If a boolean field isn’t explicitly specified, the complier will set it to false.
When solving questions related to boolean values, just notice their precedence order: first is the NOT (!) operator, then AND (&&), and at the bottom is the OR (||) operator.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Question 44 of 65
44. Question
Given:
class Foo {
Object myMethod(String argument) {
// a valid body
}
}
public class Bar extends Foo {
/* Method 1 */
String myMethod(String argument) {
// a valid body
}
/* Method 2 */
String myMethod(Object argument) {
// a valid body
}
/* Method 3 */
Object myMethod(Object argument) {
// a valid body
}
}
Which method in the Bar class must be removed to make the given code compile?
Correct
Method 1 override the superclass’s method, while methods 2 and 3 overload it. Hence, there would have been nothing wrong had each method in the subclass been defined independently.
Notice methods 2 and 3 have the same signature, composed of the method name and parameter types. We cannot define two methods with the same signature in the same class. Therefore, either of these methods must be removed.
Incorrect
Method 1 override the superclass’s method, while methods 2 and 3 overload it. Hence, there would have been nothing wrong had each method in the subclass been defined independently.
Notice methods 2 and 3 have the same signature, composed of the method name and parameter types. We cannot define two methods with the same signature in the same class. Therefore, either of these methods must be removed.
Unattempted
Method 1 override the superclass’s method, while methods 2 and 3 overload it. Hence, there would have been nothing wrong had each method in the subclass been defined independently.
Notice methods 2 and 3 have the same signature, composed of the method name and parameter types. We cannot define two methods with the same signature in the same class. Therefore, either of these methods must be removed.
Question 45 of 65
45. Question
Given:
public class Foo {
int a, b, c;
void methodX(int a) {
a = setA(a);
setBC(a, a);
}
void methodY(int a, int b) {
b = setBC(a, b);
setA(b);
}
private int setA(int a) {
return a = a;
}
private int setBC(int a, int b) {
c = b = a;
return b;
}
}
Which methods modify fields of a Foo object?
Correct
The setA method doesn’t change any fields as it assigns the argument to itself. Method setBC, on the other hand, always set field c to argument b.
Since both methodX and methodY calls setBC, they both modify field c of a Foo object.
Incorrect
The setA method doesn’t change any fields as it assigns the argument to itself. Method setBC, on the other hand, always set field c to argument b.
Since both methodX and methodY calls setBC, they both modify field c of a Foo object.
Unattempted
The setA method doesn’t change any fields as it assigns the argument to itself. Method setBC, on the other hand, always set field c to argument b.
Since both methodX and methodY calls setBC, they both modify field c of a Foo object.
Question 46 of 65
46. Question
Given:
int x = 1, y = 2;
x += x < y ? y : x;
y = x < y ? y - x : y + x;
System.out.println(x + " " + y);
What is the given code's output?
Correct
An assignment operator, such as = or +=, has the least precedence. Hence, in the second statement, the ternary operation is executed first, then the compound += operator. In that ternary operation, the expression x < y evaluates to true, hence its result is the value of y, which is 2. The whole statement then becomes x += 2, so x is set to 3.
In the next statement, the expression x < y evaluates to false, meaning the whole statement becomes y = y + x. The original values of y and x are 2 and 3, respectively; so, the final value of y is 5.
Reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Incorrect
An assignment operator, such as = or +=, has the least precedence. Hence, in the second statement, the ternary operation is executed first, then the compound += operator. In that ternary operation, the expression x < y evaluates to true, hence its result is the value of y, which is 2. The whole statement then becomes x += 2, so x is set to 3.
In the next statement, the expression x < y evaluates to false, meaning the whole statement becomes y = y + x. The original values of y and x are 2 and 3, respectively; so, the final value of y is 5.
Reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Unattempted
An assignment operator, such as = or +=, has the least precedence. Hence, in the second statement, the ternary operation is executed first, then the compound += operator. In that ternary operation, the expression x < y evaluates to true, hence its result is the value of y, which is 2. The whole statement then becomes x += 2, so x is set to 3.
In the next statement, the expression x < y evaluates to false, meaning the whole statement becomes y = y + x. The original values of y and x are 2 and 3, respectively; so, the final value of y is 5.
Reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Question 47 of 65
47. Question
Given:
class Foo {
static String name = “Foo”;
void print() {
System.out.println(this.name); // Line 1
}
}
class Bar extends Foo {
String name = “Bar”;
static void printName() {
super.print(); // Line 2
}
}
public class Test {
public static void main(String[] args) {
new Bar().printName(); // Line 3
}
}
What is the program’s output?
Given:
LocalDate d1 = LocalDate.of(2019, 1, 1);
LocalDate d2 = LocalDate.parse(“2019-1-1″, DateTimeFormatter.ISO_DATE);
LocalDate d3 = LocalDate.now().withDayOfMonth(1).withMonth(1).withYear(2019);
System.out.println(d1.equals(d2) + ” ” + d2.equals(d3));
What is the output of the given code?
Correct
The types of all arguments passed to static methods of class LocalDate match their signatures, hence no compile-time errors.
Notice with all ISO formatters, the number representing the month of year or date of month always has two digits. In case its value is less than 10, the digit 0 is added to the left. It’s clear that the string argument in the second statement is malformed, leading to a DateTimeParseException at runtime. The correct formatted value is “2019-01-01”.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html
Incorrect
The types of all arguments passed to static methods of class LocalDate match their signatures, hence no compile-time errors.
Notice with all ISO formatters, the number representing the month of year or date of month always has two digits. In case its value is less than 10, the digit 0 is added to the left. It’s clear that the string argument in the second statement is malformed, leading to a DateTimeParseException at runtime. The correct formatted value is “2019-01-01”.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html
Unattempted
The types of all arguments passed to static methods of class LocalDate match their signatures, hence no compile-time errors.
Notice with all ISO formatters, the number representing the month of year or date of month always has two digits. In case its value is less than 10, the digit 0 is added to the left. It’s clear that the string argument in the second statement is malformed, leading to a DateTimeParseException at runtime. The correct formatted value is “2019-01-01”.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html
Question 49 of 65
49. Question
Given:
LocalTime localTime = LocalTime.of(1, 15, 30);
localTime.withHour(2); // Line 1
localTime.with(ChronoField.MINUTE_OF_HOUR, 30); // Line 2
localTime.plusSeconds(15); // Line 3
System.out.println(localTime);
What is the output of the given code?
Correct
Classes in the java.time package, including LocalTime, are immutable. Any changes made to an instance will create a new object instead of modifying the existing one. This means the state of the LocalTime object created in the first statement isn’t affected by the modifications made afterward.
Incorrect
Classes in the java.time package, including LocalTime, are immutable. Any changes made to an instance will create a new object instead of modifying the existing one. This means the state of the LocalTime object created in the first statement isn’t affected by the modifications made afterward.
Unattempted
Classes in the java.time package, including LocalTime, are immutable. Any changes made to an instance will create a new object instead of modifying the existing one. This means the state of the LocalTime object created in the first statement isn’t affected by the modifications made afterward.
Question 50 of 65
50. Question
Given two classes:
package test1;
class Foo { }
And:
package test2;
import test1.Foo;
public class Bar {
public static void main(String[] args) {
Foo foo = new Foo();
foo = new Foo();
foo = null;
foo = new Foo();
}
}
How many instances of the Foo class are created when the main method is compiled and run?
Correct
The Foo class isn’t defined with an explicit constructor, meaning the compiler will add the default constructor for it automatically. As per section 8.8.9 of the Java Language Specification, the default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access.
In the given code, the Foo class doesn’t have such a modifier, implying this class and the default constructor are package-private. The Bar class belongs to a different package; hence the compilation fails.
Had the Foo class been declared as public, option C would have been the correct answer.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#d5e15148
Incorrect
The Foo class isn’t defined with an explicit constructor, meaning the compiler will add the default constructor for it automatically. As per section 8.8.9 of the Java Language Specification, the default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access.
In the given code, the Foo class doesn’t have such a modifier, implying this class and the default constructor are package-private. The Bar class belongs to a different package; hence the compilation fails.
Had the Foo class been declared as public, option C would have been the correct answer.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#d5e15148
Unattempted
The Foo class isn’t defined with an explicit constructor, meaning the compiler will add the default constructor for it automatically. As per section 8.8.9 of the Java Language Specification, the default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access.
In the given code, the Foo class doesn’t have such a modifier, implying this class and the default constructor are package-private. The Bar class belongs to a different package; hence the compilation fails.
Had the Foo class been declared as public, option C would have been the correct answer.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#d5e15148
Question 51 of 65
51. Question
Which two of the following are valid options to specify a classpath for the javac command?
Which option instructs the javac command to generate class files with all debugging information, including source file information, line numbers and local variables?
Correct
Here’s a description of the -g option of the javac command:
Generates all debugging information, including local variables. By default, only line number and source file information are generated.
All the other options aren’t recognized by this command.
Reference: https://docs.oracle.com/en/java/javase/11/tools/javac.html
Incorrect
Here’s a description of the -g option of the javac command:
Generates all debugging information, including local variables. By default, only line number and source file information are generated.
All the other options aren’t recognized by this command.
Reference: https://docs.oracle.com/en/java/javase/11/tools/javac.html
Unattempted
Here’s a description of the -g option of the javac command:
Generates all debugging information, including local variables. By default, only line number and source file information are generated.
All the other options aren’t recognized by this command.
Reference: https://docs.oracle.com/en/java/javase/11/tools/javac.html
Question 53 of 65
53. Question
Given:
int i = 0, j = 5, k;
do {
k = i;
} while (i++ < --j);
System.out.println(k);
What is the output of when executing the code fragment?
Correct
Let’s go over iterations of the do/while construct:
Iteration 1:
k is set to 0, the original value of i
i is increased to 1, its original value 0 is used for the condition expression
j is decreased to 4, its new value 4 is used for the condition expression
Since 1 < 4, the do/while construct keeps going
Iteration 2:
k is set to 1, the value of i from the previous iteration
i is increased to 2, its old value 1 is used for the condition expression
j is decreased to 3, its new value 3 is used for the condition expression
Since 2 < 3, the do/while construct keeps going
Iteration 3:
k is set to 2, the value of i from the previous iteration
i is increased to 3, its old value 2 is used for the condition expression
j is decreased to 2, its new value 2 is used for the condition expression
The expression 2 < 2 evaluates to false, hence the do/while construct exits
So, after the third iteration is executed, the k variable is set to 2.
Incorrect
Let’s go over iterations of the do/while construct:
Iteration 1:
k is set to 0, the original value of i
i is increased to 1, its original value 0 is used for the condition expression
j is decreased to 4, its new value 4 is used for the condition expression
Since 1 < 4, the do/while construct keeps going
Iteration 2:
k is set to 1, the value of i from the previous iteration
i is increased to 2, its old value 1 is used for the condition expression
j is decreased to 3, its new value 3 is used for the condition expression
Since 2 < 3, the do/while construct keeps going
Iteration 3:
k is set to 2, the value of i from the previous iteration
i is increased to 3, its old value 2 is used for the condition expression
j is decreased to 2, its new value 2 is used for the condition expression
The expression 2 < 2 evaluates to false, hence the do/while construct exits
So, after the third iteration is executed, the k variable is set to 2.
Unattempted
Let’s go over iterations of the do/while construct:
Iteration 1:
k is set to 0, the original value of i
i is increased to 1, its original value 0 is used for the condition expression
j is decreased to 4, its new value 4 is used for the condition expression
Since 1 < 4, the do/while construct keeps going
Iteration 2:
k is set to 1, the value of i from the previous iteration
i is increased to 2, its old value 1 is used for the condition expression
j is decreased to 3, its new value 3 is used for the condition expression
Since 2 < 3, the do/while construct keeps going
Iteration 3:
k is set to 2, the value of i from the previous iteration
i is increased to 3, its old value 2 is used for the condition expression
j is decreased to 2, its new value 2 is used for the condition expression
The expression 2 < 2 evaluates to false, hence the do/while construct exits
So, after the third iteration is executed, the k variable is set to 2.
Question 54 of 65
54. Question
Given a code fragment:
byte b = 100; // Line 1
short s = ‘A’; // Line 2
char c = “A”; // Line 3
float f = 1.0; // Line 4
double d = 1; // Line 5
Which two statements fail to compile?
Correct
As per the Oracle Java Tutorials, an integral literal is of type long if it ends with the letter L or l; otherwise it is of type int. Therefore, the literal values on line 1 and line 5 are of type int.
On line 1, an int value is assigned to a variable of type byte. This assignment is allowed and doesn’t require a casting operator because the given value is within the space of the byte type – from -128 to 127. According to section 5.2 of the Java Language Specification, a narrowing primitive conversion may be used if the variable is of type byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Likewise, the conversion on line 2 is a narrowing one, but the constant 65 (the Unicode value of letter A) is well within the value space of the short data type. Hence no casting is needed.
On line 5, the assignment of an int value to a double variable is just a simple widening primitive conversion. This conversion is listed in section 5.1.2 of the Java Language Specification.
On line 3, the assignment is invalid because the value is a String object rather than a char value.
On line 4, the constant value doesn’t have a suffix. Notice a floating-point literal is considered a double number if it ends with D, d or no suffix. Unlike integral conversions, a narrowing conversion of a floating-point number always requires the casting operator.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.1 https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.2
Incorrect
As per the Oracle Java Tutorials, an integral literal is of type long if it ends with the letter L or l; otherwise it is of type int. Therefore, the literal values on line 1 and line 5 are of type int.
On line 1, an int value is assigned to a variable of type byte. This assignment is allowed and doesn’t require a casting operator because the given value is within the space of the byte type – from -128 to 127. According to section 5.2 of the Java Language Specification, a narrowing primitive conversion may be used if the variable is of type byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Likewise, the conversion on line 2 is a narrowing one, but the constant 65 (the Unicode value of letter A) is well within the value space of the short data type. Hence no casting is needed.
On line 5, the assignment of an int value to a double variable is just a simple widening primitive conversion. This conversion is listed in section 5.1.2 of the Java Language Specification.
On line 3, the assignment is invalid because the value is a String object rather than a char value.
On line 4, the constant value doesn’t have a suffix. Notice a floating-point literal is considered a double number if it ends with D, d or no suffix. Unlike integral conversions, a narrowing conversion of a floating-point number always requires the casting operator.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.1 https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.2
Unattempted
As per the Oracle Java Tutorials, an integral literal is of type long if it ends with the letter L or l; otherwise it is of type int. Therefore, the literal values on line 1 and line 5 are of type int.
On line 1, an int value is assigned to a variable of type byte. This assignment is allowed and doesn’t require a casting operator because the given value is within the space of the byte type – from -128 to 127. According to section 5.2 of the Java Language Specification, a narrowing primitive conversion may be used if the variable is of type byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Likewise, the conversion on line 2 is a narrowing one, but the constant 65 (the Unicode value of letter A) is well within the value space of the short data type. Hence no casting is needed.
On line 5, the assignment of an int value to a double variable is just a simple widening primitive conversion. This conversion is listed in section 5.1.2 of the Java Language Specification.
On line 3, the assignment is invalid because the value is a String object rather than a char value.
On line 4, the constant value doesn’t have a suffix. Notice a floating-point literal is considered a double number if it ends with D, d or no suffix. Unlike integral conversions, a narrowing conversion of a floating-point number always requires the casting operator.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.1 https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.2
for (int i = 0; i < strings.length; i++) {
for (int j = 0; j < strings[i].length; j++) {
System.out.print(strings[i][j] + " ");
}
System.out.println();
}
What is the output when executing the given code?
Correct
The strings variable references a two-dimensional array. The outer array contains three one-dimensional arrays – {“a”, “d”}, {“b”, “e”} and {“c”, “f”}. The elements of these arrays are printed one by one by the for statements.
Incorrect
The strings variable references a two-dimensional array. The outer array contains three one-dimensional arrays – {“a”, “d”}, {“b”, “e”} and {“c”, “f”}. The elements of these arrays are printed one by one by the for statements.
Unattempted
The strings variable references a two-dimensional array. The outer array contains three one-dimensional arrays – {“a”, “d”}, {“b”, “e”} and {“c”, “f”}. The elements of these arrays are printed one by one by the for statements.
Question 56 of 65
56. Question
Given:
class SuperTest {
public Object myMethod(Object… args) {
// A valid body
}
}
class Test extends SuperTest {
// Method 1
public Object myMethod(String… args) {
// A valid body
}
// Method 2
public Object myMethod(Integer[] args) {
// A valid body
}
// Method 3
public Object myMethod(Object arg) {
// A valid body
}
// Method 4
public String myMethod(Object[] args) {
// A valid body
}
}
Which method in the Test class doesn’t overload the only method in the SuperTest?
Correct
The first three methods of the Test class don’t have the same parameters as the method in the SuperTest class, hence they don’t overload.
Notice varargs is just syntactic sugar for arrays, hence method 4 has the same signature as the method in the super-class. In fact, it overrides the super-class’s method.
Incorrect
The first three methods of the Test class don’t have the same parameters as the method in the SuperTest class, hence they don’t overload.
Notice varargs is just syntactic sugar for arrays, hence method 4 has the same signature as the method in the super-class. In fact, it overrides the super-class’s method.
Unattempted
The first three methods of the Test class don’t have the same parameters as the method in the SuperTest class, hence they don’t overload.
Notice varargs is just syntactic sugar for arrays, hence method 4 has the same signature as the method in the super-class. In fact, it overrides the super-class’s method.
Question 57 of 65
57. Question
Given:
interface Foo {
void methodA() { }
static void methodB();
protected void methodC();
public void methodD();
}
Which method is valid?
Correct
All methods in an interface are public and abstract by default, and an abstract method doesn’t have a body. Option A is incorrect, then.
methodB is static, but a static method must have a body. This means option B is incorrect as well.
The protected modifier isn’t allowed in an interface; thus, option C is also incorrect.
The public modifier on an interface method is redundant, but adding it doesn’t do any harm; hence, option D is the correct answer.
Incorrect
All methods in an interface are public and abstract by default, and an abstract method doesn’t have a body. Option A is incorrect, then.
methodB is static, but a static method must have a body. This means option B is incorrect as well.
The protected modifier isn’t allowed in an interface; thus, option C is also incorrect.
The public modifier on an interface method is redundant, but adding it doesn’t do any harm; hence, option D is the correct answer.
Unattempted
All methods in an interface are public and abstract by default, and an abstract method doesn’t have a body. Option A is incorrect, then.
methodB is static, but a static method must have a body. This means option B is incorrect as well.
The protected modifier isn’t allowed in an interface; thus, option C is also incorrect.
The public modifier on an interface method is redundant, but adding it doesn’t do any harm; hence, option D is the correct answer.
Question 58 of 65
58. Question
Given:
public class Test {
static String text;
public static void main(String[] args) {
String string1 = text + “Java”;
String string2 = “Java”;
System.out.println(string1 == string2);
System.out.println(string1.equals(string2));
}
}
What is the output of the program?
Correct
The text field isn’t explicitly initialized; thus, it’s set to null by default. The textual representation of a null value is “null”, therefore, the value of string1 is “nullJava”, which is obviously different from the value of string2.
Incorrect
The text field isn’t explicitly initialized; thus, it’s set to null by default. The textual representation of a null value is “null”, therefore, the value of string1 is “nullJava”, which is obviously different from the value of string2.
Unattempted
The text field isn’t explicitly initialized; thus, it’s set to null by default. The textual representation of a null value is “null”, therefore, the value of string1 is “nullJava”, which is obviously different from the value of string2.
Question 59 of 65
59. Question
Given a method:
void switchString(String arg) {
switch (arg) {
case “A”: case “a”:
System.out.println(“Apple”);
case “B”:
System.out.println(“Beef”);
default:
System.out.println(“No match”);
}
}
What is printed to the console if the switchString method is called with argument “B”?
Correct
The provided argument matches case “B”, hence the string “Beef” is printed. Notice there’s no break statement in the body of this case, hence the control falls through executes the body of the default case as well.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Incorrect
The provided argument matches case “B”, hence the string “Beef” is printed. Notice there’s no break statement in the body of this case, hence the control falls through executes the body of the default case as well.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Unattempted
The provided argument matches case “B”, hence the string “Beef” is printed. Notice there’s no break statement in the body of this case, hence the control falls through executes the body of the default case as well.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Question 60 of 65
60. Question
Given three module declarations:
module bar {
exports bar to test;
}
And:
module foo {
requires transitive bar;
exports foo;
}
And:
module test {
requires foo;
}
Which of the following statements is correct about the bar package?
Correct
The dependency of the foo module on the bar module is transitive, implying all modules that requires foo also have access to bar. Notice in the bar module, the bar package is exported to the test module only, hence it’s invisible in the foo module.
Incorrect
The dependency of the foo module on the bar module is transitive, implying all modules that requires foo also have access to bar. Notice in the bar module, the bar package is exported to the test module only, hence it’s invisible in the foo module.
Unattempted
The dependency of the foo module on the bar module is transitive, implying all modules that requires foo also have access to bar. Notice in the bar module, the bar package is exported to the test module only, hence it’s invisible in the foo module.
Question 61 of 65
61. Question
Given:
interface Foo {
String name = “Foo”;
void print();
}
public class Bar implements Foo {
String name = “Bar”;
public void print() {
System.out.println(name); // Line 1
}
public static void main(String[] args) {
Foo foo = new Bar(); // Line 2
foo.print(); // Line 3
}
}
What is the program’s output?
Correct
There’s nothing wrong with the given code. Inside the Bar class, its name field just hides the name field in the Foo interface.
When an object of the Bar class is created and assigned to a variable of the reference type Foo, the method getting called at runtime is still the one defined in the Bar class. This method prints the value of the name field in the Bar class to the console.
Incorrect
There’s nothing wrong with the given code. Inside the Bar class, its name field just hides the name field in the Foo interface.
When an object of the Bar class is created and assigned to a variable of the reference type Foo, the method getting called at runtime is still the one defined in the Bar class. This method prints the value of the name field in the Bar class to the console.
Unattempted
There’s nothing wrong with the given code. Inside the Bar class, its name field just hides the name field in the Foo interface.
When an object of the Bar class is created and assigned to a variable of the reference type Foo, the method getting called at runtime is still the one defined in the Bar class. This method prints the value of the name field in the Bar class to the console.
Question 62 of 65
62. Question
Given:
public class Test {
public static void main(String[] args) {
try {
foo();
} catch (Exception e) {
System.out.println(e);
}
}
static void foo() throws Exception {
throw new Exception(“Foo”);
}
}
What is the output of the program?
Correct
The Exception class inherits the toString method from class Throwable. As per the JDK API Specification, the Throwable#toString method returns a short description containing:
the name of the class of this object
“: ” (a colon and a space)
the result of invoking this object’s getLocalizedMessage() method
If getLocalizedMessage returns null, then just the class name is returned.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#toString()
Incorrect
The Exception class inherits the toString method from class Throwable. As per the JDK API Specification, the Throwable#toString method returns a short description containing:
the name of the class of this object
“: ” (a colon and a space)
the result of invoking this object’s getLocalizedMessage() method
If getLocalizedMessage returns null, then just the class name is returned.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#toString()
Unattempted
The Exception class inherits the toString method from class Throwable. As per the JDK API Specification, the Throwable#toString method returns a short description containing:
the name of the class of this object
“: ” (a colon and a space)
the result of invoking this object’s getLocalizedMessage() method
If getLocalizedMessage returns null, then just the class name is returned.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#toString()
Question 63 of 65
63. Question
Given:
class Foo {
public String toString() {
return “Foo”;
}
}
public class Bar {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
Foo foo = new Foo();
builder.append(foo); // Line 1
builder.append(‘ ‘); // Line 2
builder.append(“Bar”);
System.out.println(builder);
}
}
What is the program output?
Correct
There’s nothing wrong with the given code. Notice the append method can append any primitive value or an object of any type to a StringBuilder instance. In case an object is appended, its textual representation is added to the buffer.
In addition, a StringBuilder is a mutable sequence of characters. When invoking a method on this object, the object itself can be changed. This is different from String where the original object is always intact.
Incorrect
There’s nothing wrong with the given code. Notice the append method can append any primitive value or an object of any type to a StringBuilder instance. In case an object is appended, its textual representation is added to the buffer.
In addition, a StringBuilder is a mutable sequence of characters. When invoking a method on this object, the object itself can be changed. This is different from String where the original object is always intact.
Unattempted
There’s nothing wrong with the given code. Notice the append method can append any primitive value or an object of any type to a StringBuilder instance. In case an object is appended, its textual representation is added to the buffer.
In addition, a StringBuilder is a mutable sequence of characters. When invoking a method on this object, the object itself can be changed. This is different from String where the original object is always intact.
Question 64 of 65
64. Question
Given:
class Foo {
private String methodC() {
return “Foo”;
}
public String methodA() {
return methodC();
}
public String methodB() {
return methodC();
}
}
public class Bar extends Foo {
private String methodC() {
return “Bar”;
}
public String methodB() {
return methodC();
}
public static void main(String[] args) {
Foo foo = new Bar();
System.out.println(foo.methodA());
System.out.println(foo.methodB());
}
}
What is the program’s output?
Correct
methodA is defined in the Foo class only. Obviously, this method doesn’t know anything about the Bar class. Therefore, when it’s invoked, methodC defined in the Foo class, not the one in the Bar class, gets called. So, the first string in the output is “Foo”.
methodB is defined in both the Foo and Bar classes. The variable foo has reference type Foo, but it refers to an object of type Bar at runtime. This means methodB defined in the Bar class overrides the one in the Foo class. As a result, foo.methodB() calls methodB, then methodC of class Bar, and the second output string is “Bar”.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Incorrect
methodA is defined in the Foo class only. Obviously, this method doesn’t know anything about the Bar class. Therefore, when it’s invoked, methodC defined in the Foo class, not the one in the Bar class, gets called. So, the first string in the output is “Foo”.
methodB is defined in both the Foo and Bar classes. The variable foo has reference type Foo, but it refers to an object of type Bar at runtime. This means methodB defined in the Bar class overrides the one in the Foo class. As a result, foo.methodB() calls methodB, then methodC of class Bar, and the second output string is “Bar”.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Unattempted
methodA is defined in the Foo class only. Obviously, this method doesn’t know anything about the Bar class. Therefore, when it’s invoked, methodC defined in the Foo class, not the one in the Bar class, gets called. So, the first string in the output is “Foo”.
methodB is defined in both the Foo and Bar classes. The variable foo has reference type Foo, but it refers to an object of type Bar at runtime. This means methodB defined in the Bar class overrides the one in the Foo class. As a result, foo.methodB() calls methodB, then methodC of class Bar, and the second output string is “Bar”.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Question 65 of 65
65. Question
Given:
public class Test {
public static void main(String[] args) {
String concatenated = Arrays.toString(args);
System.out.println(concatenated);
}
}
What happens when compiling and running the given program with the following command?
java Test “1 2” 3
Correct
When passing arguments to the java command, single (‘) or double (“) quotes can be used to enclose arguments that contain whitespace characters. All content between the open quote and the first matching close quote are preserved by simply removing the pair of quotes.
In the given program, we pass two strings to the Test class, “1 2” and “3”. These strings are then printed out as shown in option C.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Incorrect
When passing arguments to the java command, single (‘) or double (“) quotes can be used to enclose arguments that contain whitespace characters. All content between the open quote and the first matching close quote are preserved by simply removing the pair of quotes.
In the given program, we pass two strings to the Test class, “1 2” and “3”. These strings are then printed out as shown in option C.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Unattempted
When passing arguments to the java command, single (‘) or double (“) quotes can be used to enclose arguments that contain whitespace characters. All content between the open quote and the first matching close quote are preserved by simply removing the pair of quotes.
In the given program, we pass two strings to the Test class, “1 2” and “3”. These strings are then printed out as shown in option C.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
X
Use Page numbers below to navigate to other practice tests