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 6 "
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 Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
int[] arr1 = { 10, 100, 1000 }; //Line n1
char[] arr2 = { ‘x’, ‘y’, ‘z’ }; //Line n2
arr1 = arr2; // Line n3
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " "); //Line n4
}
}
}
ASCII code of 'x' is 120, 'y' is 121 and z is 122. What will be the result of compiling and executing Test class?
Correct
SCP46269:
Line n1 creates an int array object of 3 elements: 10, 100, 1000 and arr1 refers to it.
Line n2 creates an char array object of 3 elements: ‘x’, ‘y’, ‘z’.
Statement `arr1 = arr2;` causes compilation error as char [] is not compatible with int [] even though char is compatible with int.
Incorrect
SCP46269:
Line n1 creates an int array object of 3 elements: 10, 100, 1000 and arr1 refers to it.
Line n2 creates an char array object of 3 elements: ‘x’, ‘y’, ‘z’.
Statement `arr1 = arr2;` causes compilation error as char [] is not compatible with int [] even though char is compatible with int.
Unattempted
SCP46269:
Line n1 creates an int array object of 3 elements: 10, 100, 1000 and arr1 refers to it.
Line n2 creates an char array object of 3 elements: ‘x’, ‘y’, ‘z’.
Statement `arr1 = arr2;` causes compilation error as char [] is not compatible with int [] even though char is compatible with int.
Question 2 of 65
2. Question
Consider below codes of 2 java files:
//Counter.java
package com.udayankhattry.ocp1;
public interface Counter {
int count = 10; //Line n1
}
//Test.java
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
Counter [] arr = new Counter[2]; //Line n2
for(Counter ctr : arr) {
System.out.print(ctr.count); //Line n3
}
}
}
Which of the following statements is correct?
Correct
SCP58614:
Variable ‘count’ declared inside interface Counter is implicitly public, static and final. Line n1 compiles successfully.
Line n2 creates one dimensional array of 2 elements of Counter type and both the elements are initialized to null. Line n2 compiles successfully.
Though correct way to refer static variable is by using the type name, such as Counter.count but it can also be invoked by using Counter reference variable. Hence ctr.count at Line n3 correctly points to the count variable at Line n1.
For invoking static fields, object is not needed, therefore even if ‘ctr’ refers to null, ctr.count doesn’t throw NullPoionterException. Given loop executes twice and therefore output is: 1010
Incorrect
SCP58614:
Variable ‘count’ declared inside interface Counter is implicitly public, static and final. Line n1 compiles successfully.
Line n2 creates one dimensional array of 2 elements of Counter type and both the elements are initialized to null. Line n2 compiles successfully.
Though correct way to refer static variable is by using the type name, such as Counter.count but it can also be invoked by using Counter reference variable. Hence ctr.count at Line n3 correctly points to the count variable at Line n1.
For invoking static fields, object is not needed, therefore even if ‘ctr’ refers to null, ctr.count doesn’t throw NullPoionterException. Given loop executes twice and therefore output is: 1010
Unattempted
SCP58614:
Variable ‘count’ declared inside interface Counter is implicitly public, static and final. Line n1 compiles successfully.
Line n2 creates one dimensional array of 2 elements of Counter type and both the elements are initialized to null. Line n2 compiles successfully.
Though correct way to refer static variable is by using the type name, such as Counter.count but it can also be invoked by using Counter reference variable. Hence ctr.count at Line n3 correctly points to the count variable at Line n1.
For invoking static fields, object is not needed, therefore even if ‘ctr’ refers to null, ctr.count doesn’t throw NullPoionterException. Given loop executes twice and therefore output is: 1010
Question 3 of 65
3. Question
Consider below code of Animal.java file:
class Cat {
public static void main(String args) {
System.out.println(“Cat”);
}
}
class Dog {
public static void main(String [] args) {
System.out.println(“Dog”);
}
}
And the command:
java Animal.java
What is the result?
Correct
SCP39797:
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 Animal.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java Animal.java` is equivalent to (but not exactly same as):
javac -d Animal.java
java -cp Cat
Please note that source-file can contain multiple classes (even public) but first class found must have special main method ‘public static void main(String [])’.
First class defined in Animal.java file is Cat and as it doesn’t contain special main method (parameter is of String type and not String [] type), hence given command causes error.
F:\>java Animal.java
error: can’t find main(String[]) method in class: Cat
SCP39797:
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 Animal.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java Animal.java` is equivalent to (but not exactly same as):
javac -d Animal.java
java -cp Cat
Please note that source-file can contain multiple classes (even public) but first class found must have special main method ‘public static void main(String [])’.
First class defined in Animal.java file is Cat and as it doesn’t contain special main method (parameter is of String type and not String [] type), hence given command causes error.
F:\>java Animal.java
error: can’t find main(String[]) method in class: Cat
SCP39797:
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 Animal.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java Animal.java` is equivalent to (but not exactly same as):
javac -d Animal.java
java -cp Cat
Please note that source-file can contain multiple classes (even public) but first class found must have special main method ‘public static void main(String [])’.
First class defined in Animal.java file is Cat and as it doesn’t contain special main method (parameter is of String type and not String [] type), hence given command causes error.
F:\>java Animal.java
error: can’t find main(String[]) method in class: Cat
What will be the result of compiling and executing Test class?
Correct
SCP12003:
First add parenthesis (round brackets) to the given expression: -a++.
There are 2 operators involved. unary minus and Postfix operator. Let’s start with expression and value of a.
-a++; [a = 1000].Â
-(a++); [a = 1000] Postfix operator has got higher precedence than unary operator.
-(1000); [a = 1001] Use the value of a (1000) in the expression and after that increase the value of a to 1001.
-1000; [a = 1001] -1000 is printed on to the console.
Incorrect
SCP12003:
First add parenthesis (round brackets) to the given expression: -a++.
There are 2 operators involved. unary minus and Postfix operator. Let’s start with expression and value of a.
-a++; [a = 1000].Â
-(a++); [a = 1000] Postfix operator has got higher precedence than unary operator.
-(1000); [a = 1001] Use the value of a (1000) in the expression and after that increase the value of a to 1001.
-1000; [a = 1001] -1000 is printed on to the console.
Unattempted
SCP12003:
First add parenthesis (round brackets) to the given expression: -a++.
There are 2 operators involved. unary minus and Postfix operator. Let’s start with expression and value of a.
-a++; [a = 1000].Â
-(a++); [a = 1000] Postfix operator has got higher precedence than unary operator.
-(1000); [a = 1001] Use the value of a (1000) in the expression and after that increase the value of a to 1001.
-1000; [a = 1001] -1000 is printed on to the console.
Question 5 of 65
5. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
char c1 = ‘a’; //ASCII code of ‘a’ is 97
int i1 = c1; //Line n1
System.out.println(i1); //Line n2
}
}
What is the result of compiling and executing Test class?
Correct
SCP71029:
Range of char data type is from 0 to 65535 and hence it can be easily assigned to int type. println() method is overloaded to accept char type and int type both. If char type value is passed, it prints char value and if int type value is passed, it prints int value.
As i1 is of int type, hence corresponding int value, which is 97, is printed on to the console.
Incorrect
SCP71029:
Range of char data type is from 0 to 65535 and hence it can be easily assigned to int type. println() method is overloaded to accept char type and int type both. If char type value is passed, it prints char value and if int type value is passed, it prints int value.
As i1 is of int type, hence corresponding int value, which is 97, is printed on to the console.
Unattempted
SCP71029:
Range of char data type is from 0 to 65535 and hence it can be easily assigned to int type. println() method is overloaded to accept char type and int type both. If char type value is passed, it prints char value and if int type value is passed, it prints int value.
As i1 is of int type, hence corresponding int value, which is 97, is printed on to the console.
Question 6 of 65
6. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
class Base {
static void print() { //Line n1
System.out.println(“BASE”);
}
}
class Derived extends Base {
static void print() { //Line n2
System.out.println(“DERIVED”);
}
}
public class Test {
public static void main(String[] args) {
Base b = null;
Derived d = (Derived) b; //Line n3
d.print(); //Line n4
}
}
Which of the following statements is true for above code?
Correct
SCP82979:
print() method at Line n2 hides the method at Line n1. So, no compilation error at Line n2.
Reference variable ‘b’ is of type Base, so `(Derived) b` does not cause any compilation error. Moreover, at runtime it will not throw any ClassCastException as well because b is null. Had ‘b’ been referring to an instance of Base class [Base b = new Base();], `(Derived) b` would have thrown ClassCastException.
d.print(); doesn’t cause any 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. Derived.print(); is the preferred syntax.
d.print(); invokes the static print() method of Derived class and prints DERIVED on to the console.
Incorrect
SCP82979:
print() method at Line n2 hides the method at Line n1. So, no compilation error at Line n2.
Reference variable ‘b’ is of type Base, so `(Derived) b` does not cause any compilation error. Moreover, at runtime it will not throw any ClassCastException as well because b is null. Had ‘b’ been referring to an instance of Base class [Base b = new Base();], `(Derived) b` would have thrown ClassCastException.
d.print(); doesn’t cause any 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. Derived.print(); is the preferred syntax.
d.print(); invokes the static print() method of Derived class and prints DERIVED on to the console.
Unattempted
SCP82979:
print() method at Line n2 hides the method at Line n1. So, no compilation error at Line n2.
Reference variable ‘b’ is of type Base, so `(Derived) b` does not cause any compilation error. Moreover, at runtime it will not throw any ClassCastException as well because b is null. Had ‘b’ been referring to an instance of Base class [Base b = new Base();], `(Derived) b` would have thrown ClassCastException.
d.print(); doesn’t cause any 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. Derived.print(); is the preferred syntax.
d.print(); invokes the static print() method of Derived class and prints DERIVED on to the console.
Question 7 of 65
7. Question
Consider below code of Test.java file:
public class Test {
public static void print() {
System.out.println(“STATIC METHOD!!!”);
}
public static void main(String[] args) {
Test obj = null; //Line n1
obj.print(); //Line n2
}
}
What will be the result of compiling and executing Test class?
Correct
SCP66900:
print() is static method of class Test. So correct syntax to invoke method print() is Test.print();
but static methods can also be invoked using reference variable: obj.print(); Warning is displayed in this case.
Even though obj has null value, we don’t get NullPointerException as objects are not needed to invoke static methods.
Incorrect
SCP66900:
print() is static method of class Test. So correct syntax to invoke method print() is Test.print();
but static methods can also be invoked using reference variable: obj.print(); Warning is displayed in this case.
Even though obj has null value, we don’t get NullPointerException as objects are not needed to invoke static methods.
Unattempted
SCP66900:
print() is static method of class Test. So correct syntax to invoke method print() is Test.print();
but static methods can also be invoked using reference variable: obj.print(); Warning is displayed in this case.
Even though obj has null value, we don’t get NullPointerException as objects are not needed to invoke static methods.
Question 8 of 65
8. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
String word = “REBUS”;
/* INSERT */
System.out.println(word);
}
}
Following options are available to replace /*INSERT*/:
1. word = word.substring(2);
2. word = word.substring(2, 4);
3. word = word.substring(2, 5);
4. word = word.replace(“RE”, “”);
5. word = word.substring(2, 6);
6. word = word.delete(0, 2);
How many of the above options can be used to replace /*INSERT*/ (separately and not together) such that given command prints BUS on to the console?
Correct
SCP78964:
substring(int beginIndex, int endIndex) method of String class extracts the substring, which begins at the specified beginIndex and extends to the character at index endIndex – 1.
This method throws IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex. e.g.
“freeway”.substring(4, 7) returns “way”
“freeway”.substring(4, 8) throws IndexOutOfBoundsException
substring?(int beginIndex) method of String class extracts the substring, which begins with the character at the specified index and extends to the end of this string.
This method throws IndexOutOfBoundsException if beginIndex is negative or larger than the length of this String object. e.g.
“freeway”.substring(4) returns “way”
“freeway”.substring(8) throws IndexOutOfBoundsException
replace(CharSequence target, CharSequence replacement) method of String class returns a new String object after replacing each substring of this string that matches the literal target sequence with the specified literal replacement sequence. e.g.
“Java”.replace(“a”, “A”) –> returns new String object “JAvA”.
Let’s check all the given options:
“REBUS”.substring(2); [begin = 2, end = 4 (end of the string)], returns “BUS” and hence it is a correct option.
“REBUS”.substring(2, 4); [begin = 2, end = 3 (endIndex – 1)], returns “BU” and hence it is incorrect option.
“REBUS”.substring(2, 5); [begin = 2, end = 4 (endIndex – 1)], returns “BUS” and hence it is a correct option.
“REBUS”.replace(“RE”, “”); It replaces “RE” with empty string “” and returns “BUS”, so it is also a correct option.
“REBUS”.substring(2, 6); Length of “REBUS” = 5 and endIndex = 6, which is greater than 5, hence it will thrown IndexOutOfBoundsException at runtime. Incorrect option
“REBUS”.delete(0, 2); Compilation error as delete(…) method is not available in String class, it is part of StringBuilder class. Incorrect option.
So, total 3 options will replace /*INSERT*/ to print BUS on to the console.
Incorrect
SCP78964:
substring(int beginIndex, int endIndex) method of String class extracts the substring, which begins at the specified beginIndex and extends to the character at index endIndex – 1.
This method throws IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex. e.g.
“freeway”.substring(4, 7) returns “way”
“freeway”.substring(4, 8) throws IndexOutOfBoundsException
substring?(int beginIndex) method of String class extracts the substring, which begins with the character at the specified index and extends to the end of this string.
This method throws IndexOutOfBoundsException if beginIndex is negative or larger than the length of this String object. e.g.
“freeway”.substring(4) returns “way”
“freeway”.substring(8) throws IndexOutOfBoundsException
replace(CharSequence target, CharSequence replacement) method of String class returns a new String object after replacing each substring of this string that matches the literal target sequence with the specified literal replacement sequence. e.g.
“Java”.replace(“a”, “A”) –> returns new String object “JAvA”.
Let’s check all the given options:
“REBUS”.substring(2); [begin = 2, end = 4 (end of the string)], returns “BUS” and hence it is a correct option.
“REBUS”.substring(2, 4); [begin = 2, end = 3 (endIndex – 1)], returns “BU” and hence it is incorrect option.
“REBUS”.substring(2, 5); [begin = 2, end = 4 (endIndex – 1)], returns “BUS” and hence it is a correct option.
“REBUS”.replace(“RE”, “”); It replaces “RE” with empty string “” and returns “BUS”, so it is also a correct option.
“REBUS”.substring(2, 6); Length of “REBUS” = 5 and endIndex = 6, which is greater than 5, hence it will thrown IndexOutOfBoundsException at runtime. Incorrect option
“REBUS”.delete(0, 2); Compilation error as delete(…) method is not available in String class, it is part of StringBuilder class. Incorrect option.
So, total 3 options will replace /*INSERT*/ to print BUS on to the console.
Unattempted
SCP78964:
substring(int beginIndex, int endIndex) method of String class extracts the substring, which begins at the specified beginIndex and extends to the character at index endIndex – 1.
This method throws IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex. e.g.
“freeway”.substring(4, 7) returns “way”
“freeway”.substring(4, 8) throws IndexOutOfBoundsException
substring?(int beginIndex) method of String class extracts the substring, which begins with the character at the specified index and extends to the end of this string.
This method throws IndexOutOfBoundsException if beginIndex is negative or larger than the length of this String object. e.g.
“freeway”.substring(4) returns “way”
“freeway”.substring(8) throws IndexOutOfBoundsException
replace(CharSequence target, CharSequence replacement) method of String class returns a new String object after replacing each substring of this string that matches the literal target sequence with the specified literal replacement sequence. e.g.
“Java”.replace(“a”, “A”) –> returns new String object “JAvA”.
Let’s check all the given options:
“REBUS”.substring(2); [begin = 2, end = 4 (end of the string)], returns “BUS” and hence it is a correct option.
“REBUS”.substring(2, 4); [begin = 2, end = 3 (endIndex – 1)], returns “BU” and hence it is incorrect option.
“REBUS”.substring(2, 5); [begin = 2, end = 4 (endIndex – 1)], returns “BUS” and hence it is a correct option.
“REBUS”.replace(“RE”, “”); It replaces “RE” with empty string “” and returns “BUS”, so it is also a correct option.
“REBUS”.substring(2, 6); Length of “REBUS” = 5 and endIndex = 6, which is greater than 5, hence it will thrown IndexOutOfBoundsException at runtime. Incorrect option
“REBUS”.delete(0, 2); Compilation error as delete(…) method is not available in String class, it is part of StringBuilder class. Incorrect option.
So, total 3 options will replace /*INSERT*/ to print BUS on to the console.
Question 9 of 65
9. Question
You have below two modular jars available on your windows system:
1. C:\jars\jar1\secret_one.jar
Module name is ‘secret’ and it contains ‘com.udayankhattry.ocp1.Secret’ class, corresponding java source has below code:
package com.udayankhattry.ocp1;
public class Secret {
public static void main(String… args) {
var str = “ADTETFAECNKD”;
for(int i = 0; i < str.length(); i+=2) {
System.out.print(str.charAt(i));
}
}
}
2. C:\jars\jar2\secret_two.jar
Module name is 'secret' and it contains 'com.udayankhattry.ocp1.Secret' class, corresponding java source has below code:
package com.udayankhattry.ocp1;
public class Secret {
public static void main(String... args) {
var str = "ADTETFAECNKD";
for(int i = 1; i < str.length(); i+=2) {
System.out.print(str.charAt(i));
}
}
}
What will be the result of executing below command from C:\?
Correct
SCP52034:
Logic in secret_one.jar is to take the source string “ADTETFAECNKD” and print the alternate characters starting at index 0, hence it prints ATTACK
and
Logic in secret_two.jar is to take the source string “ADTETFAECNKD” and print the alternate characters starting at index 1, hence it prints DEFEND
Format of the java command related to module is:
java [options] -m [/] [args…]
java [options] –module [/] [args…]
   (to execute the main class in a module)
  Â
–module or -m: It corresponds to module name. -m should be the last option used in the command. -m is followed by module-name, then by optional mainclass and any command-line arguments. If module is packaged in the jar and ‘Main-Class’ attribute is set, then passing classname after -m is optional.Â
  Â
And below is the important option (related to modules) of java command:
–module-path or -p: It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries.
For example, java -p out;singlemodule;connector.jar represents a module path which contains all the modules inside ‘out’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
When multiple modules with the same name are in different jar files on the module path, first module is selected and rest of the modules with same name are ignored. As first modular jar file in module path is ‘secret_two.jar’, hence com.udayankhattry.ocp1.Secret class defined in secret_two.jar file executes, which prints DEFEND on to the console.
Incorrect
SCP52034:
Logic in secret_one.jar is to take the source string “ADTETFAECNKD” and print the alternate characters starting at index 0, hence it prints ATTACK
and
Logic in secret_two.jar is to take the source string “ADTETFAECNKD” and print the alternate characters starting at index 1, hence it prints DEFEND
Format of the java command related to module is:
java [options] -m [/] [args…]
java [options] –module [/] [args…]
   (to execute the main class in a module)
  Â
–module or -m: It corresponds to module name. -m should be the last option used in the command. -m is followed by module-name, then by optional mainclass and any command-line arguments. If module is packaged in the jar and ‘Main-Class’ attribute is set, then passing classname after -m is optional.Â
  Â
And below is the important option (related to modules) of java command:
–module-path or -p: It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries.
For example, java -p out;singlemodule;connector.jar represents a module path which contains all the modules inside ‘out’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
When multiple modules with the same name are in different jar files on the module path, first module is selected and rest of the modules with same name are ignored. As first modular jar file in module path is ‘secret_two.jar’, hence com.udayankhattry.ocp1.Secret class defined in secret_two.jar file executes, which prints DEFEND on to the console.
Unattempted
SCP52034:
Logic in secret_one.jar is to take the source string “ADTETFAECNKD” and print the alternate characters starting at index 0, hence it prints ATTACK
and
Logic in secret_two.jar is to take the source string “ADTETFAECNKD” and print the alternate characters starting at index 1, hence it prints DEFEND
Format of the java command related to module is:
java [options] -m [/] [args…]
java [options] –module [/] [args…]
   (to execute the main class in a module)
  Â
–module or -m: It corresponds to module name. -m should be the last option used in the command. -m is followed by module-name, then by optional mainclass and any command-line arguments. If module is packaged in the jar and ‘Main-Class’ attribute is set, then passing classname after -m is optional.Â
  Â
And below is the important option (related to modules) of java command:
–module-path or -p: It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries.
For example, java -p out;singlemodule;connector.jar represents a module path which contains all the modules inside ‘out’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
When multiple modules with the same name are in different jar files on the module path, first module is selected and rest of the modules with same name are ignored. As first modular jar file in module path is ‘secret_two.jar’, hence com.udayankhattry.ocp1.Secret class defined in secret_two.jar file executes, which prints DEFEND on to the console.
“public class Test {
public static void main(String[] args) {
System.out.println(StringUtil.reverse(“”ROTATOR””));
System.out.println(StringUtility.reverse(“”NOON””));
}
}
”
“And the command executed from C:\
javac -d out –module-source-path src -m testing
”
Which of the following statements is correct?
Correct
SCP14607:
Module ‘string.util’ has two packages: ‘com.udayankhattry.ocp1.util’ and ‘com.udayankhattry.utility’ and its module descriptor file (module-info.java) has exports directive only for ‘com.udayankhattry.ocp1.util’ package.
Module descriptor of ‘testing’ module has requires directive for ‘string.util’ module. Hence, ‘testing’ module has access to all the public classes in ‘com.udayankhattry.ocp1.util’ package and not ‘com.udayankhattry.utility’ package.
Therefore, there is a compilation error in Test.java file. Below 2 statements in Test.java file cause compilation error:
import com.udayankhattry.utility.StringUtility;
and
System.out.println(StringUtility.reverse(“NOON”));
This is one more layer of encapsulation provided by the Java Module System, in which not all the public classes are accessible to everyone, as this was the case with pre-module codes.
public classes defined in exported packages are accessible and not the un-exported packages.
Incorrect
SCP14607:
Module ‘string.util’ has two packages: ‘com.udayankhattry.ocp1.util’ and ‘com.udayankhattry.utility’ and its module descriptor file (module-info.java) has exports directive only for ‘com.udayankhattry.ocp1.util’ package.
Module descriptor of ‘testing’ module has requires directive for ‘string.util’ module. Hence, ‘testing’ module has access to all the public classes in ‘com.udayankhattry.ocp1.util’ package and not ‘com.udayankhattry.utility’ package.
Therefore, there is a compilation error in Test.java file. Below 2 statements in Test.java file cause compilation error:
import com.udayankhattry.utility.StringUtility;
and
System.out.println(StringUtility.reverse(“NOON”));
This is one more layer of encapsulation provided by the Java Module System, in which not all the public classes are accessible to everyone, as this was the case with pre-module codes.
public classes defined in exported packages are accessible and not the un-exported packages.
Unattempted
SCP14607:
Module ‘string.util’ has two packages: ‘com.udayankhattry.ocp1.util’ and ‘com.udayankhattry.utility’ and its module descriptor file (module-info.java) has exports directive only for ‘com.udayankhattry.ocp1.util’ package.
Module descriptor of ‘testing’ module has requires directive for ‘string.util’ module. Hence, ‘testing’ module has access to all the public classes in ‘com.udayankhattry.ocp1.util’ package and not ‘com.udayankhattry.utility’ package.
Therefore, there is a compilation error in Test.java file. Below 2 statements in Test.java file cause compilation error:
import com.udayankhattry.utility.StringUtility;
and
System.out.println(StringUtility.reverse(“NOON”));
This is one more layer of encapsulation provided by the Java Module System, in which not all the public classes are accessible to everyone, as this was the case with pre-module codes.
public classes defined in exported packages are accessible and not the un-exported packages.
Question 11 of 65
11. Question
Which of the following code segments, written inside main method will compile successfully?
Select ALL that apply.
Correct
SCP88702:
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.
But there are certain restrictions on using var type:
Declaration and initialization should be in one statement, hence `var num; num = 10;` won’t compile.
var is not allowed as an element type of an array, hence `var [] arr1 = new String[2];` won’t compile.
Explicit target-type is needed for the array initializer, if you use var type. Hence, `var arr2 = {1, 2, 3};` won’t compile.
If you provide the target-type, `var arr2 = new int[]{1, 2, 3};`, then there is no compilation error and in this case var infers to int [] type.
If initializer is of null type, then it is not possible to infer the target type, hence `var msg = null;` won’t compile.
Also note that, var type cannot be the target type of lambda expressions and method references.
`final var str = “Hello”;` will compile successfully as ‘str’ infers to String type and final modifier is allowed for local variables.
`private var y = 100;` will not compile as private modifier is not allowed for local variables.
var can easily be used for enhanced for-loop indexes, and index variables declared in traditional for loops, hence both the loop code segments will compile successfully.
SCP88702:
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.
But there are certain restrictions on using var type:
Declaration and initialization should be in one statement, hence `var num; num = 10;` won’t compile.
var is not allowed as an element type of an array, hence `var [] arr1 = new String[2];` won’t compile.
Explicit target-type is needed for the array initializer, if you use var type. Hence, `var arr2 = {1, 2, 3};` won’t compile.
If you provide the target-type, `var arr2 = new int[]{1, 2, 3};`, then there is no compilation error and in this case var infers to int [] type.
If initializer is of null type, then it is not possible to infer the target type, hence `var msg = null;` won’t compile.
Also note that, var type cannot be the target type of lambda expressions and method references.
`final var str = “Hello”;` will compile successfully as ‘str’ infers to String type and final modifier is allowed for local variables.
`private var y = 100;` will not compile as private modifier is not allowed for local variables.
var can easily be used for enhanced for-loop indexes, and index variables declared in traditional for loops, hence both the loop code segments will compile successfully.
SCP88702:
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.
But there are certain restrictions on using var type:
Declaration and initialization should be in one statement, hence `var num; num = 10;` won’t compile.
var is not allowed as an element type of an array, hence `var [] arr1 = new String[2];` won’t compile.
Explicit target-type is needed for the array initializer, if you use var type. Hence, `var arr2 = {1, 2, 3};` won’t compile.
If you provide the target-type, `var arr2 = new int[]{1, 2, 3};`, then there is no compilation error and in this case var infers to int [] type.
If initializer is of null type, then it is not possible to infer the target type, hence `var msg = null;` won’t compile.
Also note that, var type cannot be the target type of lambda expressions and method references.
`final var str = “Hello”;` will compile successfully as ‘str’ infers to String type and final modifier is allowed for local variables.
`private var y = 100;` will not compile as private modifier is not allowed for local variables.
var can easily be used for enhanced for-loop indexes, and index variables declared in traditional for loops, hence both the loop code segments will compile successfully.
Choose the option that meets the following specification:
Create a well encapsulated class Clock with one instance variable model.
The value of model should be accessible and modifiable outside Clock.
Correct
SCP69380:
Encapsulation is all about having private instance variable and providing public getter and setter methods.
Out of the given 4 options, below option provides a well encapsulated Clock class:
public class Clock {
private String model;
public String getModel() { return model; }
public void setModel(String val) { model = val; }
}
Incorrect
SCP69380:
Encapsulation is all about having private instance variable and providing public getter and setter methods.
Out of the given 4 options, below option provides a well encapsulated Clock class:
public class Clock {
private String model;
public String getModel() { return model; }
public void setModel(String val) { model = val; }
}
Unattempted
SCP69380:
Encapsulation is all about having private instance variable and providing public getter and setter methods.
Out of the given 4 options, below option provides a well encapsulated Clock class:
public class Clock {
private String model;
public String getModel() { return model; }
public void setModel(String val) { model = val; }
}
Question 13 of 65
13. Question
Which of the following array declarations and initializations is NOT legal?
Correct
SCP80385:
`char [] arr1 [] = new char[5][];`: Creates two-dimensional array object, whose 1st dimension is 5 but 2nd dimension is not yet defined. On the left side array symbols can be used before the reference variable or after the reference variable or can be mixed, hence `char [][] arr1`, `char [] arr1 []` and `char arr1[][]` all are valid. This statement compiles successfully.
`byte [] val = new byte[10];`: Creates one-dimensional byte array object and val refers to it. All the array elements are initialized to 0. This statement compiles without any error.
`int [] arr2 = {1, 2, 3, 4, 5};`: This syntax creates one-dimensional int array object of 5 elements and initializes these 5 elements as well. It initializes element at 0th index to 1, element at 1st index to 2, element at 2nd index to 3, element at 3rd index to 4 and element at 4th index to 5. ‘arr2’ refers to this one-dimensional array object. This statement also compiles fine.
`int [] arr3 = new int[3]{10, 20, 30};`: You can’t specify size at the time of initializing with data, hence `new int[3]{10, 20, 30};` causes compilation error.
Correct syntax is: `int [] arr3 = new int[]{10, 20, 30};` OR `int [] arr3 = {10, 20, 30};`
Incorrect
SCP80385:
`char [] arr1 [] = new char[5][];`: Creates two-dimensional array object, whose 1st dimension is 5 but 2nd dimension is not yet defined. On the left side array symbols can be used before the reference variable or after the reference variable or can be mixed, hence `char [][] arr1`, `char [] arr1 []` and `char arr1[][]` all are valid. This statement compiles successfully.
`byte [] val = new byte[10];`: Creates one-dimensional byte array object and val refers to it. All the array elements are initialized to 0. This statement compiles without any error.
`int [] arr2 = {1, 2, 3, 4, 5};`: This syntax creates one-dimensional int array object of 5 elements and initializes these 5 elements as well. It initializes element at 0th index to 1, element at 1st index to 2, element at 2nd index to 3, element at 3rd index to 4 and element at 4th index to 5. ‘arr2’ refers to this one-dimensional array object. This statement also compiles fine.
`int [] arr3 = new int[3]{10, 20, 30};`: You can’t specify size at the time of initializing with data, hence `new int[3]{10, 20, 30};` causes compilation error.
Correct syntax is: `int [] arr3 = new int[]{10, 20, 30};` OR `int [] arr3 = {10, 20, 30};`
Unattempted
SCP80385:
`char [] arr1 [] = new char[5][];`: Creates two-dimensional array object, whose 1st dimension is 5 but 2nd dimension is not yet defined. On the left side array symbols can be used before the reference variable or after the reference variable or can be mixed, hence `char [][] arr1`, `char [] arr1 []` and `char arr1[][]` all are valid. This statement compiles successfully.
`byte [] val = new byte[10];`: Creates one-dimensional byte array object and val refers to it. All the array elements are initialized to 0. This statement compiles without any error.
`int [] arr2 = {1, 2, 3, 4, 5};`: This syntax creates one-dimensional int array object of 5 elements and initializes these 5 elements as well. It initializes element at 0th index to 1, element at 1st index to 2, element at 2nd index to 3, element at 3rd index to 4 and element at 4th index to 5. ‘arr2’ refers to this one-dimensional array object. This statement also compiles fine.
`int [] arr3 = new int[3]{10, 20, 30};`: You can’t specify size at the time of initializing with data, hence `new int[3]{10, 20, 30};` causes compilation error.
Correct syntax is: `int [] arr3 = new int[]{10, 20, 30};` OR `int [] arr3 = {10, 20, 30};`
Question 14 of 65
14. Question
For the class Test, which options, if used to replace /*INSERT*/, will print TEN 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 10:
System.out.println(“TEN”);
break;
default:
System.out.println(“DEFAULT”);
}
}
}
Correct
SCP14416:
switch can accept primitive types: byte, short, int, char; wrapper types: Byte, Short, Integer, Character; String and enums. In this case long and double are invalid values to be passed in switch expression. char uses 16 bits (2 Bytes) and its range is 0 to 65535 (no signed bit reserved) so it can easily store value 10.
Please 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
SCP14416:
switch can accept primitive types: byte, short, int, char; wrapper types: Byte, Short, Integer, Character; String and enums. In this case long and double are invalid values to be passed in switch expression. char uses 16 bits (2 Bytes) and its range is 0 to 65535 (no signed bit reserved) so it can easily store value 10.
Please 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
SCP14416:
switch can accept primitive types: byte, short, int, char; wrapper types: Byte, Short, Integer, Character; String and enums. In this case long and double are invalid values to be passed in switch expression. char uses 16 bits (2 Bytes) and its range is 0 to 65535 (no signed bit reserved) so it can easily store value 10.
Please 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 15 of 65
15. Question
Given below the directory/file structure on Windows platform:
C:
+—out
\—src
\—medicines
| module-info.java
|
\—com
\—allopathic
Medicines.java
Below are the codes of Java files:-
C:\src\medicines\module-info.java:
module medicines {
exports com.allopathic to elizabeth_hospital;
}
Please note that module ‘elizabeth_hospital’ is not available.
public class Medicines {
public static java.util.List getAll() {
return null;
}
}
And the command executed from C:\
javac -d out –module-source-path src -m medicines
What is the result?
Correct
SCP14844:
There is no compilation error in Medicines.java file.
By looking at the contents of module descriptor file (module-info.java), it can be said that:
– Name of the module is: medicines
– exports com.allopathic to elizabeth_hospital; => This is known as qualified export, in which package ‘com.allopathic’ is made available to only named module ‘elizabeth_hospital’.
If the module name, to which package is exported to (elizabeth_hospital in this case), is not available, then compiler displays the warning but compiles the code.
After executing the given javac command, you will have below directory/file structure:
C:
+—out
| \—medicines
| | module-info.class
| |
| \—com
| \—allopathic
| Medicines.class
|
\—src
\—medicines
| module-info.java
|
\—com
\—allopathic
Medicines.java
Incorrect
SCP14844:
There is no compilation error in Medicines.java file.
By looking at the contents of module descriptor file (module-info.java), it can be said that:
– Name of the module is: medicines
– exports com.allopathic to elizabeth_hospital; => This is known as qualified export, in which package ‘com.allopathic’ is made available to only named module ‘elizabeth_hospital’.
If the module name, to which package is exported to (elizabeth_hospital in this case), is not available, then compiler displays the warning but compiles the code.
After executing the given javac command, you will have below directory/file structure:
C:
+—out
| \—medicines
| | module-info.class
| |
| \—com
| \—allopathic
| Medicines.class
|
\—src
\—medicines
| module-info.java
|
\—com
\—allopathic
Medicines.java
Unattempted
SCP14844:
There is no compilation error in Medicines.java file.
By looking at the contents of module descriptor file (module-info.java), it can be said that:
– Name of the module is: medicines
– exports com.allopathic to elizabeth_hospital; => This is known as qualified export, in which package ‘com.allopathic’ is made available to only named module ‘elizabeth_hospital’.
If the module name, to which package is exported to (elizabeth_hospital in this case), is not available, then compiler displays the warning but compiles the code.
After executing the given javac command, you will have below directory/file structure:
C:
+—out
| \—medicines
| | module-info.class
| |
| \—com
| \—allopathic
| Medicines.class
|
\—src
\—medicines
| module-info.java
|
\—com
\—allopathic
Medicines.java
Question 16 of 65
16. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
final String fName = “James”;
String lName = “Gosling”;
String name1 = fName + lName;
String name2 = fName + “Gosling”;
String name3 = “James” + “Gosling”;
System.out.println(name1 == name2);
System.out.println(name2 == name3);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP66926:
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.
fName is a constant variable and lName is a non-constant variable.
`fName + lName` is not a constant expression and hence the expression will be computed at run-time and the resultant String object “JamesGosling” will not be referred by String Pool.
As fName is constant variable and “Gosling” is String literal, hence the expression `fName + “Gosling”` is a constant expression, therefore expression is computed at compile-time and results in String literal “JamesGosling”.
So, during compilation, Java compiler translates the statement
String name2 = fName + “Gosling”;
to
String name2 = “JamesGosling”;
As “JamesGosling” is a String literal, hence at runtime it will be referred by String Pool.
So, at runtime name1 and name2 refer to different String object and that is why name1 == name2 returns false.
`”James” + “Gosling”` is also a constant expression and hence Java compiler translates the statement
String name3 = “James” + “Gosling”;
to
String name3 = “JamesGosling”;
This means at runtime, variable ‘name3’ will refer to the same String pool object “JamesGosling”, which is referred by variable ‘name3’.
So, name2 and name3 refer to same String object and that is why name2 == name3 returns true.
Incorrect
SCP66926:
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.
fName is a constant variable and lName is a non-constant variable.
`fName + lName` is not a constant expression and hence the expression will be computed at run-time and the resultant String object “JamesGosling” will not be referred by String Pool.
As fName is constant variable and “Gosling” is String literal, hence the expression `fName + “Gosling”` is a constant expression, therefore expression is computed at compile-time and results in String literal “JamesGosling”.
So, during compilation, Java compiler translates the statement
String name2 = fName + “Gosling”;
to
String name2 = “JamesGosling”;
As “JamesGosling” is a String literal, hence at runtime it will be referred by String Pool.
So, at runtime name1 and name2 refer to different String object and that is why name1 == name2 returns false.
`”James” + “Gosling”` is also a constant expression and hence Java compiler translates the statement
String name3 = “James” + “Gosling”;
to
String name3 = “JamesGosling”;
This means at runtime, variable ‘name3’ will refer to the same String pool object “JamesGosling”, which is referred by variable ‘name3’.
So, name2 and name3 refer to same String object and that is why name2 == name3 returns true.
Unattempted
SCP66926:
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.
fName is a constant variable and lName is a non-constant variable.
`fName + lName` is not a constant expression and hence the expression will be computed at run-time and the resultant String object “JamesGosling” will not be referred by String Pool.
As fName is constant variable and “Gosling” is String literal, hence the expression `fName + “Gosling”` is a constant expression, therefore expression is computed at compile-time and results in String literal “JamesGosling”.
So, during compilation, Java compiler translates the statement
String name2 = fName + “Gosling”;
to
String name2 = “JamesGosling”;
As “JamesGosling” is a String literal, hence at runtime it will be referred by String Pool.
So, at runtime name1 and name2 refer to different String object and that is why name1 == name2 returns false.
`”James” + “Gosling”` is also a constant expression and hence Java compiler translates the statement
String name3 = “James” + “Gosling”;
to
String name3 = “JamesGosling”;
This means at runtime, variable ‘name3’ will refer to the same String pool object “JamesGosling”, which is referred by variable ‘name3’.
So, name2 and name3 refer to same String object and that is why name2 == name3 returns true.
Question 17 of 65
17. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
String text = ” BE YOURSELF! “; //Contains multiple space characters
System.out.println(text./*INSERT*/);
}
}
Which of the following options, if used to replace /*INSERT*/, will compile successfully and on execution will print “BE YOURSELF!” on to the console?
Select ALL that apply.
Correct
SCP76962:
Javadoc of trim() method states that it returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to ‘U+0020’ or ‘\u0020’ (the space character).
As the developer comment in above code states that ‘text’ refers to String object containing multiple space characters, hence text.trim() returns “BE YOURSELF!” after removing all leading and trailing space characters. Hence trim() is correct option.
stripLeading(), stripTrailing() and strip() were added in Java 11.
stripLeading() returns a string whose value is this string, with all leading white space removed.
stripTrailing() returns a string whose value is this string, with all trailing white space removed.
strip() returns a string whose value is this string, with all leading and trailing white space removed.
Point to note here is that trim() method works with space, where space is defined as any character whose codepoint is less than or equal to ‘U+0020’ or ‘\u0020’ (the space character) but strip(), stripLeading() and stripTrailing() works with white space.
To find out what is white space character in Java, check Character.isWhitespace?(int) method, you will find below:
A character is a Java whitespace character if and only if it satisfies one of the following criteria:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’).
It is ‘\t’, U+0009 HORIZONTAL TABULATION.
It is ‘\n’, U+000A LINE FEED.
It is ‘\u000B’, U+000B VERTICAL TABULATION.
It is ‘\f’, U+000C FORM FEED.
It is ‘\r’, U+000D CARRIAGE RETURN.
It is ‘\u001C’, U+001C FILE SEPARATOR.
It is ‘\u001D’, U+001D GROUP SEPARATOR.
It is ‘\u001E’, U+001E RECORD SEPARATOR.
It is ‘\u001F’, U+001F UNIT SEPARATOR.
White space character in java includes space character along with above characters.
Hence, text.strip() will successfully remove all the leading and trailing white spaces and will return “BE YOURSELF!”.
text.stripLeading().stripTrailing() will first remove leading white space and then trailing white space and will return “BE YOURSELF!”.
String class doesn’t have methods with the names: ltrim(), rtrim(), trimLeading(), trimTrailing() and trimBoth(), hence these will cause compilation error.
Incorrect
SCP76962:
Javadoc of trim() method states that it returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to ‘U+0020’ or ‘\u0020’ (the space character).
As the developer comment in above code states that ‘text’ refers to String object containing multiple space characters, hence text.trim() returns “BE YOURSELF!” after removing all leading and trailing space characters. Hence trim() is correct option.
stripLeading(), stripTrailing() and strip() were added in Java 11.
stripLeading() returns a string whose value is this string, with all leading white space removed.
stripTrailing() returns a string whose value is this string, with all trailing white space removed.
strip() returns a string whose value is this string, with all leading and trailing white space removed.
Point to note here is that trim() method works with space, where space is defined as any character whose codepoint is less than or equal to ‘U+0020’ or ‘\u0020’ (the space character) but strip(), stripLeading() and stripTrailing() works with white space.
To find out what is white space character in Java, check Character.isWhitespace?(int) method, you will find below:
A character is a Java whitespace character if and only if it satisfies one of the following criteria:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’).
It is ‘\t’, U+0009 HORIZONTAL TABULATION.
It is ‘\n’, U+000A LINE FEED.
It is ‘\u000B’, U+000B VERTICAL TABULATION.
It is ‘\f’, U+000C FORM FEED.
It is ‘\r’, U+000D CARRIAGE RETURN.
It is ‘\u001C’, U+001C FILE SEPARATOR.
It is ‘\u001D’, U+001D GROUP SEPARATOR.
It is ‘\u001E’, U+001E RECORD SEPARATOR.
It is ‘\u001F’, U+001F UNIT SEPARATOR.
White space character in java includes space character along with above characters.
Hence, text.strip() will successfully remove all the leading and trailing white spaces and will return “BE YOURSELF!”.
text.stripLeading().stripTrailing() will first remove leading white space and then trailing white space and will return “BE YOURSELF!”.
String class doesn’t have methods with the names: ltrim(), rtrim(), trimLeading(), trimTrailing() and trimBoth(), hence these will cause compilation error.
Unattempted
SCP76962:
Javadoc of trim() method states that it returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to ‘U+0020’ or ‘\u0020’ (the space character).
As the developer comment in above code states that ‘text’ refers to String object containing multiple space characters, hence text.trim() returns “BE YOURSELF!” after removing all leading and trailing space characters. Hence trim() is correct option.
stripLeading(), stripTrailing() and strip() were added in Java 11.
stripLeading() returns a string whose value is this string, with all leading white space removed.
stripTrailing() returns a string whose value is this string, with all trailing white space removed.
strip() returns a string whose value is this string, with all leading and trailing white space removed.
Point to note here is that trim() method works with space, where space is defined as any character whose codepoint is less than or equal to ‘U+0020’ or ‘\u0020’ (the space character) but strip(), stripLeading() and stripTrailing() works with white space.
To find out what is white space character in Java, check Character.isWhitespace?(int) method, you will find below:
A character is a Java whitespace character if and only if it satisfies one of the following criteria:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’).
It is ‘\t’, U+0009 HORIZONTAL TABULATION.
It is ‘\n’, U+000A LINE FEED.
It is ‘\u000B’, U+000B VERTICAL TABULATION.
It is ‘\f’, U+000C FORM FEED.
It is ‘\r’, U+000D CARRIAGE RETURN.
It is ‘\u001C’, U+001C FILE SEPARATOR.
It is ‘\u001D’, U+001D GROUP SEPARATOR.
It is ‘\u001E’, U+001E RECORD SEPARATOR.
It is ‘\u001F’, U+001F UNIT SEPARATOR.
White space character in java includes space character along with above characters.
Hence, text.strip() will successfully remove all the leading and trailing white spaces and will return “BE YOURSELF!”.
text.stripLeading().stripTrailing() will first remove leading white space and then trailing white space and will return “BE YOURSELF!”.
String class doesn’t have methods with the names: ltrim(), rtrim(), trimLeading(), trimTrailing() and trimBoth(), hence these will cause compilation error.
Question 18 of 65
18. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String [] args) {
var arr = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; //Line n1
String str = process(arr, 3, 8); //Line n2
System.out.println(str);
}
/*INSERT*/
}
Line n2 causes compilation error as process method is not found.
Which of the following method definitions, if used to replace /*INSERT*/, will resolve the compilation error?
Correct
SCP88920:
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.
At Line n1, arr infers to int[] type.
It is clear from Line n2 that, method name should be process, it should be static method, it should accept 3 parameters (int[], int, int) and its return type must be String. Hence below definition is correct:
private static String process(int [] arr, int start, int end) {
return null;
}
Incorrect
SCP88920:
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.
At Line n1, arr infers to int[] type.
It is clear from Line n2 that, method name should be process, it should be static method, it should accept 3 parameters (int[], int, int) and its return type must be String. Hence below definition is correct:
private static String process(int [] arr, int start, int end) {
return null;
}
Unattempted
SCP88920:
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.
At Line n1, arr infers to int[] type.
It is clear from Line n2 that, method name should be process, it should be static method, it should accept 3 parameters (int[], int, int) and its return type must be String. Hence below definition is correct:
private static String process(int [] arr, int start, int end) {
return null;
}
Question 19 of 65
19. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String [] args) {
StringBuilder sb = new StringBuilder(“INHALE “);
String s = sb.toString() + (sb.append(“EXHALE “));
System.out.println(s.strip().length());
}
}
What will be the result of compiling and executing Test class?
Correct
SCP76996:
Initially sb refers to {“INHALE “}
Given Statement:
String s = sb.toString() + (sb.append(“EXHALE “));
String s = “INHALE ” + (sb.append(“EXHALE “)); //Left operand of + operator is evaluated first, sb –> {“INHALE “}
String s = “INHALE ” + {“INHALE EXHALE “}; //Right operand of + operator is evaluated next, sb –> {“INHALE EXHALE “}
String s = “INHALE ” + “INHALE EXHALE “; //As left operand is of String type, so + operator behaves as concatenation operator and that is why toString() method on right operand (which is StringBuilder object referred by ‘sb’) is invoked.
String s = “INHALE INHALE EXHALE “; //String object referred by ‘s’ has 21 characters.
strip() method of String class (available since Java 11) returns a string whose value is this string, with all leading and trailing white space removed.
To find out what is white space character in Java, check Character.isWhitespace?(int) method, you will find below:
A character is a Java whitespace character if and only if it satisfies one of the following criteria:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’).
It is ‘\t’, U+0009 HORIZONTAL TABULATION.
It is ‘\n’, U+000A LINE FEED.
It is ‘\u000B’, U+000B VERTICAL TABULATION.
It is ‘\f’, U+000C FORM FEED.
It is ‘\r’, U+000D CARRIAGE RETURN.
It is ‘\u001C’, U+001C FILE SEPARATOR.
It is ‘\u001D’, U+001D GROUP SEPARATOR.
It is ‘\u001E’, U+001E RECORD SEPARATOR.
It is ‘\u001F’, U+001F UNIT SEPARATOR.
White space character in java includes space character along with above characters.
As s refers to “INHALE INHALE EXHALE ” [contains 21 characters], hence s.strip() creates a new String object by trimming trailing space character: “INHALE INHALE EXHALE” [contains 20 characters].
Hence, `System.out.println(s.strip().length());` prints 20 on to the console.
Incorrect
SCP76996:
Initially sb refers to {“INHALE “}
Given Statement:
String s = sb.toString() + (sb.append(“EXHALE “));
String s = “INHALE ” + (sb.append(“EXHALE “)); //Left operand of + operator is evaluated first, sb –> {“INHALE “}
String s = “INHALE ” + {“INHALE EXHALE “}; //Right operand of + operator is evaluated next, sb –> {“INHALE EXHALE “}
String s = “INHALE ” + “INHALE EXHALE “; //As left operand is of String type, so + operator behaves as concatenation operator and that is why toString() method on right operand (which is StringBuilder object referred by ‘sb’) is invoked.
String s = “INHALE INHALE EXHALE “; //String object referred by ‘s’ has 21 characters.
strip() method of String class (available since Java 11) returns a string whose value is this string, with all leading and trailing white space removed.
To find out what is white space character in Java, check Character.isWhitespace?(int) method, you will find below:
A character is a Java whitespace character if and only if it satisfies one of the following criteria:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’).
It is ‘\t’, U+0009 HORIZONTAL TABULATION.
It is ‘\n’, U+000A LINE FEED.
It is ‘\u000B’, U+000B VERTICAL TABULATION.
It is ‘\f’, U+000C FORM FEED.
It is ‘\r’, U+000D CARRIAGE RETURN.
It is ‘\u001C’, U+001C FILE SEPARATOR.
It is ‘\u001D’, U+001D GROUP SEPARATOR.
It is ‘\u001E’, U+001E RECORD SEPARATOR.
It is ‘\u001F’, U+001F UNIT SEPARATOR.
White space character in java includes space character along with above characters.
As s refers to “INHALE INHALE EXHALE ” [contains 21 characters], hence s.strip() creates a new String object by trimming trailing space character: “INHALE INHALE EXHALE” [contains 20 characters].
Hence, `System.out.println(s.strip().length());` prints 20 on to the console.
Unattempted
SCP76996:
Initially sb refers to {“INHALE “}
Given Statement:
String s = sb.toString() + (sb.append(“EXHALE “));
String s = “INHALE ” + (sb.append(“EXHALE “)); //Left operand of + operator is evaluated first, sb –> {“INHALE “}
String s = “INHALE ” + {“INHALE EXHALE “}; //Right operand of + operator is evaluated next, sb –> {“INHALE EXHALE “}
String s = “INHALE ” + “INHALE EXHALE “; //As left operand is of String type, so + operator behaves as concatenation operator and that is why toString() method on right operand (which is StringBuilder object referred by ‘sb’) is invoked.
String s = “INHALE INHALE EXHALE “; //String object referred by ‘s’ has 21 characters.
strip() method of String class (available since Java 11) returns a string whose value is this string, with all leading and trailing white space removed.
To find out what is white space character in Java, check Character.isWhitespace?(int) method, you will find below:
A character is a Java whitespace character if and only if it satisfies one of the following criteria:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’).
It is ‘\t’, U+0009 HORIZONTAL TABULATION.
It is ‘\n’, U+000A LINE FEED.
It is ‘\u000B’, U+000B VERTICAL TABULATION.
It is ‘\f’, U+000C FORM FEED.
It is ‘\r’, U+000D CARRIAGE RETURN.
It is ‘\u001C’, U+001C FILE SEPARATOR.
It is ‘\u001D’, U+001D GROUP SEPARATOR.
It is ‘\u001E’, U+001E RECORD SEPARATOR.
It is ‘\u001F’, U+001F UNIT SEPARATOR.
White space character in java includes space character along with above characters.
As s refers to “INHALE INHALE EXHALE ” [contains 21 characters], hence s.strip() creates a new String object by trimming trailing space character: “INHALE INHALE EXHALE” [contains 20 characters].
Hence, `System.out.println(s.strip().length());` prints 20 on to the console.
Question 20 of 65
20. Question
Consider below code of Test.java file:
public class Test {
public static void main(String[] args) {
P p = new R(); //Line n1
System.out.println(p.compute(“Go”)); //Line n2
}
}
class P {
String compute(String str) {
return str.repeat(3);
}
}
class Q extends P {
String compute(String str) {
return super.compute(str.toLowerCase());
}
}
class R extends Q {
String compute(String str) {
return super.compute(str.replace(‘o’, ‘O’));
}
}
And the command:
java Test.java
What is the result?
Correct
SCP49326:
Class Q correctly overrides the compute(String) method of P class and class R correctly overrides the compute(String) method of Q class. Keyword super is used to invoke the method of parent class.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
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
Hence, in this case given command executes main(String []) method.
At Line n1, reference variable ‘p’ refers to an instance of class R, hence p.compute(“Go”) invokes the compute(String) method of R class.
return super.compute(str.replace(‘o’, ‘O’)); => return super.compute(“Go”.replace(‘o’, ‘O’)); => return super.compute(“GO”);
It invokes the compute(String) method of Parent class, which is Q.
=> return super.compute(str.toLowerCase()); => return super.compute(“GO”.toLowerCase()); => return super.compute(“go”);
It invokes the compute(String) method of Parent class, which is P.
=> return str.repeat(3); => return “go”.repeat(3); => return “gogogo”;
Control goes back to compute(String) method of Q and to the compute(String) method of R, which returns “gogogo”.
Line n2 prints gogogo on to the console.
Incorrect
SCP49326:
Class Q correctly overrides the compute(String) method of P class and class R correctly overrides the compute(String) method of Q class. Keyword super is used to invoke the method of parent class.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
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
Hence, in this case given command executes main(String []) method.
At Line n1, reference variable ‘p’ refers to an instance of class R, hence p.compute(“Go”) invokes the compute(String) method of R class.
return super.compute(str.replace(‘o’, ‘O’)); => return super.compute(“Go”.replace(‘o’, ‘O’)); => return super.compute(“GO”);
It invokes the compute(String) method of Parent class, which is Q.
=> return super.compute(str.toLowerCase()); => return super.compute(“GO”.toLowerCase()); => return super.compute(“go”);
It invokes the compute(String) method of Parent class, which is P.
=> return str.repeat(3); => return “go”.repeat(3); => return “gogogo”;
Control goes back to compute(String) method of Q and to the compute(String) method of R, which returns “gogogo”.
Line n2 prints gogogo on to the console.
Unattempted
SCP49326:
Class Q correctly overrides the compute(String) method of P class and class R correctly overrides the compute(String) method of Q class. Keyword super is used to invoke the method of parent class.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
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
Hence, in this case given command executes main(String []) method.
At Line n1, reference variable ‘p’ refers to an instance of class R, hence p.compute(“Go”) invokes the compute(String) method of R class.
return super.compute(str.replace(‘o’, ‘O’)); => return super.compute(“Go”.replace(‘o’, ‘O’)); => return super.compute(“GO”);
It invokes the compute(String) method of Parent class, which is Q.
=> return super.compute(str.toLowerCase()); => return super.compute(“GO”.toLowerCase()); => return super.compute(“go”);
It invokes the compute(String) method of Parent class, which is P.
=> return str.repeat(3); => return “go”.repeat(3); => return “gogogo”;
Control goes back to compute(String) method of Q and to the compute(String) method of R, which returns “gogogo”.
Line n2 prints gogogo on to the console.
Question 21 of 65
21. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
for:
for (int i = 2; i <= 100; i = i + 2) {
for(int j = 1; j <= 10; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
if(i == 10) {
break for;
}
}
}
}
What will be the result of compiling and executing Test class?
Correct
SCP71688:
for is a keyword and hence can’t be used as a label.
Java labels follow the identifier naming rules and one rule is that we can’t use java keywords as identifier. Hence, Compilation error.
Incorrect
SCP71688:
for is a keyword and hence can’t be used as a label.
Java labels follow the identifier naming rules and one rule is that we can’t use java keywords as identifier. Hence, Compilation error.
Unattempted
SCP71688:
for is a keyword and hence can’t be used as a label.
Java labels follow the identifier naming rules and one rule is that we can’t use java keywords as identifier. Hence, Compilation error.
Question 22 of 65
22. Question
Given code of Test.java file:
public class Test {
private static int [] arr;
public static void main(String [] args) {
if(arr.length > 0 && arr != null) {
System.out.println(arr[0]);
}
}
}
Predict Output, if the above code is run with given command?
Correct
SCP33728:
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
Variable arr is a class variable of int [] type, so by default it is initialized to null.
In if block, arr.length > 0 is checked first. Accessing length property on null reference throws NullPointerException.
Correct logical if block declaration should be:
if(arr != null && arr.length > 0)
First check for null and then access properties/methods.
Incorrect
SCP33728:
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
Variable arr is a class variable of int [] type, so by default it is initialized to null.
In if block, arr.length > 0 is checked first. Accessing length property on null reference throws NullPointerException.
Correct logical if block declaration should be:
if(arr != null && arr.length > 0)
First check for null and then access properties/methods.
Unattempted
SCP33728:
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
Variable arr is a class variable of int [] type, so by default it is initialized to null.
In if block, arr.length > 0 is checked first. Accessing length property on null reference throws NullPointerException.
Correct logical if block declaration should be:
if(arr != null && arr.length > 0)
First check for null and then access properties/methods.
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 var = 0; //Line n1
var: for (; var < 3; var++) { //Line n2
if (var % 2 == 0) {
continue var; //Line n3
}
var++; //Line n4
}
System.out.println(var);
}
}
Which of the following statements is true?
Correct
SCP61887:
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, variable ‘var’ infers to int type. Line n1 compiles successfully.
At Line n2, ‘var’ is used as for loop’s label, no issues at Line n2 as well.
At Line n3, continue is used with label. break and continue can be used with labels, so no issue at line n3 as well.
As var infers to int type, hence at Line n4, `var++;` is a valid statement.
Given code compiles successfully.
Incorrect
SCP61887:
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, variable ‘var’ infers to int type. Line n1 compiles successfully.
At Line n2, ‘var’ is used as for loop’s label, no issues at Line n2 as well.
At Line n3, continue is used with label. break and continue can be used with labels, so no issue at line n3 as well.
As var infers to int type, hence at Line n4, `var++;` is a valid statement.
Given code compiles successfully.
Unattempted
SCP61887:
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, variable ‘var’ infers to int type. Line n1 compiles successfully.
At Line n2, ‘var’ is used as for loop’s label, no issues at Line n2 as well.
At Line n3, continue is used with label. break and continue can be used with labels, so no issue at line n3 as well.
As var infers to int type, hence at Line n4, `var++;` is a valid statement.
Given code compiles successfully.
What will be the result of compiling and executing Test class?
Correct
SCP17018:
Lambda expression for Predicate is: s -> s.length() < 4. This means return true if passed string's length is < 4.Â
So first three array elements are printed.
Incorrect
SCP17018:
Lambda expression for Predicate is: s -> s.length() < 4. This means return true if passed string's length is < 4.Â
So first three array elements are printed.
Unattempted
SCP17018:
Lambda expression for Predicate is: s -> s.length() < 4. This means return true if passed string's length is < 4.Â
So first three array elements are printed.
Question 25 of 65
25. Question
You have below 3rd party modular jar:
C:\third-party\jars\conncetivity.jar
Module name is: com.db.connect
and it contains com.jdbc.utils.Connect class which contains main(String…) method.
Which of the following commands executed from C:\ will successfully execute the com.jdbc.utils.Connect class?
Correct
SCP52011:
Format of the java command related to module is:
java [options] -m [/] [args…]
java [options] –module [/] [args…]
   (to execute the main class in a module)
  Â
–module or -m: It corresponds to module name. -m should be the last option used in the command. -m is followed by module-name, then by optional mainclass and any command-line arguments. If module is packaged in the jar and ‘Main-Class’ attribute is set, then passing classname after -m is optional.
  Â
And below is the important option (related to modules) of java command:
–module-path or -p: It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries.
For example, java -p out;singlemodule;connector.jar represents a module path which contains all the modules inside ‘out’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
As given question doesn’t say anything about setting the ‘Main-Class’ attribute, hence class name must be passed after the module name in -m option.
Correct -m option will be: -m com.db.connect/com.jdbc.utils.Connect
Correct -p option will be: -p third-party\jars or -p third-party\jars\conncetivity.jar
Let’s check all the options one by one:
java -p third-party -m com.db.connect/com.jdbc.utils.Connect ? ‘-p third-party’ is not valid, it should be ‘-p third-party\jars’ or ‘-p third-party\jars\conncetivity.jar’.
java -p third-party\jars -m com.db.connect ? ‘-m com.db.connect’ is not valid, it should be ‘-m com.db.connect/com.jdbc.utils.Connect’.
java -p third-party\* -m com.db.connect/com.jdbc.utils.Connect ? ‘*’ is not allowed in -p option.
java -p third-party\jars\conncetivity.jar -m com.db.connect ? ‘-m com.db.connect’ is not valid, it should be ‘-m com.db.connect/com.jdbc.utils.Connect’.
java -p third-party\jars -m com.db.connect/com.jdbc.utils.Connect ? Both -p and -m options are correct.
java -m com.db.connect/com.jdbc.utils.Connect -p third-party\jars ? -m should be the last option.
Incorrect
SCP52011:
Format of the java command related to module is:
java [options] -m [/] [args…]
java [options] –module [/] [args…]
   (to execute the main class in a module)
  Â
–module or -m: It corresponds to module name. -m should be the last option used in the command. -m is followed by module-name, then by optional mainclass and any command-line arguments. If module is packaged in the jar and ‘Main-Class’ attribute is set, then passing classname after -m is optional.
  Â
And below is the important option (related to modules) of java command:
–module-path or -p: It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries.
For example, java -p out;singlemodule;connector.jar represents a module path which contains all the modules inside ‘out’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
As given question doesn’t say anything about setting the ‘Main-Class’ attribute, hence class name must be passed after the module name in -m option.
Correct -m option will be: -m com.db.connect/com.jdbc.utils.Connect
Correct -p option will be: -p third-party\jars or -p third-party\jars\conncetivity.jar
Let’s check all the options one by one:
java -p third-party -m com.db.connect/com.jdbc.utils.Connect ? ‘-p third-party’ is not valid, it should be ‘-p third-party\jars’ or ‘-p third-party\jars\conncetivity.jar’.
java -p third-party\jars -m com.db.connect ? ‘-m com.db.connect’ is not valid, it should be ‘-m com.db.connect/com.jdbc.utils.Connect’.
java -p third-party\* -m com.db.connect/com.jdbc.utils.Connect ? ‘*’ is not allowed in -p option.
java -p third-party\jars\conncetivity.jar -m com.db.connect ? ‘-m com.db.connect’ is not valid, it should be ‘-m com.db.connect/com.jdbc.utils.Connect’.
java -p third-party\jars -m com.db.connect/com.jdbc.utils.Connect ? Both -p and -m options are correct.
java -m com.db.connect/com.jdbc.utils.Connect -p third-party\jars ? -m should be the last option.
Unattempted
SCP52011:
Format of the java command related to module is:
java [options] -m [/] [args…]
java [options] –module [/] [args…]
   (to execute the main class in a module)
  Â
–module or -m: It corresponds to module name. -m should be the last option used in the command. -m is followed by module-name, then by optional mainclass and any command-line arguments. If module is packaged in the jar and ‘Main-Class’ attribute is set, then passing classname after -m is optional.
  Â
And below is the important option (related to modules) of java command:
–module-path or -p: It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries.
For example, java -p out;singlemodule;connector.jar represents a module path which contains all the modules inside ‘out’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
As given question doesn’t say anything about setting the ‘Main-Class’ attribute, hence class name must be passed after the module name in -m option.
Correct -m option will be: -m com.db.connect/com.jdbc.utils.Connect
Correct -p option will be: -p third-party\jars or -p third-party\jars\conncetivity.jar
Let’s check all the options one by one:
java -p third-party -m com.db.connect/com.jdbc.utils.Connect ? ‘-p third-party’ is not valid, it should be ‘-p third-party\jars’ or ‘-p third-party\jars\conncetivity.jar’.
java -p third-party\jars -m com.db.connect ? ‘-m com.db.connect’ is not valid, it should be ‘-m com.db.connect/com.jdbc.utils.Connect’.
java -p third-party\* -m com.db.connect/com.jdbc.utils.Connect ? ‘*’ is not allowed in -p option.
java -p third-party\jars\conncetivity.jar -m com.db.connect ? ‘-m com.db.connect’ is not valid, it should be ‘-m com.db.connect/com.jdbc.utils.Connect’.
java -p third-party\jars -m com.db.connect/com.jdbc.utils.Connect ? Both -p and -m options are correct.
java -m com.db.connect/com.jdbc.utils.Connect -p third-party\jars ? -m should be the last option.
Question 26 of 65
26. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
static var arr = new Boolean[1];
public static void main(String[] args) {
if(arr[0]) {
System.out.println(true);
} else {
System.out.println(false);
}
}
}
What will be the result of compiling and executing Test class?
Correct
SCP49796:
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
As the name suggests, Local variable Type inference is applicable only for local variables and not for instance or class variables. Hence, `static var arr = new Boolean[1];` causes compilation error.
Incorrect
SCP49796:
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
As the name suggests, Local variable Type inference is applicable only for local variables and not for instance or class variables. Hence, `static var arr = new Boolean[1];` causes compilation error.
Unattempted
SCP49796:
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
As the name suggests, Local variable Type inference is applicable only for local variables and not for instance or class variables. Hence, `static var arr = new Boolean[1];` causes compilation error.
class FilePrinter implements Printer {
public void print() { //Line n1
System.out.println(“FILE PRINTER”);
}
}
public class Test {
public static void main(String[] args) {
Printer p = new FilePrinter(); //Line n2
p.print(); //Line n3
var fp = new FilePrinter(); //Line n4
fp.print(); //Line n5
}
}
What will be the result of compiling and executing Test class?
Correct
SCP61185:
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 FilePrinter class correctly overrides the default method print() of Printer interface. Line n1 compiles successfully.
At Line n2, ‘p’ is of Printer type (supertype) and it refers to an instance of FilePrinter class (subtype), this is polymorphism and allowed in Java. Line n2 compiles successfully.
At Line n3, method print() is invoked on ‘p’ reference (Printer type) and as print() method defined in Printer interface declares to throw FileNotFoundException (checked exception). As main(String []) method doesn’t declare to throw FileNotFoundException and also there is not try-catch block available, therefore Line n3 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
At Line n4, ‘fp’ infers to FilePrinter type.
At Line n5, method print() is invoked on ‘fp’ reference (FilePrinter type) and as print() method defined in FilePrinter class doesn’t declare to throw any checked exception, hence Line n5 compiles successfully.
Only Line n3 causes compilation failure.
Incorrect
SCP61185:
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 FilePrinter class correctly overrides the default method print() of Printer interface. Line n1 compiles successfully.
At Line n2, ‘p’ is of Printer type (supertype) and it refers to an instance of FilePrinter class (subtype), this is polymorphism and allowed in Java. Line n2 compiles successfully.
At Line n3, method print() is invoked on ‘p’ reference (Printer type) and as print() method defined in Printer interface declares to throw FileNotFoundException (checked exception). As main(String []) method doesn’t declare to throw FileNotFoundException and also there is not try-catch block available, therefore Line n3 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
At Line n4, ‘fp’ infers to FilePrinter type.
At Line n5, method print() is invoked on ‘fp’ reference (FilePrinter type) and as print() method defined in FilePrinter class doesn’t declare to throw any checked exception, hence Line n5 compiles successfully.
Only Line n3 causes compilation failure.
Unattempted
SCP61185:
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 FilePrinter class correctly overrides the default method print() of Printer interface. Line n1 compiles successfully.
At Line n2, ‘p’ is of Printer type (supertype) and it refers to an instance of FilePrinter class (subtype), this is polymorphism and allowed in Java. Line n2 compiles successfully.
At Line n3, method print() is invoked on ‘p’ reference (Printer type) and as print() method defined in Printer interface declares to throw FileNotFoundException (checked exception). As main(String []) method doesn’t declare to throw FileNotFoundException and also there is not try-catch block available, therefore Line n3 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
At Line n4, ‘fp’ infers to FilePrinter type.
At Line n5, method print() is invoked on ‘fp’ reference (FilePrinter type) and as print() method defined in FilePrinter class doesn’t declare to throw any checked exception, hence Line n5 compiles successfully.
Only Line n3 causes compilation failure.
Question 28 of 65
28. Question
Consider the code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
private static void m(int i) {
System.out.print(1);
}
private static void m(int i1, int i2) {
System.out.print(2);
}
What will be the result of compiling and executing Test class?
Correct
SCP54924:
If choice is between implicit casting and variable arguments, then implicit casting takes precedence because variable arguments syntax was added in Java 5 version.
m(‘A’); is tagged to m(int) as ‘A’ is char literal and implicitly casted to int.
m(‘A’, ‘B’); is tagged to m(int, int) as ‘A’ and ‘B’ are char literals and implicitly casted to int.
m(‘A’, ‘B’, ‘C’); is tagged to m(char…)
m(‘A’, ‘B’, ‘C’, ‘D’); is tagged to m(char…)
There is no compilation error and on execution output is: 1233
Incorrect
SCP54924:
If choice is between implicit casting and variable arguments, then implicit casting takes precedence because variable arguments syntax was added in Java 5 version.
m(‘A’); is tagged to m(int) as ‘A’ is char literal and implicitly casted to int.
m(‘A’, ‘B’); is tagged to m(int, int) as ‘A’ and ‘B’ are char literals and implicitly casted to int.
m(‘A’, ‘B’, ‘C’); is tagged to m(char…)
m(‘A’, ‘B’, ‘C’, ‘D’); is tagged to m(char…)
There is no compilation error and on execution output is: 1233
Unattempted
SCP54924:
If choice is between implicit casting and variable arguments, then implicit casting takes precedence because variable arguments syntax was added in Java 5 version.
m(‘A’); is tagged to m(int) as ‘A’ is char literal and implicitly casted to int.
m(‘A’, ‘B’); is tagged to m(int, int) as ‘A’ and ‘B’ are char literals and implicitly casted to int.
m(‘A’, ‘B’, ‘C’); is tagged to m(char…)
m(‘A’, ‘B’, ‘C’, ‘D’); is tagged to m(char…)
There is no compilation error and on execution output is: 1233
Question 29 of 65
29. Question
Below are the possible definitions of Printable interface:
1
public abstract interface Printable {}
2
public interface Printable {
protected void print();
}
3
public interface Printable {
int i;
void print();
}
4
public interface Printable {
void print();
default void log() {
}
private default void log1() {
}
private static void log2() {
}
static int getNumLogs() {
return -1;
}
}
5
@MarkerInterface
public interface Printable {}
6
public interface Printable {
public static final int x = 10;
public final int y = 20;
int z = 30;
}
How many definitions are valid?
Correct
SCP17076:
public abstract interface Printable {}: ?
Valid, as interface in java is implicitly abstract, so using abstract keyword doesn’t cause any error.
public interface Printable {
  protected void print();
}: ?
abstract method of the interface are implicitly public and if you provide access modifier for the abstract method of the interface, then only ‘public’ is allowed. As ‘protected’ is used for print() method, hence it causes compilation error.
public interface Printable {
  int i;
  void print();
}: ?
Variables declared inside interface are implicitly public, static and final and therefore compiler complains about un-initialized final variable i.
public interface Printable {
  void print();
  default void log() {
  }
  private default void log1() {
  }
 Â
  private static void log2() {
  }
  static int getNumLogs() {
    return -1;
  }
}: ?
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.
default modifier is not allowed with private method of the interface, hence method log1() causes compilation error. Methods print(), log(), log2() and getNumLogs() compile successfully.
@MarkerInterface
public interface Printable {}: ?
@MarkerInterface annotation is not available in Java and hence it causes compilation error.
public interface Printable {
  public static final int x = 10;
  public final int y = 20;
  int z = 30;
}: ?
Interfaces can define public, static and final variables and these modifiers are implicit.
Hence, for ‘y’ compiler adds static modifier and for ‘z’ compiler adds public, static and final modifiers.
Therefore, only 2 interface definitions are valid.
Incorrect
SCP17076:
public abstract interface Printable {}: ?
Valid, as interface in java is implicitly abstract, so using abstract keyword doesn’t cause any error.
public interface Printable {
  protected void print();
}: ?
abstract method of the interface are implicitly public and if you provide access modifier for the abstract method of the interface, then only ‘public’ is allowed. As ‘protected’ is used for print() method, hence it causes compilation error.
public interface Printable {
  int i;
  void print();
}: ?
Variables declared inside interface are implicitly public, static and final and therefore compiler complains about un-initialized final variable i.
public interface Printable {
  void print();
  default void log() {
  }
  private default void log1() {
  }
 Â
  private static void log2() {
  }
  static int getNumLogs() {
    return -1;
  }
}: ?
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.
default modifier is not allowed with private method of the interface, hence method log1() causes compilation error. Methods print(), log(), log2() and getNumLogs() compile successfully.
@MarkerInterface
public interface Printable {}: ?
@MarkerInterface annotation is not available in Java and hence it causes compilation error.
public interface Printable {
  public static final int x = 10;
  public final int y = 20;
  int z = 30;
}: ?
Interfaces can define public, static and final variables and these modifiers are implicit.
Hence, for ‘y’ compiler adds static modifier and for ‘z’ compiler adds public, static and final modifiers.
Therefore, only 2 interface definitions are valid.
Unattempted
SCP17076:
public abstract interface Printable {}: ?
Valid, as interface in java is implicitly abstract, so using abstract keyword doesn’t cause any error.
public interface Printable {
  protected void print();
}: ?
abstract method of the interface are implicitly public and if you provide access modifier for the abstract method of the interface, then only ‘public’ is allowed. As ‘protected’ is used for print() method, hence it causes compilation error.
public interface Printable {
  int i;
  void print();
}: ?
Variables declared inside interface are implicitly public, static and final and therefore compiler complains about un-initialized final variable i.
public interface Printable {
  void print();
  default void log() {
  }
  private default void log1() {
  }
 Â
  private static void log2() {
  }
  static int getNumLogs() {
    return -1;
  }
}: ?
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.
default modifier is not allowed with private method of the interface, hence method log1() causes compilation error. Methods print(), log(), log2() and getNumLogs() compile successfully.
@MarkerInterface
public interface Printable {}: ?
@MarkerInterface annotation is not available in Java and hence it causes compilation error.
public interface Printable {
  public static final int x = 10;
  public final int y = 20;
  int z = 30;
}: ?
Interfaces can define public, static and final variables and these modifiers are implicit.
Hence, for ‘y’ compiler adds static modifier and for ‘z’ compiler adds public, static and final modifiers.
Therefore, only 2 interface definitions are valid.
Question 30 of 65
30. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
import java.io.IOException;
class Parent {
Parent() throws IOException {
System.out.print(“HAKUNA”);
}
}
public class Test {
public static void main(String[] args) throws Exception {
new Child();
}
}
What will be the result of compiling and executing Test class?
Correct
SCP39288:
It is legal for the constructors to have throws clause.
Constructors are not inherited by the Child class so there is no method overriding rules related to the constructors but as one constructor invokes other constructors implicitly or explicitly by using this(…) or super(…), hence exception handling becomes interesting.
Java compiler adds super(); as the first statement inside Child class’s constructor:
Child() throws Exception {
super(); //added by the compiler
System.out.println(“MATATA”);
}
super(); invokes the constructor of Parent class (which declares to throw IOException), but as no-argument constructor of Child class declares to throw Exception (super class of IOException), hence IOException is also handled. There is no compilation error and output is: HAKUNAMATATA
Incorrect
SCP39288:
It is legal for the constructors to have throws clause.
Constructors are not inherited by the Child class so there is no method overriding rules related to the constructors but as one constructor invokes other constructors implicitly or explicitly by using this(…) or super(…), hence exception handling becomes interesting.
Java compiler adds super(); as the first statement inside Child class’s constructor:
Child() throws Exception {
super(); //added by the compiler
System.out.println(“MATATA”);
}
super(); invokes the constructor of Parent class (which declares to throw IOException), but as no-argument constructor of Child class declares to throw Exception (super class of IOException), hence IOException is also handled. There is no compilation error and output is: HAKUNAMATATA
Unattempted
SCP39288:
It is legal for the constructors to have throws clause.
Constructors are not inherited by the Child class so there is no method overriding rules related to the constructors but as one constructor invokes other constructors implicitly or explicitly by using this(…) or super(…), hence exception handling becomes interesting.
Java compiler adds super(); as the first statement inside Child class’s constructor:
Child() throws Exception {
super(); //added by the compiler
System.out.println(“MATATA”);
}
super(); invokes the constructor of Parent class (which declares to throw IOException), but as no-argument constructor of Child class declares to throw Exception (super class of IOException), hence IOException is also handled. There is no compilation error and output is: HAKUNAMATATA
public class Test {
public static void main(String[] args) {
List gemStones = new ArrayList<>();
gemStones.add(new StringBuilder(“Sapphire”));
gemStones.add(new StringBuilder(“Emerald”));
gemStones.add(new StringBuilder(“Ruby”));
What will be the result of compiling and executing Test class?
Correct
SCP58873:
Three StringBuilder objects [{“Sapphire”}, {“Emerald”}, {“Ruby”}] are added to the gemStones list.
StringBuilder class doesn’t override equals(Object) method and hence `days.contains(new StringBuilder(“Sapphire”))` returns false. Code inside if-block is not executed and days.size() returns 3.
Incorrect
SCP58873:
Three StringBuilder objects [{“Sapphire”}, {“Emerald”}, {“Ruby”}] are added to the gemStones list.
StringBuilder class doesn’t override equals(Object) method and hence `days.contains(new StringBuilder(“Sapphire”))` returns false. Code inside if-block is not executed and days.size() returns 3.
Unattempted
SCP58873:
Three StringBuilder objects [{“Sapphire”}, {“Emerald”}, {“Ruby”}] are added to the gemStones list.
StringBuilder class doesn’t override equals(Object) method and hence `days.contains(new StringBuilder(“Sapphire”))` returns false. Code inside if-block is not executed and days.size() returns 3.
Question 32 of 65
32. Question
Consider below code of University.java file:
package com.udayankhattry.ocp1;
public class Teacher {
public static void main(String [] args) {
System.out.println(“Teacher”);
}
}
public class Student {
public static void main(String [] args) {
System.out.println(“Student”);
}
}
And the command:
java University.java
What is the result?
Correct
SCP50572:
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 University.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java University.java` is equivalent to (but not exactly same as):
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 [])’.
SCP50572:
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 University.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java University.java` is equivalent to (but not exactly same as):
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 [])’.
SCP50572:
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 University.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java University.java` is equivalent to (but not exactly same as):
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) {
System.out.println(“String”);
}
public static void main(Integer [] args) {
System.out.println(“Integer”);
}
public static void main(byte [] args) {
System.out.println(“byte”);
}
}
And the commands:
javac Test.java
java Test 10
What is the result?
Correct
SCP29993:
Like any other method, main method can also be overloaded. But main method called by JVM is always with String [] parameter. Don’t get confused with 10 as it is passed as “10”.
Execute above class with any command line arguments or 0 command line argument, output will always be “String”.
Incorrect
SCP29993:
Like any other method, main method can also be overloaded. But main method called by JVM is always with String [] parameter. Don’t get confused with 10 as it is passed as “10”.
Execute above class with any command line arguments or 0 command line argument, output will always be “String”.
Unattempted
SCP29993:
Like any other method, main method can also be overloaded. But main method called by JVM is always with String [] parameter. Don’t get confused with 10 as it is passed as “10”.
Execute above class with any command line arguments or 0 command line argument, output will always be “String”.
Question 34 of 65
34. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
int grade = 85;
if(grade >= 60)
System.out.println(“Congratulations”);
System.out.println(“You passed”);
else
System.out.println(“You failed”);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP86329:
As there is no brackets after if, hence only one statement is part of if block and other is outside.
Above code can be written as below:
if(grade >= 60) {
System.out.println(“Congratulations”);
}
System.out.println(“You passed”);
else
System.out.println(“You failed”);
 Â
There should not be anything in between if-else block but in this case, System.out.println(“You passed”); is in between if-else and thus Compilation error.
Incorrect
SCP86329:
As there is no brackets after if, hence only one statement is part of if block and other is outside.
Above code can be written as below:
if(grade >= 60) {
System.out.println(“Congratulations”);
}
System.out.println(“You passed”);
else
System.out.println(“You failed”);
 Â
There should not be anything in between if-else block but in this case, System.out.println(“You passed”); is in between if-else and thus Compilation error.
Unattempted
SCP86329:
As there is no brackets after if, hence only one statement is part of if block and other is outside.
Above code can be written as below:
if(grade >= 60) {
System.out.println(“Congratulations”);
}
System.out.println(“You passed”);
else
System.out.println(“You failed”);
 Â
There should not be anything in between if-else block but in this case, System.out.println(“You passed”); is in between if-else and thus Compilation error.
Question 35 of 65
35. Question
Given code of Sport.java file:
package com.udayankhattry.ocp1;
public class Sport {
String name = “”;
}
And below definitions:
1
public String Sport() {
return name;
}
2
public void Sport(String name) {
this.name = name;
}
3
public void Sport(String… sports) {
name = String.join(“,”, sports);
}
4
public Sport() {
name = “”;
}
5
public Sport(String name) {
this.name = name;
}
6
public Sport(String name1, String name2) {
name = String.join(“,”, name1, name2);
}
How many of the given definitions can be added to Sport class, such that there are no compilation errors?
Correct
SCP10919:
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.
As compiler is aware that given infinite loop has an exit point, hence it doesn’t mark Line n2 as unreachable. Line n2 doesn’t cause any compilation error as well.
There is no compilation error for 3rd and 6th statements as syntax of calling join(…) method is correct.
In java it is allowed to use same method name as the class name (though not a recommended practice), hence 1st, 2nd and 3rd statements represent overloaded ‘Sport’ methods.
4th, 5th and 6th statements represent overloaded constructors as no return type is specified.
All 6 statements can be inserted in Sport class.
Incorrect
SCP10919:
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.
As compiler is aware that given infinite loop has an exit point, hence it doesn’t mark Line n2 as unreachable. Line n2 doesn’t cause any compilation error as well.
There is no compilation error for 3rd and 6th statements as syntax of calling join(…) method is correct.
In java it is allowed to use same method name as the class name (though not a recommended practice), hence 1st, 2nd and 3rd statements represent overloaded ‘Sport’ methods.
4th, 5th and 6th statements represent overloaded constructors as no return type is specified.
All 6 statements can be inserted in Sport class.
Unattempted
SCP10919:
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.
As compiler is aware that given infinite loop has an exit point, hence it doesn’t mark Line n2 as unreachable. Line n2 doesn’t cause any compilation error as well.
There is no compilation error for 3rd and 6th statements as syntax of calling join(…) method is correct.
In java it is allowed to use same method name as the class name (though not a recommended practice), hence 1st, 2nd and 3rd statements represent overloaded ‘Sport’ methods.
4th, 5th and 6th statements represent overloaded constructors as no return type is specified.
All 6 statements can be inserted in Sport class.
Question 36 of 65
36. Question
Consider below code of Test.java file:
//Test.java
package com.udayankhattry.ocp1;
class Parent {
int i = 10;
Parent(int i) {
super();
this.i = i;
}
}
class Child extends Parent {
int j = 20;
Child(int j) {
super(0);
this.j = j;
}
Child(int i, int j) {
super(i);
this(j);
}
}
public class Test {
public static void main(String[] args) {
Child child = new Child(1000, 2000);
System.out.println(child.i + “:” + child.j);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP79183:
super(); inside Parent(int) constructor invokes the no-argument constructor of Object class and hence no compilation error in Parent(int) constructor.Â
super(0); inside Child(int) constructor invokes Parent(int) constructor, which is available and hence no issues.Â
Child(int, int) constructor has both super(i) and this(j) statements. A constructor should have super(…) or this(…) but not both. Hence Child(int, int) causes compilation failure.
As all the classes are defined in Test.java file under ‘com.udayankhattry.ocp1’ package, hence child.i and child.j don’t cause compilation error. i and j are declared with package scope.
Incorrect
SCP79183:
super(); inside Parent(int) constructor invokes the no-argument constructor of Object class and hence no compilation error in Parent(int) constructor.Â
super(0); inside Child(int) constructor invokes Parent(int) constructor, which is available and hence no issues.Â
Child(int, int) constructor has both super(i) and this(j) statements. A constructor should have super(…) or this(…) but not both. Hence Child(int, int) causes compilation failure.
As all the classes are defined in Test.java file under ‘com.udayankhattry.ocp1’ package, hence child.i and child.j don’t cause compilation error. i and j are declared with package scope.
Unattempted
SCP79183:
super(); inside Parent(int) constructor invokes the no-argument constructor of Object class and hence no compilation error in Parent(int) constructor.Â
super(0); inside Child(int) constructor invokes Parent(int) constructor, which is available and hence no issues.Â
Child(int, int) constructor has both super(i) and this(j) statements. A constructor should have super(…) or this(…) but not both. Hence Child(int, int) causes compilation failure.
As all the classes are defined in Test.java file under ‘com.udayankhattry.ocp1’ package, hence child.i and child.j don’t cause compilation error. i and j are declared with package scope.
Question 37 of 65
37. Question
Consider below code of Test.java file:
class Super {
Super(int i) {
System.out.println(100);
}
}
class Sub extends Super {
Sub() {
System.out.println(200);
}
}
public class Test {
public static void main(String[] args) {
new Sub();
}
}
What will be the result of compiling and executing above code?
Correct
SCP54928:
super(); is added by the compiler as the first statement in both the constructors:
Super(int i) {
super();
System.out.println(100);
}
and
Sub() {
super();
System.out.println(200);
}
Class Super extends from Object class and Object class has no-argument constructor, hence no issues with the constructor of Super class.
But no-argument constructor is not available in Super class, hence calling super(); from Sub class’s constructor causes compilation error.
Incorrect
SCP54928:
super(); is added by the compiler as the first statement in both the constructors:
Super(int i) {
super();
System.out.println(100);
}
and
Sub() {
super();
System.out.println(200);
}
Class Super extends from Object class and Object class has no-argument constructor, hence no issues with the constructor of Super class.
But no-argument constructor is not available in Super class, hence calling super(); from Sub class’s constructor causes compilation error.
Unattempted
SCP54928:
super(); is added by the compiler as the first statement in both the constructors:
Super(int i) {
super();
System.out.println(100);
}
and
Sub() {
super();
System.out.println(200);
}
Class Super extends from Object class and Object class has no-argument constructor, hence no issues with the constructor of Super class.
But no-argument constructor is not available in Super class, hence calling super(); from Sub class’s constructor causes compilation error.
What will be the result of compiling and executing Test class?
Correct
SCP88085:
This is bit tricky. Just remember this:
Two instances of following wrapper objects, created through auto-boxing will always be same, if their primitive values are same:
Boolean,
Byte,
Character from \u0000 to \u007f (7f equals to 127),
Short and Integer from -128 to 127.Â
For 1st statement, list.add(27); => Auto-boxing creates an integer object for 27.Â
For 2nd statement, list.add(27); => Java compiler finds that there is already an Integer object in the memory with value 27, so it uses the same object.
That is why `System.out.println(list.get(0) == list.get(1));` returns true.Â
For 3rd statement, list.add(227); => Auto-boxing creates an integer object for 227.
For 4th statement, list.add(227); => As 227 is greater than 127, hence auto-boxing creates another integer object for 227.
As both the objects are created at different memory locations, hence `System.out.println(list.get(2) == list.get(3));` returns false.
Incorrect
SCP88085:
This is bit tricky. Just remember this:
Two instances of following wrapper objects, created through auto-boxing will always be same, if their primitive values are same:
Boolean,
Byte,
Character from \u0000 to \u007f (7f equals to 127),
Short and Integer from -128 to 127.Â
For 1st statement, list.add(27); => Auto-boxing creates an integer object for 27.Â
For 2nd statement, list.add(27); => Java compiler finds that there is already an Integer object in the memory with value 27, so it uses the same object.
That is why `System.out.println(list.get(0) == list.get(1));` returns true.Â
For 3rd statement, list.add(227); => Auto-boxing creates an integer object for 227.
For 4th statement, list.add(227); => As 227 is greater than 127, hence auto-boxing creates another integer object for 227.
As both the objects are created at different memory locations, hence `System.out.println(list.get(2) == list.get(3));` returns false.
Unattempted
SCP88085:
This is bit tricky. Just remember this:
Two instances of following wrapper objects, created through auto-boxing will always be same, if their primitive values are same:
Boolean,
Byte,
Character from \u0000 to \u007f (7f equals to 127),
Short and Integer from -128 to 127.Â
For 1st statement, list.add(27); => Auto-boxing creates an integer object for 27.Â
For 2nd statement, list.add(27); => Java compiler finds that there is already an Integer object in the memory with value 27, so it uses the same object.
That is why `System.out.println(list.get(0) == list.get(1));` returns true.Â
For 3rd statement, list.add(227); => Auto-boxing creates an integer object for 227.
For 4th statement, list.add(227); => As 227 is greater than 127, hence auto-boxing creates another integer object for 227.
As both the objects are created at different memory locations, hence `System.out.println(list.get(2) == list.get(3));` returns false.
Question 39 of 65
39. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String… args) {
System.out.println(“Java 11 is awesome!!!”);
}
}
Which of the following java commands will print ‘Java 11 is awesome!!!’ on to the console?
Correct
SCP47169:
To execute Test class, you should specify the -classpath or -cp option with java command, to specify the search path for Test class. This search path should contain whole path of the Test class(com\udayankhattry\ocp1\Test.class).
In this case, the search path is ‘F:\codes\classes\’ but as command is executed from ‘F:\codes\’ directory, hence relative path should be ‘classes\’.
And you should also use fully qualified name of the class, which is com.udayankhattry.ocp1.Test.
Hence, correct command to executed Test class is: java -cp classes\ com.udayankhattry.ocp1.Test
Incorrect
SCP47169:
To execute Test class, you should specify the -classpath or -cp option with java command, to specify the search path for Test class. This search path should contain whole path of the Test class(com\udayankhattry\ocp1\Test.class).
In this case, the search path is ‘F:\codes\classes\’ but as command is executed from ‘F:\codes\’ directory, hence relative path should be ‘classes\’.
And you should also use fully qualified name of the class, which is com.udayankhattry.ocp1.Test.
Hence, correct command to executed Test class is: java -cp classes\ com.udayankhattry.ocp1.Test
Unattempted
SCP47169:
To execute Test class, you should specify the -classpath or -cp option with java command, to specify the search path for Test class. This search path should contain whole path of the Test class(com\udayankhattry\ocp1\Test.class).
In this case, the search path is ‘F:\codes\classes\’ but as command is executed from ‘F:\codes\’ directory, hence relative path should be ‘classes\’.
And you should also use fully qualified name of the class, which is com.udayankhattry.ocp1.Test.
Hence, correct command to executed Test class is: java -cp classes\ com.udayankhattry.ocp1.Test
Question 40 of 65
40. Question
Given below the directory/file structure on Windows platform:
C:
+—src
| \—com.udayan.test
| module-info.java
| Test.java
|
\—cls
Below is the code of module-info.java file:
module com.udayan.test {
}
and below is the code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String… args) {
System.out.println(“HEALTH IS WEALTH”);
}
}
And below command executed from C:\
javac -d cls –module-source-path src –module com.udayan.test
What will be the full path of generated Test.class file?
Correct
SCP33759:
Test class is defined under ‘com.udayankhattry.ocp1’. Though it is the best practice to keep the source code files under package directory structure, e.g. ‘C:\src\com.udayan.test\com\udayankhattry\ocp1\Test.java’ is the logical path for Test.java file but it can legally be placed at any path. Hence, ‘C:\src\com.udayan.test\Test.java’ is also allowed.
Please note that generated class files must be under proper directory structure.
Format of javac command is:
javacBelow are the important options (related to modules) of javac command:
–module-source-path :
Specify where to find input source files for multiple modules. In this case, module source path is ‘src’ directory.
–module , -m :
Compile only the specified module. This will compile all *.java file specified in the module. Multiple module names are separated by comma.
-d :
Specify where to place generated class files. In this case, it is ‘cls’ directory. Please note generated class files will be arranged in package-wise directory structure.
–module-path , -p :
Specify where to find compiled/packaged application modules. It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries. For example, javac -p mods;singlemodule;connector.jar represents a module path which contains all the modules inside ‘mods’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
It is not used in this case as given module is not dependent upon other compiled/packaged application modules.
Given command will first create the module-directory ‘com.udayan.test’ based on the module name specified in module-info.java file and will create the structure ‘com\udayankhattry\ocp1\Test.class’ (based on package statement in Test.java file) under ‘com.udayan.test’ directory.
Hence, correct option is: C:\cls\com.udayan.test\com\udayankhattry\ocp1\Test.class
Incorrect
SCP33759:
Test class is defined under ‘com.udayankhattry.ocp1’. Though it is the best practice to keep the source code files under package directory structure, e.g. ‘C:\src\com.udayan.test\com\udayankhattry\ocp1\Test.java’ is the logical path for Test.java file but it can legally be placed at any path. Hence, ‘C:\src\com.udayan.test\Test.java’ is also allowed.
Please note that generated class files must be under proper directory structure.
Format of javac command is:
javacBelow are the important options (related to modules) of javac command:
–module-source-path :
Specify where to find input source files for multiple modules. In this case, module source path is ‘src’ directory.
–module , -m :
Compile only the specified module. This will compile all *.java file specified in the module. Multiple module names are separated by comma.
-d :
Specify where to place generated class files. In this case, it is ‘cls’ directory. Please note generated class files will be arranged in package-wise directory structure.
–module-path , -p :
Specify where to find compiled/packaged application modules. It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries. For example, javac -p mods;singlemodule;connector.jar represents a module path which contains all the modules inside ‘mods’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
It is not used in this case as given module is not dependent upon other compiled/packaged application modules.
Given command will first create the module-directory ‘com.udayan.test’ based on the module name specified in module-info.java file and will create the structure ‘com\udayankhattry\ocp1\Test.class’ (based on package statement in Test.java file) under ‘com.udayan.test’ directory.
Hence, correct option is: C:\cls\com.udayan.test\com\udayankhattry\ocp1\Test.class
Unattempted
SCP33759:
Test class is defined under ‘com.udayankhattry.ocp1’. Though it is the best practice to keep the source code files under package directory structure, e.g. ‘C:\src\com.udayan.test\com\udayankhattry\ocp1\Test.java’ is the logical path for Test.java file but it can legally be placed at any path. Hence, ‘C:\src\com.udayan.test\Test.java’ is also allowed.
Please note that generated class files must be under proper directory structure.
Format of javac command is:
javacBelow are the important options (related to modules) of javac command:
–module-source-path :
Specify where to find input source files for multiple modules. In this case, module source path is ‘src’ directory.
–module , -m :
Compile only the specified module. This will compile all *.java file specified in the module. Multiple module names are separated by comma.
-d :
Specify where to place generated class files. In this case, it is ‘cls’ directory. Please note generated class files will be arranged in package-wise directory structure.
–module-path , -p :
Specify where to find compiled/packaged application modules. It represents the list of directories containing modules or paths to individual modules. A platform dependent path separator (; on Windows and : on Linux/Mac) is used for multiple entries. For example, javac -p mods;singlemodule;connector.jar represents a module path which contains all the modules inside ‘mods’ directory, exploded module ‘singlemodule’ and modular jar ‘connector.jar’.
It is not used in this case as given module is not dependent upon other compiled/packaged application modules.
Given command will first create the module-directory ‘com.udayan.test’ based on the module name specified in module-info.java file and will create the structure ‘com\udayankhattry\ocp1\Test.class’ (based on package statement in Test.java file) under ‘com.udayan.test’ directory.
Hence, correct option is: C:\cls\com.udayan.test\com\udayankhattry\ocp1\Test.class
Question 41 of 65
41. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
/*INSERT*/
arr[0] = 5;
arr[1] = 10;
System.out.println(“[” + arr[0] + “, ” + arr[1] + “]”);
}
}
For the class Test, which options, if used to replace /*INSERT*/, will print [5, 10] on to the console? Select 3 options.
Correct
SCP62953:
You can declare one-dimensional array either by using `short arr []` or `short [] arr`.
You can either create and assign array object in the same statement or two statements. `short arr [] = new short[2];` and `short [] arr; arr = new short[2];` both are correct.Â
Array size cannot be specified at the time of declaration, so `short [2] arr;` causes compilation error.Â
`short [] arr = {};` => arr refers to a short array object of 0 size. so arr[0] = 5; and arr[1] = 10; will throw ArrayIndexOutOfBoundsException at runtime.Â
`short [] arr = new short[]{100, 100};` => arr refers to a short array object of size 2 and both array elements have value 100. arr[0] = 5; replaces 1st element value with 5 and arr[1] = 10; replaces 2nd element value with 10. So this is also a correct option.Â
`short [] arr = new short[2]{100, 100};` => Array’s size can’t be specified, if you use {} to assign values to array elements. Hence, this statement causes compilation error.
Incorrect
SCP62953:
You can declare one-dimensional array either by using `short arr []` or `short [] arr`.
You can either create and assign array object in the same statement or two statements. `short arr [] = new short[2];` and `short [] arr; arr = new short[2];` both are correct.Â
Array size cannot be specified at the time of declaration, so `short [2] arr;` causes compilation error.Â
`short [] arr = {};` => arr refers to a short array object of 0 size. so arr[0] = 5; and arr[1] = 10; will throw ArrayIndexOutOfBoundsException at runtime.Â
`short [] arr = new short[]{100, 100};` => arr refers to a short array object of size 2 and both array elements have value 100. arr[0] = 5; replaces 1st element value with 5 and arr[1] = 10; replaces 2nd element value with 10. So this is also a correct option.Â
`short [] arr = new short[2]{100, 100};` => Array’s size can’t be specified, if you use {} to assign values to array elements. Hence, this statement causes compilation error.
Unattempted
SCP62953:
You can declare one-dimensional array either by using `short arr []` or `short [] arr`.
You can either create and assign array object in the same statement or two statements. `short arr [] = new short[2];` and `short [] arr; arr = new short[2];` both are correct.Â
Array size cannot be specified at the time of declaration, so `short [2] arr;` causes compilation error.Â
`short [] arr = {};` => arr refers to a short array object of 0 size. so arr[0] = 5; and arr[1] = 10; will throw ArrayIndexOutOfBoundsException at runtime.Â
`short [] arr = new short[]{100, 100};` => arr refers to a short array object of size 2 and both array elements have value 100. arr[0] = 5; replaces 1st element value with 5 and arr[1] = 10; replaces 2nd element value with 10. So this is also a correct option.Â
`short [] arr = new short[2]{100, 100};` => Array’s size can’t be specified, if you use {} to assign values to array elements. Hence, this statement causes compilation error.
Question 42 of 65
42. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
import java.sql.SQLException;
public class Test {
private static void checkData() throws SQLException {
try {
throw new SQLException();
} catch (Exception e) {
e = null; //Line 10
throw e; //Line 11
}
}
What will be the result of compiling and executing Test class?
Correct
SCP32644:
Exception is a java class, so `e = null;` is a valid statement and compiles successfully.
If you comment Line 10, and simply throw e, then code would compile successfully as compiler is certain that ‘e’ would refer to an instance of SQLException only.
But the moment compiler finds `e = null;`, `throw e;` (Line 11) causes compilation error as at runtime ‘e’ may refer to any Exception type.
NOTE: No issues with Line 17 as method checkData() declares to throw SQLException and main(String []) method code correctly handles it.
Incorrect
SCP32644:
Exception is a java class, so `e = null;` is a valid statement and compiles successfully.
If you comment Line 10, and simply throw e, then code would compile successfully as compiler is certain that ‘e’ would refer to an instance of SQLException only.
But the moment compiler finds `e = null;`, `throw e;` (Line 11) causes compilation error as at runtime ‘e’ may refer to any Exception type.
NOTE: No issues with Line 17 as method checkData() declares to throw SQLException and main(String []) method code correctly handles it.
Unattempted
SCP32644:
Exception is a java class, so `e = null;` is a valid statement and compiles successfully.
If you comment Line 10, and simply throw e, then code would compile successfully as compiler is certain that ‘e’ would refer to an instance of SQLException only.
But the moment compiler finds `e = null;`, `throw e;` (Line 11) causes compilation error as at runtime ‘e’ may refer to any Exception type.
NOTE: No issues with Line 17 as method checkData() declares to throw SQLException and main(String []) method code correctly handles it.
Question 43 of 65
43. Question
How can you force JVM to run Garbage Collector?
Correct
SCP71000:
Both Runtime.getRuntime().gc(); and System.gc(); do the same thing, these make a request to JVM to run Garbage Collector.
JVM makes the best effort to run Garbage Collector but nothing is guaranteed.
Setting the reference variable to null will make the object, eligible for Garbage Collection, if there are no other references to this object. But this doesn’t force JVM to run the Garbage Collector. Garbage Collection cannot be forced.
Incorrect
SCP71000:
Both Runtime.getRuntime().gc(); and System.gc(); do the same thing, these make a request to JVM to run Garbage Collector.
JVM makes the best effort to run Garbage Collector but nothing is guaranteed.
Setting the reference variable to null will make the object, eligible for Garbage Collection, if there are no other references to this object. But this doesn’t force JVM to run the Garbage Collector. Garbage Collection cannot be forced.
Unattempted
SCP71000:
Both Runtime.getRuntime().gc(); and System.gc(); do the same thing, these make a request to JVM to run Garbage Collector.
JVM makes the best effort to run Garbage Collector but nothing is guaranteed.
Setting the reference variable to null will make the object, eligible for Garbage Collection, if there are no other references to this object. But this doesn’t force JVM to run the Garbage Collector. Garbage Collection cannot be forced.
Question 44 of 65
44. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
import java.io.FileNotFoundException;
public class Test {
static String [] names = {“Williamson.pdf”, “Finch.pdf”, “Kohli.pdf”, “Morgan.pdf”};
public static void main(String[] args) {
try {
if (search(“virat.pdf”))
System.out.println(“FOUND”);
private static boolean search(String name) throws FileNotFoundException {
for(int i = 0; i <= 4; i++) {
if (names[i].equalsIgnoreCase(name)) {
return true;
}
}
throw new FileNotFoundException();
}
}
What will be the result of compiling and executing Test class?
Correct
SCP45701:
search(String) method declares to throw FileNotFoundException, which is a checked exception. It returns true if match is found otherwise it throws an instance of FileNotFoundException.
main(String[]) provides try-catch block around `search(“virat.pdf”)` and catch handler checks for FileNotFoundException. Given code compiles successfully.
There are 4 elements in ‘names’ array, so starting index is 0 and end index is 3, but given for loop goes till index number 4.
As search string is “virat.pdf” (not present in names array), hence for loop will execute for i = 0, 1, 2, 3, 4.
For i = 4, `names[i].equalsIgnoreCase(name)` throws ArrayIndexOutOfBoundsException (it is a RuntimeException). main(String []) method doesn’t provide handler for ArrayIndexOutOfBoundsException and therefore stack trace is printed on to the console and program terminates abruptly.
Incorrect
SCP45701:
search(String) method declares to throw FileNotFoundException, which is a checked exception. It returns true if match is found otherwise it throws an instance of FileNotFoundException.
main(String[]) provides try-catch block around `search(“virat.pdf”)` and catch handler checks for FileNotFoundException. Given code compiles successfully.
There are 4 elements in ‘names’ array, so starting index is 0 and end index is 3, but given for loop goes till index number 4.
As search string is “virat.pdf” (not present in names array), hence for loop will execute for i = 0, 1, 2, 3, 4.
For i = 4, `names[i].equalsIgnoreCase(name)` throws ArrayIndexOutOfBoundsException (it is a RuntimeException). main(String []) method doesn’t provide handler for ArrayIndexOutOfBoundsException and therefore stack trace is printed on to the console and program terminates abruptly.
Unattempted
SCP45701:
search(String) method declares to throw FileNotFoundException, which is a checked exception. It returns true if match is found otherwise it throws an instance of FileNotFoundException.
main(String[]) provides try-catch block around `search(“virat.pdf”)` and catch handler checks for FileNotFoundException. Given code compiles successfully.
There are 4 elements in ‘names’ array, so starting index is 0 and end index is 3, but given for loop goes till index number 4.
As search string is “virat.pdf” (not present in names array), hence for loop will execute for i = 0, 1, 2, 3, 4.
For i = 4, `names[i].equalsIgnoreCase(name)` throws ArrayIndexOutOfBoundsException (it is a RuntimeException). main(String []) method doesn’t provide handler for ArrayIndexOutOfBoundsException and therefore stack trace is printed on to the console and program terminates abruptly.
Question 45 of 65
45. Question
Which of the following 2 options correctly define the Exam class?
Correct
SCP61485:
If package is used, then it should be the first statement. But javadoc and developer comments are not considered as java statements, so a class can have developer and javadoc comments before the package statement.
If import and package both are available, then correct order is package, import, class declaration.
Multiple package statements are not allowed.
Incorrect
SCP61485:
If package is used, then it should be the first statement. But javadoc and developer comments are not considered as java statements, so a class can have developer and javadoc comments before the package statement.
If import and package both are available, then correct order is package, import, class declaration.
Multiple package statements are not allowed.
Unattempted
SCP61485:
If package is used, then it should be the first statement. But javadoc and developer comments are not considered as java statements, so a class can have developer and javadoc comments before the package statement.
If import and package both are available, then correct order is package, import, class declaration.
Multiple package statements are not allowed.
Question 46 of 65
46. Question
ASCII code of ‘m’ is 109 and ‘M’ is 77.
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
StringBuilder[] array1 = { new StringBuilder(“Manners”), new StringBuilder(“maketh”),
new StringBuilder(“Man”) };
StringBuilder[] array2 = { new StringBuilder(“Manners”), new StringBuilder(“maketh”),
new StringBuilder(“man”) };
System.out.print(Arrays.mismatch(array1, array2));
System.out.print(Arrays.compare(array1, array2));
}
}
What will be the result of compiling and executing above code?
Correct
SCP65104:
Apart from mismatch methods for primitive arrays, Arrays class also has following non-primitive mismatch methods:
int mismatch?(Object[] a, Object[] a2): Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. Array elements are compared based on the obj.equals(Object) method.
int mismatch?(T[] a, T[] a2, Comparator super T> cmp): Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. Array elements are compared based on the specified comparator.
Statement Arrays.mismatch(array1, array2) returns 0 as StringBuilder class doesn’t override equals(Object) method and hence the implementation of equals(Object) method Object class is invoked. equals(Object) method defined in Object class uses == operator to check the equality and based on that 1st element (at index 0) of both the arrays don’t match.
Apart from compare methods to for primitive arrays, Arrays class also has following generic compare methods:
int compare?(T[] a, T[] b): Compares two Object arrays, with Comparable elements, lexicographically.
int compare?(T[] a, T[] b, Comparator super T> cmp): Compares two Object arrays using a specified comparator.
StringBuilder elements are Comparable, as StringBuilder class implements Comparable interface. Based on the compareTo(StringBuilder) method implementation, first two array elements of array1 and array2 are same.
As both the arrays have different StringBuilder objects at index 2 hence, Arrays.compare(array1, array2) returns -32, which is the result of “Man”.compareTo(“man”).
It simply returns ‘M’ – ‘m’ value, which is 77 – 109 = -32.
Output of the given code is: 0-32.
Incorrect
SCP65104:
Apart from mismatch methods for primitive arrays, Arrays class also has following non-primitive mismatch methods:
int mismatch?(Object[] a, Object[] a2): Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. Array elements are compared based on the obj.equals(Object) method.
int mismatch?(T[] a, T[] a2, Comparator super T> cmp): Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. Array elements are compared based on the specified comparator.
Statement Arrays.mismatch(array1, array2) returns 0 as StringBuilder class doesn’t override equals(Object) method and hence the implementation of equals(Object) method Object class is invoked. equals(Object) method defined in Object class uses == operator to check the equality and based on that 1st element (at index 0) of both the arrays don’t match.
Apart from compare methods to for primitive arrays, Arrays class also has following generic compare methods:
int compare?(T[] a, T[] b): Compares two Object arrays, with Comparable elements, lexicographically.
int compare?(T[] a, T[] b, Comparator super T> cmp): Compares two Object arrays using a specified comparator.
StringBuilder elements are Comparable, as StringBuilder class implements Comparable interface. Based on the compareTo(StringBuilder) method implementation, first two array elements of array1 and array2 are same.
As both the arrays have different StringBuilder objects at index 2 hence, Arrays.compare(array1, array2) returns -32, which is the result of “Man”.compareTo(“man”).
It simply returns ‘M’ – ‘m’ value, which is 77 – 109 = -32.
Output of the given code is: 0-32.
Unattempted
SCP65104:
Apart from mismatch methods for primitive arrays, Arrays class also has following non-primitive mismatch methods:
int mismatch?(Object[] a, Object[] a2): Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. Array elements are compared based on the obj.equals(Object) method.
int mismatch?(T[] a, T[] a2, Comparator super T> cmp): Finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. Array elements are compared based on the specified comparator.
Statement Arrays.mismatch(array1, array2) returns 0 as StringBuilder class doesn’t override equals(Object) method and hence the implementation of equals(Object) method Object class is invoked. equals(Object) method defined in Object class uses == operator to check the equality and based on that 1st element (at index 0) of both the arrays don’t match.
Apart from compare methods to for primitive arrays, Arrays class also has following generic compare methods:
int compare?(T[] a, T[] b): Compares two Object arrays, with Comparable elements, lexicographically.
int compare?(T[] a, T[] b, Comparator super T> cmp): Compares two Object arrays using a specified comparator.
StringBuilder elements are Comparable, as StringBuilder class implements Comparable interface. Based on the compareTo(StringBuilder) method implementation, first two array elements of array1 and array2 are same.
As both the arrays have different StringBuilder objects at index 2 hence, Arrays.compare(array1, array2) returns -32, which is the result of “Man”.compareTo(“man”).
It simply returns ‘M’ – ‘m’ value, which is 77 – 109 = -32.
Output of the given code is: 0-32.
Question 47 of 65
47. Question
What will be the result of compiling and executing Test class?
Correct
SCP50743:
while loop doesn’t have curly bracket over here, so only System.out.println(x) belongs to while loop.Â
Above syntax can be written as follows:Â
int x = 5;
while (x < 10) {
System.out.println(x);
}
x++;
As x++; is outside loop, hence value of x is always 5 within loop, 5 < 10 is true for all the iterations and hence infinite loop.
Incorrect
SCP50743:
while loop doesn’t have curly bracket over here, so only System.out.println(x) belongs to while loop.Â
Above syntax can be written as follows:Â
int x = 5;
while (x < 10) {
System.out.println(x);
}
x++;
As x++; is outside loop, hence value of x is always 5 within loop, 5 < 10 is true for all the iterations and hence infinite loop.
Unattempted
SCP50743:
while loop doesn’t have curly bracket over here, so only System.out.println(x) belongs to while loop.Â
Above syntax can be written as follows:Â
int x = 5;
while (x < 10) {
System.out.println(x);
}
x++;
As x++; is outside loop, hence value of x is always 5 within loop, 5 < 10 is true for all the iterations and hence infinite loop.
public class Test {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(0, “I”);
list.set(0, “CAN”);
System.out.println(list);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP79317:
list.add(0, “I”); means list –> [I], Â
list.set(0, “CAN”); means replace the current element at index 0 with the passed element “CAN”. So after this operation, list –> [CAN].
[CAN] is printed on to the console.
Incorrect
SCP79317:
list.add(0, “I”); means list –> [I], Â
list.set(0, “CAN”); means replace the current element at index 0 with the passed element “CAN”. So after this operation, list –> [CAN].
[CAN] is printed on to the console.
Unattempted
SCP79317:
list.add(0, “I”); means list –> [I], Â
list.set(0, “CAN”); means replace the current element at index 0 with the passed element “CAN”. So after this operation, list –> [CAN].
[CAN] is printed on to the console.
public class Test {
public static void convert(String s)
throws IllegalArgumentException, RuntimeException, Exception {
if(s.length() == 0) {
throw new RuntimeException(“LENGTH SHOULD BE GREATER THAN 0”);
}
}
public static void main(String [] args) {
try {
convert(“”);
}
catch(IllegalArgumentException | RuntimeException | Exception e) { //Line 14
System.out.println(e.getMessage()); //Line 15
} //Line 16
catch(Exception e) {
e.printStackTrace();
}
}
}
Line 14 causes compilation error. Which of the following changes enables to code to print LENGTH SHOULD BE GREATER THAN 0?
Correct
SCP54664:
Throwable is the root class of the exception hierarchy and it contains some useful constructors:
1. public Throwable() {…} : No-argument constructor
2. public Throwable(String message) {…} : Pass the detail message
3. public Throwable(String message, Throwable cause) {…} : Pass the detail message and the cause
4. public Throwable(Throwable cause) {…} : Pass the cause
Exception and RuntimeException classes also provide similar constructors.
Throwable class also contains methods, which are inherited by all the subclasses (Exception, RuntimeException etc.)
1. public String getMessage() {…} : Returns the detail message (E.g. detail message set by 2nd and 3rd constructor)
2. public String toString() {} :
Returns a short description of this throwable. The result is the concatenation of:
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.
In multi-catch statement, classes with multi-level hierarchical relationship can’t be used.
RuntimeException is subclass of Exception, IllegalArgumentException is indirect subclass of Exception and IllegalArgumentException is subclass of RuntimeException, hence these pairs can’t be used in multi-catch statement.
Only one option is left to replace Line 14 with ‘catch(RuntimeException e) {‘.
Commenting out Line 14, Line 15 and Line 16 will resolve the compilation error but it will print the whole stack trace rather than just printing the message.
Incorrect
SCP54664:
Throwable is the root class of the exception hierarchy and it contains some useful constructors:
1. public Throwable() {…} : No-argument constructor
2. public Throwable(String message) {…} : Pass the detail message
3. public Throwable(String message, Throwable cause) {…} : Pass the detail message and the cause
4. public Throwable(Throwable cause) {…} : Pass the cause
Exception and RuntimeException classes also provide similar constructors.
Throwable class also contains methods, which are inherited by all the subclasses (Exception, RuntimeException etc.)
1. public String getMessage() {…} : Returns the detail message (E.g. detail message set by 2nd and 3rd constructor)
2. public String toString() {} :
Returns a short description of this throwable. The result is the concatenation of:
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.
In multi-catch statement, classes with multi-level hierarchical relationship can’t be used.
RuntimeException is subclass of Exception, IllegalArgumentException is indirect subclass of Exception and IllegalArgumentException is subclass of RuntimeException, hence these pairs can’t be used in multi-catch statement.
Only one option is left to replace Line 14 with ‘catch(RuntimeException e) {‘.
Commenting out Line 14, Line 15 and Line 16 will resolve the compilation error but it will print the whole stack trace rather than just printing the message.
Unattempted
SCP54664:
Throwable is the root class of the exception hierarchy and it contains some useful constructors:
1. public Throwable() {…} : No-argument constructor
2. public Throwable(String message) {…} : Pass the detail message
3. public Throwable(String message, Throwable cause) {…} : Pass the detail message and the cause
4. public Throwable(Throwable cause) {…} : Pass the cause
Exception and RuntimeException classes also provide similar constructors.
Throwable class also contains methods, which are inherited by all the subclasses (Exception, RuntimeException etc.)
1. public String getMessage() {…} : Returns the detail message (E.g. detail message set by 2nd and 3rd constructor)
2. public String toString() {} :
Returns a short description of this throwable. The result is the concatenation of:
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.
In multi-catch statement, classes with multi-level hierarchical relationship can’t be used.
RuntimeException is subclass of Exception, IllegalArgumentException is indirect subclass of Exception and IllegalArgumentException is subclass of RuntimeException, hence these pairs can’t be used in multi-catch statement.
Only one option is left to replace Line 14 with ‘catch(RuntimeException e) {‘.
Commenting out Line 14, Line 15 and Line 16 will resolve the compilation error but it will print the whole stack trace rather than just printing the message.
Question 50 of 65
50. Question
Consider below code of Circus.java file:
//Circus.java
package com.udayankhattry.ocp1;
class Animal {
protected void jump() {
System.out.println(“ANIMAL”);
}
}
class Cat extends Animal {
public void jump(int a) {
System.out.println(“CAT”);
}
}
class Deer extends Animal {
public void jump() {
System.out.println(“DEER”);
}
}
public class Circus {
public static void main(String[] args) {
Animal cat = new Cat();
Animal deer = new Deer();
cat.jump();
deer.jump();
}
}
What will be the result of compiling and executing above code?
Correct
SCP58036:
Cat class doesn’t override the jump() method of Animal class, in fact jump(int) method is overloaded in Cat class.
Deer class overrides jump() method of Animal class.
Reference variable ‘cat’ is of Animal type, cat.jump() syntax is fine and as Cat doesn’t override jump() method hence Animal version is invoked, which prints ANIMAL on to the console.
Even though reference variable ‘deer’ is of Animal type but at runtime `deer.jump();` invokes overriding method of Deer class, this prints DEER on to the console.
Incorrect
SCP58036:
Cat class doesn’t override the jump() method of Animal class, in fact jump(int) method is overloaded in Cat class.
Deer class overrides jump() method of Animal class.
Reference variable ‘cat’ is of Animal type, cat.jump() syntax is fine and as Cat doesn’t override jump() method hence Animal version is invoked, which prints ANIMAL on to the console.
Even though reference variable ‘deer’ is of Animal type but at runtime `deer.jump();` invokes overriding method of Deer class, this prints DEER on to the console.
Unattempted
SCP58036:
Cat class doesn’t override the jump() method of Animal class, in fact jump(int) method is overloaded in Cat class.
Deer class overrides jump() method of Animal class.
Reference variable ‘cat’ is of Animal type, cat.jump() syntax is fine and as Cat doesn’t override jump() method hence Animal version is invoked, which prints ANIMAL on to the console.
Even though reference variable ‘deer’ is of Animal type but at runtime `deer.jump();` invokes overriding method of Deer class, this prints DEER on to the console.
Question 51 of 65
51. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
interface Operator {
public abstract T operation(T t1, T t2);
}
public class Test {
public static void main(String[] args) {
System.out.println(/*INSERT*/);
}
}
Which of the following statements can be used to replace /*INSERT*/ such that there are no compilation errors?
Correct
SCP48647:
Reference variable to which lambda expression is assigned is known as target type. Target type can be a static variable, instance variable, local variable, method parameter or return type. Lambda expression doesn’t work without target type and target type must be a functional interface.Â
In this case, println(Object) method is invoked but Object is a class and not a functional interface, hence no lambda expression can be passed directly to println method.Â
But you can first assign lambda expression to target type and then pass the target type reference variable to println(Object) method:
Operator operator = (s1, s2) -> s1 + s2;Â
System.out.println(operator);
Or you can typecast lambda expression to target type. e.g. following works:
System.out.println((Operator)(String s1, String s2) -> s1 + s2);
System.out.println((Operator)(s1, s2) -> s1 + s2);
System.out.println((Operator)(s1, s2) -> { return s1 + s2; });
Incorrect
SCP48647:
Reference variable to which lambda expression is assigned is known as target type. Target type can be a static variable, instance variable, local variable, method parameter or return type. Lambda expression doesn’t work without target type and target type must be a functional interface.Â
In this case, println(Object) method is invoked but Object is a class and not a functional interface, hence no lambda expression can be passed directly to println method.Â
But you can first assign lambda expression to target type and then pass the target type reference variable to println(Object) method:
Operator operator = (s1, s2) -> s1 + s2;Â
System.out.println(operator);
Or you can typecast lambda expression to target type. e.g. following works:
System.out.println((Operator)(String s1, String s2) -> s1 + s2);
System.out.println((Operator)(s1, s2) -> s1 + s2);
System.out.println((Operator)(s1, s2) -> { return s1 + s2; });
Unattempted
SCP48647:
Reference variable to which lambda expression is assigned is known as target type. Target type can be a static variable, instance variable, local variable, method parameter or return type. Lambda expression doesn’t work without target type and target type must be a functional interface.Â
In this case, println(Object) method is invoked but Object is a class and not a functional interface, hence no lambda expression can be passed directly to println method.Â
But you can first assign lambda expression to target type and then pass the target type reference variable to println(Object) method:
Operator operator = (s1, s2) -> s1 + s2;Â
System.out.println(operator);
Or you can typecast lambda expression to target type. e.g. following works:
System.out.println((Operator)(String s1, String s2) -> s1 + s2);
System.out.println((Operator)(s1, s2) -> s1 + s2);
System.out.println((Operator)(s1, s2) -> { return s1 + s2; });
Question 52 of 65
52. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
String arr1 [], arr2, arr3 = null; //Line n1
arr1 = new String[2];
arr1[0] = “A”;
arr1[1] = “B”;
arr2 = arr3 = arr1; //Line n2
System.out.println(String.join(“-“, arr2)); //Line n3
}
}
What will be the result of compiling and executing Test class?
Correct
SCP74933:
arr1 is of String[] type, where as arr2 and arr3 are of String type. As all three arr1, arr2 and arr3 are of reference type, hence null can be assigned to all these variables. Line n1 compiles successfully.
Statement at Line n2: arr2 = arr3 = arr1;
=> arr2 = (arr3 = arr1); //assignment operator is right to left associative.
arr3 is of String type and arr1 is of String [] type, hence (arr3 = arr1) causes compilation error.
Though you had to select one correct option, hence no need to look further but I am providing explanation for Line n3 as well.
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, `String.join(“-“, arr2)` compiles successfully as arr2 is of String type.
Incorrect
SCP74933:
arr1 is of String[] type, where as arr2 and arr3 are of String type. As all three arr1, arr2 and arr3 are of reference type, hence null can be assigned to all these variables. Line n1 compiles successfully.
Statement at Line n2: arr2 = arr3 = arr1;
=> arr2 = (arr3 = arr1); //assignment operator is right to left associative.
arr3 is of String type and arr1 is of String [] type, hence (arr3 = arr1) causes compilation error.
Though you had to select one correct option, hence no need to look further but I am providing explanation for Line n3 as well.
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, `String.join(“-“, arr2)` compiles successfully as arr2 is of String type.
Unattempted
SCP74933:
arr1 is of String[] type, where as arr2 and arr3 are of String type. As all three arr1, arr2 and arr3 are of reference type, hence null can be assigned to all these variables. Line n1 compiles successfully.
Statement at Line n2: arr2 = arr3 = arr1;
=> arr2 = (arr3 = arr1); //assignment operator is right to left associative.
arr3 is of String type and arr1 is of String [] type, hence (arr3 = arr1) causes compilation error.
Though you had to select one correct option, hence no need to look further but I am providing explanation for Line n3 as well.
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, `String.join(“-“, arr2)` compiles successfully as arr2 is of String type.
Question 53 of 65
53. Question
For the implied readability, which of the below directives is used in the module descriptor?
Correct
SCP70967:
Implied readability is to specify a transitive dependency on another module such that other modules reading your module also read that dependency.
For example, if module C has `requires B;` (C reads B) and module B has `requires A;` (B reads A), then C doesn’t read A.
To have the transitive readability, ‘requires transitive’ directive is used. If module C has `requires B;` (C reads B) and module B has `requires transitive A;` (B reads A [transitive dependency]), then C will also read A.
Incorrect
SCP70967:
Implied readability is to specify a transitive dependency on another module such that other modules reading your module also read that dependency.
For example, if module C has `requires B;` (C reads B) and module B has `requires A;` (B reads A), then C doesn’t read A.
To have the transitive readability, ‘requires transitive’ directive is used. If module C has `requires B;` (C reads B) and module B has `requires transitive A;` (B reads A [transitive dependency]), then C will also read A.
Unattempted
SCP70967:
Implied readability is to specify a transitive dependency on another module such that other modules reading your module also read that dependency.
For example, if module C has `requires B;` (C reads B) and module B has `requires A;` (B reads A), then C doesn’t read A.
To have the transitive readability, ‘requires transitive’ directive is used. If module C has `requires B;` (C reads B) and module B has `requires transitive A;` (B reads A [transitive dependency]), then C will also read A.
Question 54 of 65
54. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
var i = 1;
var j = 5;
var k = 0;
A: while(true) {
i++;
B: while(true) {
j–;
C: while(true) {
k += i + j;
if(i == j)
break A;
else if (i > j)
continue A;
else
continue B;
}
}
}
System.out.println(k);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP72548:
No syntax error in the given code.
Initially, i = 1, j = 5 and k = 0.
1st iteration of A: i = 2.
  1st iteration of B: j = 4.
    1st iteration of C: k = k + i + j = 0 + 2 + 4 = 6. `i == j` evaluates to false and `i > j` also evaluates to false, hence else block gets executed. `continue B` takes the control to the loop B.
  2nd iteration of B: j = 3.
    1st iteration of C: k = k + i + j = 6 + 2 + 3 = 11. `i == j` evaluates to false and `i > j` also evaluates to false, hence else block gets executed. `continue B` takes the control to the loop B.
  3rd iteration of B: j = 2.
    1st iteration of C: k = k + i + j = 11 + 2 + 2 = 15. `i == j` evaluates to true, control breaks out of the loop A.
`System.out.println(k);` prints 15 on to the console.
Incorrect
SCP72548:
No syntax error in the given code.
Initially, i = 1, j = 5 and k = 0.
1st iteration of A: i = 2.
  1st iteration of B: j = 4.
    1st iteration of C: k = k + i + j = 0 + 2 + 4 = 6. `i == j` evaluates to false and `i > j` also evaluates to false, hence else block gets executed. `continue B` takes the control to the loop B.
  2nd iteration of B: j = 3.
    1st iteration of C: k = k + i + j = 6 + 2 + 3 = 11. `i == j` evaluates to false and `i > j` also evaluates to false, hence else block gets executed. `continue B` takes the control to the loop B.
  3rd iteration of B: j = 2.
    1st iteration of C: k = k + i + j = 11 + 2 + 2 = 15. `i == j` evaluates to true, control breaks out of the loop A.
`System.out.println(k);` prints 15 on to the console.
Unattempted
SCP72548:
No syntax error in the given code.
Initially, i = 1, j = 5 and k = 0.
1st iteration of A: i = 2.
  1st iteration of B: j = 4.
    1st iteration of C: k = k + i + j = 0 + 2 + 4 = 6. `i == j` evaluates to false and `i > j` also evaluates to false, hence else block gets executed. `continue B` takes the control to the loop B.
  2nd iteration of B: j = 3.
    1st iteration of C: k = k + i + j = 6 + 2 + 3 = 11. `i == j` evaluates to false and `i > j` also evaluates to false, hence else block gets executed. `continue B` takes the control to the loop B.
  3rd iteration of B: j = 2.
    1st iteration of C: k = k + i + j = 11 + 2 + 2 = 15. `i == j` evaluates to true, control breaks out of the loop A.
`System.out.println(k);` prints 15 on to the console.
Question 55 of 65
55. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
double price = 90000;
String model;
if(price > 100000) {
model = “Tesla Model X”;
} else if(price <= 100000) {
model = "Tesla Model S";
}
System.out.println(model);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP67342:
In this case “if – else if” block is used and not “if – else” block.
90000 is assigned to variable ‘price’ but you can assign parameter value or call some method returning double value, such as:
`double price = currentTemp();`.
In these cases, compiler will not know the exact value until runtime, hence Java Compiler is not sure which boolean expression will be evaluated to true and so variable model may not be initialized.
Usage of LOCAL variable, ‘model’ without initialization causes compilation error. Hence, `System.out.println(model);` statement causes compilation error.
Incorrect
SCP67342:
In this case “if – else if” block is used and not “if – else” block.
90000 is assigned to variable ‘price’ but you can assign parameter value or call some method returning double value, such as:
`double price = currentTemp();`.
In these cases, compiler will not know the exact value until runtime, hence Java Compiler is not sure which boolean expression will be evaluated to true and so variable model may not be initialized.
Usage of LOCAL variable, ‘model’ without initialization causes compilation error. Hence, `System.out.println(model);` statement causes compilation error.
Unattempted
SCP67342:
In this case “if – else if” block is used and not “if – else” block.
90000 is assigned to variable ‘price’ but you can assign parameter value or call some method returning double value, such as:
`double price = currentTemp();`.
In these cases, compiler will not know the exact value until runtime, hence Java Compiler is not sure which boolean expression will be evaluated to true and so variable model may not be initialized.
Usage of LOCAL variable, ‘model’ without initialization causes compilation error. Hence, `System.out.println(model);` statement causes compilation error.
class Base {
protected void m1() {
System.out.println(“Base: m1()”);
}
}
class Derived extends Base {
void m1() {
System.out.println(“Derived: m1()”);
}
}
public class TestBaseDerived {
public static void main(String[] args) {
Base b = new Derived();
b.m1();
}
}
What will be the result of compiling and executing TestBaseDerived class?
Correct
SCP16204:
Derived class overrides method m1() of Base class.
Access modifier of method m1() in Base class is protected, so overriding method can use protected or public. But overriding method in this case used default modifier and hence there is compilation error.
Incorrect
SCP16204:
Derived class overrides method m1() of Base class.
Access modifier of method m1() in Base class is protected, so overriding method can use protected or public. But overriding method in this case used default modifier and hence there is compilation error.
Unattempted
SCP16204:
Derived class overrides method m1() of Base class.
Access modifier of method m1() in Base class is protected, so overriding method can use protected or public. But overriding method in this case used default modifier and hence there is compilation error.
Question 57 of 65
57. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
for(var i = 5; i >= 1; i–) { //Line n1
System.out.println(“*”.repeat(i)); //Line n2
}
}
}
What will be the result of compiling and executing Test class?
Correct
SCP35359:
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.
At Line n1, variable ‘i’ infers to int type, so given loop executes 5 times from values of i from 5 to 1.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
1st iteration: System.out.println(“*”.repeat(5)); => prints ***** on to the console.
2nd iteration: System.out.println(“*”.repeat(4)); => prints **** on to the console.
3rd iteration: System.out.println(“*”.repeat(3)); => prints *** on to the console.
4th iteration: System.out.println(“*”.repeat(2)); => prints ** on to the console.
5th iteration: System.out.println(“*”.repeat(1)); => prints * on to the console.
Hence, output is:
*****
****
***
**
*
Incorrect
SCP35359:
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.
At Line n1, variable ‘i’ infers to int type, so given loop executes 5 times from values of i from 5 to 1.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
1st iteration: System.out.println(“*”.repeat(5)); => prints ***** on to the console.
2nd iteration: System.out.println(“*”.repeat(4)); => prints **** on to the console.
3rd iteration: System.out.println(“*”.repeat(3)); => prints *** on to the console.
4th iteration: System.out.println(“*”.repeat(2)); => prints ** on to the console.
5th iteration: System.out.println(“*”.repeat(1)); => prints * on to the console.
Hence, output is:
*****
****
***
**
*
Unattempted
SCP35359:
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.
At Line n1, variable ‘i’ infers to int type, so given loop executes 5 times from values of i from 5 to 1.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
1st iteration: System.out.println(“*”.repeat(5)); => prints ***** on to the console.
2nd iteration: System.out.println(“*”.repeat(4)); => prints **** on to the console.
3rd iteration: System.out.println(“*”.repeat(3)); => prints *** on to the console.
4th iteration: System.out.println(“*”.repeat(2)); => prints ** on to the console.
5th iteration: System.out.println(“*”.repeat(1)); => prints * on to the console.
Hence, output is:
*****
****
***
**
*
public class Test {
public static void main(String[] args) {
var books = List.of(new Book (“Head First Java”, “Kathy Sierra”, 19.5),
new Book (“Java SE 11 Programmer I -1Z0-815 Practice Tests”, “Udayan Khattry”, 9.99),
new Book (“Java – The Complete Reference”, “Herbert Schildt”, 14.0));
What will be the result of compiling and executing Test class?
Correct
SCP40919:
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 books = List.of(…); => books refers to a List of Book 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 ‘books’ 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 books reference) but 3 Book 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: `b -> b.setPrice(b.getPrice() – 4` is the correct implementation of `void accept(Book t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to reduce the book price by 4 units. Hence, statement at Line n1 will reduce the price of 3 Book instances available in the list.
Lambda expression at Line n2: `b -> System.out.println(b)` is also the correct implementation of `void accept(Book t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to print the Book object on to the console. toString() method of Book object is invoked and it uses static join method of String class to construct the display String.
Statement at Line n2 will print the details of 3 Book instances available in the list.
Output will be:
Head First Java:Kathy Sierra:15.5
Java SE 11 Programmer I -1Z0-815 Practice Tests:Udayan Khattry:5.99
Java – The Complete Reference:Herbert Schildt:10.0
Incorrect
SCP40919:
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 books = List.of(…); => books refers to a List of Book 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 ‘books’ 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 books reference) but 3 Book 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: `b -> b.setPrice(b.getPrice() – 4` is the correct implementation of `void accept(Book t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to reduce the book price by 4 units. Hence, statement at Line n1 will reduce the price of 3 Book instances available in the list.
Lambda expression at Line n2: `b -> System.out.println(b)` is also the correct implementation of `void accept(Book t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to print the Book object on to the console. toString() method of Book object is invoked and it uses static join method of String class to construct the display String.
Statement at Line n2 will print the details of 3 Book instances available in the list.
Output will be:
Head First Java:Kathy Sierra:15.5
Java SE 11 Programmer I -1Z0-815 Practice Tests:Udayan Khattry:5.99
Java – The Complete Reference:Herbert Schildt:10.0
Unattempted
SCP40919:
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 books = List.of(…); => books refers to a List of Book 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 ‘books’ 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 books reference) but 3 Book 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: `b -> b.setPrice(b.getPrice() – 4` is the correct implementation of `void accept(Book t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to reduce the book price by 4 units. Hence, statement at Line n1 will reduce the price of 3 Book instances available in the list.
Lambda expression at Line n2: `b -> System.out.println(b)` is also the correct implementation of `void accept(Book t);` and hence can easily be assigned to target type Consumer. Purpose of this lambda expression is to print the Book object on to the console. toString() method of Book object is invoked and it uses static join method of String class to construct the display String.
Statement at Line n2 will print the details of 3 Book instances available in the list.
Output will be:
Head First Java:Kathy Sierra:15.5
Java SE 11 Programmer I -1Z0-815 Practice Tests:Udayan Khattry:5.99
Java – The Complete Reference:Herbert Schildt:10.0
Question 59 of 65
59. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
System.out.println(“Equals??? ” + 10 != 5);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP12252:
Binary plus (+) has got higher precedence than != operator. Let us group the expression.Â
“Equals??? ” + 10 != 5Â
= (“Equals??? ” + 10) != 5Â
[!= is binary operator, so we have to evaluate the left side first. + operator behaves as concatenation operator.]Â
= “Equals??? 10” != 5Â
Left side of above expression is String, and right side is int. But String can’t be compared to int hence compilation error.Â
Incorrect
SCP12252:
Binary plus (+) has got higher precedence than != operator. Let us group the expression.Â
“Equals??? ” + 10 != 5Â
= (“Equals??? ” + 10) != 5Â
[!= is binary operator, so we have to evaluate the left side first. + operator behaves as concatenation operator.]Â
= “Equals??? 10” != 5Â
Left side of above expression is String, and right side is int. But String can’t be compared to int hence compilation error.Â
Unattempted
SCP12252:
Binary plus (+) has got higher precedence than != operator. Let us group the expression.Â
“Equals??? ” + 10 != 5Â
= (“Equals??? ” + 10) != 5Â
[!= is binary operator, so we have to evaluate the left side first. + operator behaves as concatenation operator.]Â
= “Equals??? 10” != 5Â
Left side of above expression is String, and right side is int. But String can’t be compared to int hence compilation error.Â
Question 60 of 65
60. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
String[] arr = { “L”, “I”, “V”, “E” }; //Line n1
int i = -2;
What will be the result of compiling and executing Test class?
Correct
SCP88090:
Line n1 creates a String [] object of 4 elements and arr refers to this array object. arr[0] = “L”, arr[1] = “I”, arr[2] = “V” and arr[3] = “E”.
i = -2.
Boolean expression of Line n2: i++ == -1
=> (i++) == -1 //As Post-increment operator ++ has higher precedence over ==
=> -2 == -1 //i = -1, value of i is used in the expression and then incremented.
=> false and hence Line n3 is not executed.
But there is no issue with Line n3 and it compiles successfully.
Boolean expression of Line n4 is evaluated next:
–i == -2 //i = -1
=> (–i) == -2 //As Pre-decrement operator — has higher precedence over ==
=> -2 == -2 //i = -2, value of i is decremented first and then used in the expression.
=> true and hence Line n5 is executed next.
Line n5:
arr[-++i] = “O”; //i = -2
=> arr[-(++i)] = “O”; //Unary minus ‘-‘ and pre-increment ‘++’ operators have same precedence
=> arr[-(-1)] = “O”; //i = -1, value of i is incremented first and then used in the expression.
=> arr[1] = “O”; //2nd array element is changed to “O”.
Hence after Line n5, arr refers to {“L”, “O”, “V”, “E”}
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.
Hence, `System.out.println(String.join(“”, arr));` prints LOVE on to the console.
Incorrect
SCP88090:
Line n1 creates a String [] object of 4 elements and arr refers to this array object. arr[0] = “L”, arr[1] = “I”, arr[2] = “V” and arr[3] = “E”.
i = -2.
Boolean expression of Line n2: i++ == -1
=> (i++) == -1 //As Post-increment operator ++ has higher precedence over ==
=> -2 == -1 //i = -1, value of i is used in the expression and then incremented.
=> false and hence Line n3 is not executed.
But there is no issue with Line n3 and it compiles successfully.
Boolean expression of Line n4 is evaluated next:
–i == -2 //i = -1
=> (–i) == -2 //As Pre-decrement operator — has higher precedence over ==
=> -2 == -2 //i = -2, value of i is decremented first and then used in the expression.
=> true and hence Line n5 is executed next.
Line n5:
arr[-++i] = “O”; //i = -2
=> arr[-(++i)] = “O”; //Unary minus ‘-‘ and pre-increment ‘++’ operators have same precedence
=> arr[-(-1)] = “O”; //i = -1, value of i is incremented first and then used in the expression.
=> arr[1] = “O”; //2nd array element is changed to “O”.
Hence after Line n5, arr refers to {“L”, “O”, “V”, “E”}
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.
Hence, `System.out.println(String.join(“”, arr));` prints LOVE on to the console.
Unattempted
SCP88090:
Line n1 creates a String [] object of 4 elements and arr refers to this array object. arr[0] = “L”, arr[1] = “I”, arr[2] = “V” and arr[3] = “E”.
i = -2.
Boolean expression of Line n2: i++ == -1
=> (i++) == -1 //As Post-increment operator ++ has higher precedence over ==
=> -2 == -1 //i = -1, value of i is used in the expression and then incremented.
=> false and hence Line n3 is not executed.
But there is no issue with Line n3 and it compiles successfully.
Boolean expression of Line n4 is evaluated next:
–i == -2 //i = -1
=> (–i) == -2 //As Pre-decrement operator — has higher precedence over ==
=> -2 == -2 //i = -2, value of i is decremented first and then used in the expression.
=> true and hence Line n5 is executed next.
Line n5:
arr[-++i] = “O”; //i = -2
=> arr[-(++i)] = “O”; //Unary minus ‘-‘ and pre-increment ‘++’ operators have same precedence
=> arr[-(-1)] = “O”; //i = -1, value of i is incremented first and then used in the expression.
=> arr[1] = “O”; //2nd array element is changed to “O”.
Hence after Line n5, arr refers to {“L”, “O”, “V”, “E”}
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.
Hence, `System.out.println(String.join(“”, arr));` prints LOVE on to the console.
abstract class Super {
public abstract void m1() throws IOException;
}
class Sub extends Super {
@Override
public void m1() throws IOException {
throw new FileNotFoundException();
}
}
public class Test {
public static void main(String[] args) {
Super s = new Sub();
try {
s.m1();
} catch (IOException e) {
System.out.print(“A”);
} catch(FileNotFoundException e) {
System.out.print(“B”);
} finally {
System.out.print(“C”);
}
}
}
What will be the result of compiling and executing Test class?
Correct
SCP41108:
Method m1() of Sub class correctly overrides the method m1() of Super class, so there is no compilation error in Sub class.
FileNotFoundException extends IOException and hence catch block of FileNotFoundException should appear before the catch block of IOException.
Therefore, class Test causes compilation error.
Incorrect
SCP41108:
Method m1() of Sub class correctly overrides the method m1() of Super class, so there is no compilation error in Sub class.
FileNotFoundException extends IOException and hence catch block of FileNotFoundException should appear before the catch block of IOException.
Therefore, class Test causes compilation error.
Unattempted
SCP41108:
Method m1() of Sub class correctly overrides the method m1() of Super class, so there is no compilation error in Sub class.
FileNotFoundException extends IOException and hence catch block of FileNotFoundException should appear before the catch block of IOException.
Therefore, class Test causes compilation error.
Question 62 of 65
62. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(20); //Line n1
sb.append(“A”.repeat(25)); //Line n2
System.out.println(sb.toString().length()); //Line n3
What will be the result of compiling and executing Test class?
Correct
SCP27131:
`new StringBuilder(20);` creates a StringBuilder instance, whose capacity (internal char array’s length) is 20. This initial capacity is not fixed and changes on adding / removing characters to the StringBuilder object.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
Line n2 successfully appends 25 A’s to the StringBuilder object.
Line n3 prints 25 on to the console.
At Line n4, `sb.setLength(10);` sets the length of StringBuilder object referred by ‘sb’ to 10 (it is reducing the length of StringBuilder object from 25 to 10), hence ‘sb’ refers to StringBuilder object containing 10 A’s (last 15 A’s are gone).
Hence, Line n3 prints 10 on to the console.
Incorrect
SCP27131:
`new StringBuilder(20);` creates a StringBuilder instance, whose capacity (internal char array’s length) is 20. This initial capacity is not fixed and changes on adding / removing characters to the StringBuilder object.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
Line n2 successfully appends 25 A’s to the StringBuilder object.
Line n3 prints 25 on to the console.
At Line n4, `sb.setLength(10);` sets the length of StringBuilder object referred by ‘sb’ to 10 (it is reducing the length of StringBuilder object from 25 to 10), hence ‘sb’ refers to StringBuilder object containing 10 A’s (last 15 A’s are gone).
Hence, Line n3 prints 10 on to the console.
Unattempted
SCP27131:
`new StringBuilder(20);` creates a StringBuilder instance, whose capacity (internal char array’s length) is 20. This initial capacity is not fixed and changes on adding / removing characters to the StringBuilder object.
Instance method ‘repeat()’ has been added to String class in Java 11 and it has the signature: `public String repeat(int count) {}`
It returns the new String object whose value is the concatenation of this String repeated ‘count’ times. For example,
“A”.repeat(3); returns “AAA”.
Line n2 successfully appends 25 A’s to the StringBuilder object.
Line n3 prints 25 on to the console.
At Line n4, `sb.setLength(10);` sets the length of StringBuilder object referred by ‘sb’ to 10 (it is reducing the length of StringBuilder object from 25 to 10), hence ‘sb’ refers to StringBuilder object containing 10 A’s (last 15 A’s are gone).
Hence, Line n3 prints 10 on to the console.
Question 63 of 65
63. Question
Which of the following commands displays the list of system modules?
Correct
SCP30480:
To get a list of all the system modules, use below command:
java –list-modules
Incorrect
SCP30480:
To get a list of all the system modules, use below command:
java –list-modules
Unattempted
SCP30480:
To get a list of all the system modules, use below command:
java –list-modules
Question 64 of 65
64. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
interface ILog {
void log();
boolean equals();
}
public class Test {
public static void main(String[] args) {
ILog obj = () -> System.out.println(“FEELING FANTASTIC”);
obj.log();
}
}
What will be the result of compiling and executing Test class?
Correct
SCP69338:
Functional interface must have only one non-overriding abstract method but Functional interface can have constant variables, static methods, default methods, private methods and overriding abstract methods [equals(Object) method, toString() method etc. from Object class].
Interface ILog specifies two non-overriding abstract methods, hence lambda expression causes compilation error.
Incorrect
SCP69338:
Functional interface must have only one non-overriding abstract method but Functional interface can have constant variables, static methods, default methods, private methods and overriding abstract methods [equals(Object) method, toString() method etc. from Object class].
Interface ILog specifies two non-overriding abstract methods, hence lambda expression causes compilation error.
Unattempted
SCP69338:
Functional interface must have only one non-overriding abstract method but Functional interface can have constant variables, static methods, default methods, private methods and overriding abstract methods [equals(Object) method, toString() method etc. from Object class].
Interface ILog specifies two non-overriding abstract methods, hence lambda expression causes compilation error.
Question 65 of 65
65. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String [] args) {
var x = 7.85; //Line n1
var y = 5.25f; //Line n2
var a = (int)x + (int)y; //Line n3
var b = (int)(x + y); //Line n4
System.out.println(a + b);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP53663:
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.
At Line n1, x infers to double type as 7.85 is double literal.
At Line n2, y infers to float type as 5.25f is a float literal.
Line n3:
var a = (int)x + (int)y;
var a = (int)7.85 + (int)5.25;
var a = 7 + 5;
var a = 12; //a infers to int type
Line n4:
var b = (int)(x + y);
var b = (int)(7.85 + 5.25);
var b = (int)(13.10);
var b = 13; //b infers to int type
Hence, `System.out.println(a + b);` prints 25 on to the console.
Incorrect
SCP53663:
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.
At Line n1, x infers to double type as 7.85 is double literal.
At Line n2, y infers to float type as 5.25f is a float literal.
Line n3:
var a = (int)x + (int)y;
var a = (int)7.85 + (int)5.25;
var a = 7 + 5;
var a = 12; //a infers to int type
Line n4:
var b = (int)(x + y);
var b = (int)(7.85 + 5.25);
var b = (int)(13.10);
var b = 13; //b infers to int type
Hence, `System.out.println(a + b);` prints 25 on to the console.
Unattempted
SCP53663:
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.
At Line n1, x infers to double type as 7.85 is double literal.
At Line n2, y infers to float type as 5.25f is a float literal.
Line n3:
var a = (int)x + (int)y;
var a = (int)7.85 + (int)5.25;
var a = 7 + 5;
var a = 12; //a infers to int type
Line n4:
var b = (int)(x + y);
var b = (int)(7.85 + 5.25);
var b = (int)(13.10);
var b = 13; //b infers to int type
Hence, `System.out.println(a + b);` prints 25 on to the console.
X
Use Page numbers below to navigate to other practice tests