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 4 "
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
Which of the following is not a valid array declaration?
Correct
SCP89183:
`int [] arr1 = new int[8];` Creates one-dimensional array object to store 8 elements and arr1 refers to it. This statement compiles without any error.
`int [][] arr2 = new int[8][8];` Creates two-dimensional array object to store 8 * 8 = 64 elements. This statement also compiles fine.
`int [] arr3 [] = new int[8][];` Creates two-dimensional array object, whose 1st dimension is 8 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 `int [][] arr3`, `int [] arr3 []` and `int arr3[][]` all are valid. This statement compiles successfully.
`int arr4[][] = new int[][8];`: 1st array dimension must be specified at the time of declaration. new int[][8]; causes compilation error as 1st dimension is not specified.
Incorrect
SCP89183:
`int [] arr1 = new int[8];` Creates one-dimensional array object to store 8 elements and arr1 refers to it. This statement compiles without any error.
`int [][] arr2 = new int[8][8];` Creates two-dimensional array object to store 8 * 8 = 64 elements. This statement also compiles fine.
`int [] arr3 [] = new int[8][];` Creates two-dimensional array object, whose 1st dimension is 8 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 `int [][] arr3`, `int [] arr3 []` and `int arr3[][]` all are valid. This statement compiles successfully.
`int arr4[][] = new int[][8];`: 1st array dimension must be specified at the time of declaration. new int[][8]; causes compilation error as 1st dimension is not specified.
Unattempted
SCP89183:
`int [] arr1 = new int[8];` Creates one-dimensional array object to store 8 elements and arr1 refers to it. This statement compiles without any error.
`int [][] arr2 = new int[8][8];` Creates two-dimensional array object to store 8 * 8 = 64 elements. This statement also compiles fine.
`int [] arr3 [] = new int[8][];` Creates two-dimensional array object, whose 1st dimension is 8 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 `int [][] arr3`, `int [] arr3 []` and `int arr3[][]` all are valid. This statement compiles successfully.
`int arr4[][] = new int[][8];`: 1st array dimension must be specified at the time of declaration. new int[][8]; causes compilation error as 1st dimension is not specified.
What will be the result of compiling and executing Test class?
Correct
SCP68210:
process(List, Predicate) method prints all the records passing the Predicate’s test and test is to process the records having Furniture’s weight less than 45. There are 3 records (Chair, Table & Sofa) with weight < 45 and these are printed in the insertion order.
NOTE: toString() method just returns the name.
Incorrect
SCP68210:
process(List, Predicate) method prints all the records passing the Predicate’s test and test is to process the records having Furniture’s weight less than 45. There are 3 records (Chair, Table & Sofa) with weight < 45 and these are printed in the insertion order.
NOTE: toString() method just returns the name.
Unattempted
SCP68210:
process(List, Predicate) method prints all the records passing the Predicate’s test and test is to process the records having Furniture’s weight less than 45. There are 3 records (Chair, Table & Sofa) with weight < 45 and these are printed in the insertion order.
NOTE: toString() method just returns the name.
SCP38860:
Instance overloaded method split(…) has below declarations:
1. public String[] split?(String regex, int limit) {…}: It returns the String[] after splitting this string around matches of the given regex.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
A. If the limit is positive then the pattern will be applied at most (limit – 1) times, the array’s length will be no greater than limit, and the array’s last entry will contain all input beyond the last matched delimiter. For example:
“BAZAAR”.split(“A”, 1); returns [“BAZAAR”] as pattern is applied 1 – 1 = 0 time.
“BAZAAR”.split(“A”, 2); returns [“B”,”ZAAR”] as pattern is applied 2 – 1 = 1 time.
“BAZAAR”.split(“A”, 3); returns [“B”,”Z”,”AR”] as pattern is applied 3 – 1 = 2 times.
“BAZAAR”.split(“A”, 4); returns [“B”,”Z”,””,”R”] as pattern is applied 4 – 1 = 3 times.
“BAZAAR”.split(“A”, 4); returns [“B”,”Z”,””,”R”] as pattern needs to be applied 5 – 1 = 4 times but it is applied 3 times (which is max).
“:”.split(“:”, 2); returns [“”,””] as pattern is applied (2 – 1) time and there is an empty space (“”) before and after “:”, so resulting array contains two empty strings.
B. If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. For example,
“BAZAAR”.split(“A”, 0); returns [“B”,”Z”,””,”R”].
“:”.split(“:”, 0); returns blank array as both the empty strings are discarded.
C. If the limit is negative then the pattern will be applied as many times as possible and the array can have any length. For example,
“BAZAAR”.split(“A”, -10); returns [“B”,”Z”,””,”R”] as pattern is applied max times, which is 3.
“:”.split(“:”, -2); returns [“”,””] as pattern is applied max times, which is 3.
2. public String[] split?(String regex) {…}: It returns the String[] after splitting this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.Â
“BAZAAR”.split(“A”); returns [“B”,”Z”,””,”R”] as this statement is equivalent to “BAZAAR”.split(“A”, 0);.
“:”.split(“:”); returns blank array as this statement is equivalent to “:”.split(“:”, 0);.
Let’s solve the given expression based on above points:
txt.split(“an”).length
=”an”.split(“an”).length
=[].length //”an”.split(“an”) returns blank array as both the empty strings are discarded.
0
Hence, 0 is printed on to the console.
Incorrect
SCP38860:
Instance overloaded method split(…) has below declarations:
1. public String[] split?(String regex, int limit) {…}: It returns the String[] after splitting this string around matches of the given regex.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
A. If the limit is positive then the pattern will be applied at most (limit – 1) times, the array’s length will be no greater than limit, and the array’s last entry will contain all input beyond the last matched delimiter. For example:
“BAZAAR”.split(“A”, 1); returns [“BAZAAR”] as pattern is applied 1 – 1 = 0 time.
“BAZAAR”.split(“A”, 2); returns [“B”,”ZAAR”] as pattern is applied 2 – 1 = 1 time.
“BAZAAR”.split(“A”, 3); returns [“B”,”Z”,”AR”] as pattern is applied 3 – 1 = 2 times.
“BAZAAR”.split(“A”, 4); returns [“B”,”Z”,””,”R”] as pattern is applied 4 – 1 = 3 times.
“BAZAAR”.split(“A”, 4); returns [“B”,”Z”,””,”R”] as pattern needs to be applied 5 – 1 = 4 times but it is applied 3 times (which is max).
“:”.split(“:”, 2); returns [“”,””] as pattern is applied (2 – 1) time and there is an empty space (“”) before and after “:”, so resulting array contains two empty strings.
B. If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. For example,
“BAZAAR”.split(“A”, 0); returns [“B”,”Z”,””,”R”].
“:”.split(“:”, 0); returns blank array as both the empty strings are discarded.
C. If the limit is negative then the pattern will be applied as many times as possible and the array can have any length. For example,
“BAZAAR”.split(“A”, -10); returns [“B”,”Z”,””,”R”] as pattern is applied max times, which is 3.
“:”.split(“:”, -2); returns [“”,””] as pattern is applied max times, which is 3.
2. public String[] split?(String regex) {…}: It returns the String[] after splitting this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.Â
“BAZAAR”.split(“A”); returns [“B”,”Z”,””,”R”] as this statement is equivalent to “BAZAAR”.split(“A”, 0);.
“:”.split(“:”); returns blank array as this statement is equivalent to “:”.split(“:”, 0);.
Let’s solve the given expression based on above points:
txt.split(“an”).length
=”an”.split(“an”).length
=[].length //”an”.split(“an”) returns blank array as both the empty strings are discarded.
0
Hence, 0 is printed on to the console.
Unattempted
SCP38860:
Instance overloaded method split(…) has below declarations:
1. public String[] split?(String regex, int limit) {…}: It returns the String[] after splitting this string around matches of the given regex.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
A. If the limit is positive then the pattern will be applied at most (limit – 1) times, the array’s length will be no greater than limit, and the array’s last entry will contain all input beyond the last matched delimiter. For example:
“BAZAAR”.split(“A”, 1); returns [“BAZAAR”] as pattern is applied 1 – 1 = 0 time.
“BAZAAR”.split(“A”, 2); returns [“B”,”ZAAR”] as pattern is applied 2 – 1 = 1 time.
“BAZAAR”.split(“A”, 3); returns [“B”,”Z”,”AR”] as pattern is applied 3 – 1 = 2 times.
“BAZAAR”.split(“A”, 4); returns [“B”,”Z”,””,”R”] as pattern is applied 4 – 1 = 3 times.
“BAZAAR”.split(“A”, 4); returns [“B”,”Z”,””,”R”] as pattern needs to be applied 5 – 1 = 4 times but it is applied 3 times (which is max).
“:”.split(“:”, 2); returns [“”,””] as pattern is applied (2 – 1) time and there is an empty space (“”) before and after “:”, so resulting array contains two empty strings.
B. If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. For example,
“BAZAAR”.split(“A”, 0); returns [“B”,”Z”,””,”R”].
“:”.split(“:”, 0); returns blank array as both the empty strings are discarded.
C. If the limit is negative then the pattern will be applied as many times as possible and the array can have any length. For example,
“BAZAAR”.split(“A”, -10); returns [“B”,”Z”,””,”R”] as pattern is applied max times, which is 3.
“:”.split(“:”, -2); returns [“”,””] as pattern is applied max times, which is 3.
2. public String[] split?(String regex) {…}: It returns the String[] after splitting this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.Â
“BAZAAR”.split(“A”); returns [“B”,”Z”,””,”R”] as this statement is equivalent to “BAZAAR”.split(“A”, 0);.
“:”.split(“:”); returns blank array as this statement is equivalent to “:”.split(“:”, 0);.
Let’s solve the given expression based on above points:
txt.split(“an”).length
=”an”.split(“an”).length
=[].length //”an”.split(“an”) returns blank array as both the empty strings are discarded.
0
Hence, 0 is printed on to the console.
Question 4 of 65
4. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
String [][] arr = { {“%”, “$$”}, {“***”, “@@@@”, “#####”}};
for(String [] str : arr) {
for(String s : str) {
System.out.println(s);
if(s.length() == 4) //Line n1
break; //Line n2
}
break; //Line n3
}
}
}
What will be the result of compiling and executing Test class?
Correct
SCP17598:
Variable ‘arr’ refers to a two-dimensional array. for-each loops are used to iterate the given array.
In 1st iteration of outer loop, str refers to one-dimensional String array {“%”, “$$”}.
In 1st iteration of inner loop, s refers to “%” and “%” will be printed on to the console. Boolean expression of Line n1 evaluates to false so Line n2 is not executed.
In 2nd iteration of inner loop, s refers to “$$” and “$$” will be printed on to the console. Boolean expression of Line n1 evaluates to false so Line n2 is not executed.
Iteration of inner for-each loop is over and control executes Line n3. break; statement at Line n3 terminates the outer loop and program ends successfully.
So, output is:
%
$$
Incorrect
SCP17598:
Variable ‘arr’ refers to a two-dimensional array. for-each loops are used to iterate the given array.
In 1st iteration of outer loop, str refers to one-dimensional String array {“%”, “$$”}.
In 1st iteration of inner loop, s refers to “%” and “%” will be printed on to the console. Boolean expression of Line n1 evaluates to false so Line n2 is not executed.
In 2nd iteration of inner loop, s refers to “$$” and “$$” will be printed on to the console. Boolean expression of Line n1 evaluates to false so Line n2 is not executed.
Iteration of inner for-each loop is over and control executes Line n3. break; statement at Line n3 terminates the outer loop and program ends successfully.
So, output is:
%
$$
Unattempted
SCP17598:
Variable ‘arr’ refers to a two-dimensional array. for-each loops are used to iterate the given array.
In 1st iteration of outer loop, str refers to one-dimensional String array {“%”, “$$”}.
In 1st iteration of inner loop, s refers to “%” and “%” will be printed on to the console. Boolean expression of Line n1 evaluates to false so Line n2 is not executed.
In 2nd iteration of inner loop, s refers to “$$” and “$$” will be printed on to the console. Boolean expression of Line n1 evaluates to false so Line n2 is not executed.
Iteration of inner for-each loop is over and control executes Line n3. break; statement at Line n3 terminates the outer loop and program ends successfully.
So, output is:
%
$$
Question 5 of 65
5. Question
Consider the following interface declaration:
public interface I1 {
void m1() throws java.io.IOException;
}
Which of the following incorrectly implements interface I1?
Correct
SCP67998:
NOTE: Question is asking for “incorrect” implementation and not “correct” implementation.
java.io.FileNotFoundException extends java.io.IOException
and
java.io.IOException extends java.lang.Exception
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.
Based on above rules, class C4 incorrectly implements method m1() of interface I1 as it declares to throw Exception, which is super class of java.io.IOException.
Incorrect
SCP67998:
NOTE: Question is asking for “incorrect” implementation and not “correct” implementation.
java.io.FileNotFoundException extends java.io.IOException
and
java.io.IOException extends java.lang.Exception
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.
Based on above rules, class C4 incorrectly implements method m1() of interface I1 as it declares to throw Exception, which is super class of java.io.IOException.
Unattempted
SCP67998:
NOTE: Question is asking for “incorrect” implementation and not “correct” implementation.
java.io.FileNotFoundException extends java.io.IOException
and
java.io.IOException extends java.lang.Exception
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.
Based on above rules, class C4 incorrectly implements method m1() of interface I1 as it declares to throw Exception, which is super class of java.io.IOException.
Question 6 of 65
6. Question
Consider below code of TestBook.java file:
package com.udayankhattry.ocp1;
class Book {
private String name;
private String author;
public class TestBook {
public static void main(String[] args) {
private Book book = new Book(“Head First Java”, “Kathy Sierra”);
System.out.println(book.getName());
System.out.println(book.getAuthor());
}
}
What will be the result of compiling and executing above code?
Correct
SCP50325:
Variable ‘book’ in main(String[]) method of TestBook class cannot be declared private as it is a local variable. Hence, there is a compilation error in TestBook class.Â
Only final modifier can be used with local variables.
Incorrect
SCP50325:
Variable ‘book’ in main(String[]) method of TestBook class cannot be declared private as it is a local variable. Hence, there is a compilation error in TestBook class.Â
Only final modifier can be used with local variables.
Unattempted
SCP50325:
Variable ‘book’ in main(String[]) method of TestBook class cannot be declared private as it is a local variable. Hence, there is a compilation error in TestBook class.Â
Only final modifier can be used with local variables.
Contents of module-info.java file:
module com.udayankhattry.modularity {
}
Contents of Main.java file:
package com.udayankhattry.ocp1;
public class Main {
public static void main(String… args) {
System.out.println(“MODULAR APPLICATION”);
}
}
Which of the following jar commands executed from C:\, will package the above module such that the execution of the command:
java -p jars -m com.udayankhattry.modularity
prints MODULAR APPLICATION on to the console?
Correct
SCP34840:
Expected output from the given Java command C:\>java -p jars -m com.udayankhattry.modularity is: MODULAR APPLICATION
Please note that in the above command class name to execute (com.udayankhattry.ocp1.Main) is not specified in the -m option, which means META-INF\MANIFEST.MF file must have below entry for the main class:
Main-Class: com.udayankhattry.ocp1.Main
To create this entry in jar file -e or –main-class option of jar command is used. Out of the given 4 options, only one command has -e option:
jar -cfe jars\test.jar com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
And hence it is the correct option.
Let’s see how above jar command works:
-c or –create: Create the archive
-f or –file=FILE: The archive file name
-e or –main-class=CLASSNAME: The application entry point for stand-alone applications bundled into a modular, or executable, jar archive
-C DIR: Change to the specified directory and include the following file
Hence,
jar –create –file=jars\test.jar –main-class=com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar –create –file jars\test.jar –main-class com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar -c -f jars\test.jar -e com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar -cfe jars\test.jar com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
are exactly same commands and works as below:
Create a new archive ‘jars\test.jar’ and set the entry point to ‘com.udayankhattry.ocp1.Main’ class.
-C classes\com.udayankhattry.modularity . instructs jar tool to change to the ‘classes\com.udayankhattry.modularity’ directory and put all compiled files from this directory in the JAR file.
Incorrect
SCP34840:
Expected output from the given Java command C:\>java -p jars -m com.udayankhattry.modularity is: MODULAR APPLICATION
Please note that in the above command class name to execute (com.udayankhattry.ocp1.Main) is not specified in the -m option, which means META-INF\MANIFEST.MF file must have below entry for the main class:
Main-Class: com.udayankhattry.ocp1.Main
To create this entry in jar file -e or –main-class option of jar command is used. Out of the given 4 options, only one command has -e option:
jar -cfe jars\test.jar com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
And hence it is the correct option.
Let’s see how above jar command works:
-c or –create: Create the archive
-f or –file=FILE: The archive file name
-e or –main-class=CLASSNAME: The application entry point for stand-alone applications bundled into a modular, or executable, jar archive
-C DIR: Change to the specified directory and include the following file
Hence,
jar –create –file=jars\test.jar –main-class=com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar –create –file jars\test.jar –main-class com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar -c -f jars\test.jar -e com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar -cfe jars\test.jar com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
are exactly same commands and works as below:
Create a new archive ‘jars\test.jar’ and set the entry point to ‘com.udayankhattry.ocp1.Main’ class.
-C classes\com.udayankhattry.modularity . instructs jar tool to change to the ‘classes\com.udayankhattry.modularity’ directory and put all compiled files from this directory in the JAR file.
Unattempted
SCP34840:
Expected output from the given Java command C:\>java -p jars -m com.udayankhattry.modularity is: MODULAR APPLICATION
Please note that in the above command class name to execute (com.udayankhattry.ocp1.Main) is not specified in the -m option, which means META-INF\MANIFEST.MF file must have below entry for the main class:
Main-Class: com.udayankhattry.ocp1.Main
To create this entry in jar file -e or –main-class option of jar command is used. Out of the given 4 options, only one command has -e option:
jar -cfe jars\test.jar com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
And hence it is the correct option.
Let’s see how above jar command works:
-c or –create: Create the archive
-f or –file=FILE: The archive file name
-e or –main-class=CLASSNAME: The application entry point for stand-alone applications bundled into a modular, or executable, jar archive
-C DIR: Change to the specified directory and include the following file
Hence,
jar –create –file=jars\test.jar –main-class=com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar –create –file jars\test.jar –main-class com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar -c -f jars\test.jar -e com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
OR
jar -cfe jars\test.jar com.udayankhattry.ocp1.Main -C classes\com.udayankhattry.modularity .
are exactly same commands and works as below:
Create a new archive ‘jars\test.jar’ and set the entry point to ‘com.udayankhattry.ocp1.Main’ class.
-C classes\com.udayankhattry.modularity . instructs jar tool to change to the ‘classes\com.udayankhattry.modularity’ directory and put all compiled files from this directory in the JAR file.
Question 8 of 65
8. Question
Given below the directory/file structure on Windows platform:
C:
+—codes
| \—currency
| | module-info.java
| |
| \—com
| \—udayankhattry
| \—ocp1
| Currency.java
|
\—classes
And consider the command to be executed from C:\
javac -d classes _______________ codes -m currency
Which of the options can be used to fill above blank such that there is no error on executing above command?
Correct
SCP45519:
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 ‘codes’ 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 ‘classes’ 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’.
Let’s check all the options one by one:
–module-path ? –module-source-path is missing. –module-path is same as -p and it expects path of compiled classes or jar files containing compiled classes.
–module-source-path ? Correct.
–path ? –path is not a valid option of javac command.
–source-code-path ? –source-code-path is not a valid option of javac command.
–source ? –source is not a valid option of javac command.
-p ? –module-source-path is missing. -p is same as –module-path and it expects path of compiled classes or jar files containing compiled classes.
Incorrect
SCP45519:
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 ‘codes’ 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 ‘classes’ 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’.
Let’s check all the options one by one:
–module-path ? –module-source-path is missing. –module-path is same as -p and it expects path of compiled classes or jar files containing compiled classes.
–module-source-path ? Correct.
–path ? –path is not a valid option of javac command.
–source-code-path ? –source-code-path is not a valid option of javac command.
–source ? –source is not a valid option of javac command.
-p ? –module-source-path is missing. -p is same as –module-path and it expects path of compiled classes or jar files containing compiled classes.
Unattempted
SCP45519:
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 ‘codes’ 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 ‘classes’ 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’.
Let’s check all the options one by one:
–module-path ? –module-source-path is missing. –module-path is same as -p and it expects path of compiled classes or jar files containing compiled classes.
–module-source-path ? Correct.
–path ? –path is not a valid option of javac command.
–source-code-path ? –source-code-path is not a valid option of javac command.
–source ? –source is not a valid option of javac command.
-p ? –module-source-path is missing. -p is same as –module-path and it expects path of compiled classes or jar files containing compiled classes.
Question 9 of 65
9. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
interface M {
public static void log() {
System.out.println(“M”);
}
}
abstract class A {
public static void log() {
System.out.println(“N”);
}
}
class MyClass extends A implements M {}
public class Test {
public static void main(String[] args) {
M obj1 = new MyClass();
obj1.log(); //Line n1
A obj2 = new MyClass();
obj2.log(); //Line n2
MyClass obj3 = new MyClass();
obj3.log(); //Line n3
}
}
Which of the following statements is correct?
Correct
SCP58611:
As per Java 8, default and static methods were added in the interface. Interface M defines static method log(), there is no compilation error in interface M.
Also the scope of static log() method of M is limited to interface M and it can be invoked by using Interface name only, M.log().
Abstract class A also defines the static log() method. Abstract class can have 0 or more abstract methods. Hence, no compilation error in class A as well.
Super type reference variable can refer to an instance of Sub type, therefore the statement `M obj1 = new MyClass();` compiles successfully.
obj1 is of M type, hence `obj1.log();` tries to tag the static method of M but static log() method of M can only be invoked by using M.log();.
Therefore, Line n1 causes compilation error.
Scope of static log() method of A is not limited to class A only but MyClass also gets A.log() method in its scope.
There are different ways in which static method of an abstract class can be accessed:
1. By using the name of the abstract class: M.log(); //Preferred way
2. By using the reference variable of abstract class: A o1 = null; o1.log();
3. By using the name of the subclass: MyClass.log();
4. By using the reference variable of the subclass: MyClass o2 = null; o2.log();
Hence, Line n2 and Line n3 compile successfully.
Incorrect
SCP58611:
As per Java 8, default and static methods were added in the interface. Interface M defines static method log(), there is no compilation error in interface M.
Also the scope of static log() method of M is limited to interface M and it can be invoked by using Interface name only, M.log().
Abstract class A also defines the static log() method. Abstract class can have 0 or more abstract methods. Hence, no compilation error in class A as well.
Super type reference variable can refer to an instance of Sub type, therefore the statement `M obj1 = new MyClass();` compiles successfully.
obj1 is of M type, hence `obj1.log();` tries to tag the static method of M but static log() method of M can only be invoked by using M.log();.
Therefore, Line n1 causes compilation error.
Scope of static log() method of A is not limited to class A only but MyClass also gets A.log() method in its scope.
There are different ways in which static method of an abstract class can be accessed:
1. By using the name of the abstract class: M.log(); //Preferred way
2. By using the reference variable of abstract class: A o1 = null; o1.log();
3. By using the name of the subclass: MyClass.log();
4. By using the reference variable of the subclass: MyClass o2 = null; o2.log();
Hence, Line n2 and Line n3 compile successfully.
Unattempted
SCP58611:
As per Java 8, default and static methods were added in the interface. Interface M defines static method log(), there is no compilation error in interface M.
Also the scope of static log() method of M is limited to interface M and it can be invoked by using Interface name only, M.log().
Abstract class A also defines the static log() method. Abstract class can have 0 or more abstract methods. Hence, no compilation error in class A as well.
Super type reference variable can refer to an instance of Sub type, therefore the statement `M obj1 = new MyClass();` compiles successfully.
obj1 is of M type, hence `obj1.log();` tries to tag the static method of M but static log() method of M can only be invoked by using M.log();.
Therefore, Line n1 causes compilation error.
Scope of static log() method of A is not limited to class A only but MyClass also gets A.log() method in its scope.
There are different ways in which static method of an abstract class can be accessed:
1. By using the name of the abstract class: M.log(); //Preferred way
2. By using the reference variable of abstract class: A o1 = null; o1.log();
3. By using the name of the subclass: MyClass.log();
4. By using the reference variable of the subclass: MyClass o2 = null; o2.log();
Hence, Line n2 and Line n3 compile successfully.
Question 10 of 65
10. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
final boolean flag = false; //Line n1
while(flag) {
System.out.println(“Good Morning!”); //Line n2
}
}
}
Which of the following statements is correct for above code?
Correct
SCP22942:
`final boolean flag = false;` statement makes flag a compile time constant.Â
Compiler knows the value of flag, which is false at compile time and hence it gives “Unreachable Code” error for Line n2.
Incorrect
SCP22942:
`final boolean flag = false;` statement makes flag a compile time constant.Â
Compiler knows the value of flag, which is false at compile time and hence it gives “Unreachable Code” error for Line n2.
Unattempted
SCP22942:
`final boolean flag = false;` statement makes flag a compile time constant.Â
Compiler knows the value of flag, which is false at compile time and hence it gives “Unreachable Code” error for Line n2.
Question 11 of 65
11. Question
Consider below codes of 4 java files:
//A.java
package com.udayankhattry.ocp1;
public class A {
public void print() {
System.out.println(“A”);
}
}
//B.java
package com.udayankhattry.ocp1;
public class B extends A {
public void print() {
System.out.println(“B”);
}
}
//C.java
package com.udayankhattry.ocp1;
public class C extends A {
public void print() {
System.out.println(“C”);
}
}
//Test.java
package com.udayankhattry.ocp1.test;
import com.udayankhattry.ocp1.*;
public class Test {
public static void main(String[] args) {
A obj1 = new C();
A obj2 = new B();
C obj3 = (C)obj1;
C obj4 = (C)obj2;
obj3.print();
}
}
What will be the result of compiling and executing Test class?
Correct
SCP82361:
Class A, B and C are declared public and are inside same package ‘com.udayankhattry.ocp1’. Method print() of class A has correctly been overridden by B and C.
print() method is public so no issues in accessing it anywhere.
Let’s check the code inside main method.
A obj1 = new C(); => obj1 refers to an instance of C class, it is polymorphism.Â
A obj2 = new B(); => obj2 refers to an instance of B class, it is polymorphism.Â
C obj3 = (C)obj1; => obj1 actually refers to an instance of C class, so at runtime obj3 (C type) will refer to an instance of C class. As obj1 is of A type so explicit typecasting is necessary.Â
C obj4 = (C)obj2; => obj2 actually refers to an instance of B class, so at runtime obj4 (C type) will refer to an instance of B class. B and C are siblings and can’t refer to each other, so this statement will throw ClassCastException at runtime.
Incorrect
SCP82361:
Class A, B and C are declared public and are inside same package ‘com.udayankhattry.ocp1’. Method print() of class A has correctly been overridden by B and C.
print() method is public so no issues in accessing it anywhere.
Let’s check the code inside main method.
A obj1 = new C(); => obj1 refers to an instance of C class, it is polymorphism.Â
A obj2 = new B(); => obj2 refers to an instance of B class, it is polymorphism.Â
C obj3 = (C)obj1; => obj1 actually refers to an instance of C class, so at runtime obj3 (C type) will refer to an instance of C class. As obj1 is of A type so explicit typecasting is necessary.Â
C obj4 = (C)obj2; => obj2 actually refers to an instance of B class, so at runtime obj4 (C type) will refer to an instance of B class. B and C are siblings and can’t refer to each other, so this statement will throw ClassCastException at runtime.
Unattempted
SCP82361:
Class A, B and C are declared public and are inside same package ‘com.udayankhattry.ocp1’. Method print() of class A has correctly been overridden by B and C.
print() method is public so no issues in accessing it anywhere.
Let’s check the code inside main method.
A obj1 = new C(); => obj1 refers to an instance of C class, it is polymorphism.Â
A obj2 = new B(); => obj2 refers to an instance of B class, it is polymorphism.Â
C obj3 = (C)obj1; => obj1 actually refers to an instance of C class, so at runtime obj3 (C type) will refer to an instance of C class. As obj1 is of A type so explicit typecasting is necessary.Â
C obj4 = (C)obj2; => obj2 actually refers to an instance of B class, so at runtime obj4 (C type) will refer to an instance of B class. B and C are siblings and can’t refer to each other, so this statement will throw ClassCastException at runtime.
public class Test {
public static void main(String[] args) {
List places = new ArrayList<>();
places.add(“Austin”);
places.add(“Okinawa”);
places.add(“Giza”);
places.add(“Manila”);
places.add(“Batam”);
places.add(“Giza”);
What will be the result of compiling and executing Test class?
Correct
SCP37729:
remove(Object) method of List interface removes the first occurrence of the specified element from the list, if it is present. If this list does not contain the element, it is unchanged. remove(Object) method returns true, if removal was successful otherwise false.
Initially list has: [Austin, Okinawa, Giza, Manila, Batam, Giza]. places.remove(“Giza”) removes the first occurrence of “Giza” and after the successful removal, list has: [Austin, Okinawa, Manila, Batam, Giza]. places.remove(“Giza”) returns true, control goes inside if block and executes places.remove(“Austin”);
places list contains “Austin”, so after the removal list has: [Okinawa, Manila, Batam, Giza].
Incorrect
SCP37729:
remove(Object) method of List interface removes the first occurrence of the specified element from the list, if it is present. If this list does not contain the element, it is unchanged. remove(Object) method returns true, if removal was successful otherwise false.
Initially list has: [Austin, Okinawa, Giza, Manila, Batam, Giza]. places.remove(“Giza”) removes the first occurrence of “Giza” and after the successful removal, list has: [Austin, Okinawa, Manila, Batam, Giza]. places.remove(“Giza”) returns true, control goes inside if block and executes places.remove(“Austin”);
places list contains “Austin”, so after the removal list has: [Okinawa, Manila, Batam, Giza].
Unattempted
SCP37729:
remove(Object) method of List interface removes the first occurrence of the specified element from the list, if it is present. If this list does not contain the element, it is unchanged. remove(Object) method returns true, if removal was successful otherwise false.
Initially list has: [Austin, Okinawa, Giza, Manila, Batam, Giza]. places.remove(“Giza”) removes the first occurrence of “Giza” and after the successful removal, list has: [Austin, Okinawa, Manila, Batam, Giza]. places.remove(“Giza”) returns true, control goes inside if block and executes places.remove(“Austin”);
places list contains “Austin”, so after the removal list has: [Okinawa, Manila, Batam, Giza].
Question 13 of 65
13. Question
super keyword in java is used to:
Correct
SCP26691:
‘super’ refers to parent class object and ‘this’ refers to currently executing object.
Incorrect
SCP26691:
‘super’ refers to parent class object and ‘this’ refers to currently executing object.
Unattempted
SCP26691:
‘super’ refers to parent class object and ‘this’ refers to currently executing object.
Question 14 of 65
14. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
String [] arr = {“A”, “B”, “C”, “D”, “E”};
for(/*INSERT*/) {
System.out.print(arr[n]);
}
}
}
Which option, if used to replace /*INSERT*/, on execution will print ACE on to the console?
Correct
SCP84984:
You have to print element at index 0, 2 and 4, which means index must start with 0 and step expression should increment the index by 2.
Hence, int n = 0; n < arr.length; n += 2 is the correct option.
Incorrect
SCP84984:
You have to print element at index 0, 2 and 4, which means index must start with 0 and step expression should increment the index by 2.
Hence, int n = 0; n < arr.length; n += 2 is the correct option.
Unattempted
SCP84984:
You have to print element at index 0, 2 and 4, which means index must start with 0 and step expression should increment the index by 2.
Hence, int n = 0; n < arr.length; n += 2 is the correct option.
Question 15 of 65
15. Question
Consider below code of Test.java file:
class Test {
public static void main(String [] args) {
final var x = 10; //Line n1
byte b = x + 10; //Line n2
System.out.println(b);
}
}
Which of the following commands will print 20 on to the console?
Select ALL that apply.
Correct
SCP43832:
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.
Hence at Line n1, java compiler automatically infers x to be of int type as right side expression is int literal.
Line n2 compiles successfully. As x is a final variable, so x + 10 is a constant expression. If you are working with constant expression and the resultant value of the constant expression is within the range, then resultant value is implicitly casted. In this case, resultant value 20 is implicitly casted.
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
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 [])’.
`java Test.java` prints 20 on to the console.
`java –source 11 Test.java` instructs the java command to process the Test.java file as Java 11 source code. As var reserved type works JDK 10 onwards, hence this command also prints 20 on to the console.
`java –source 10 Test.java` instructs the java command to process the Test.java file as Java 10 source code. As var reserved type works JDK 10 onwards, hence this command also prints 20 on to the console.
`java –source 9 Test.java` instructs the java command to process the Test.java file as Java 9 source code. As var reserved type works JDK 10 onwards, hence this command causes error.
`java –source 8 Test.java` instructs the java command to process the Test.java file as Java 8 source code. As var reserved type works JDK 10 onwards, hence this command causes error.
SCP43832:
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.
Hence at Line n1, java compiler automatically infers x to be of int type as right side expression is int literal.
Line n2 compiles successfully. As x is a final variable, so x + 10 is a constant expression. If you are working with constant expression and the resultant value of the constant expression is within the range, then resultant value is implicitly casted. In this case, resultant value 20 is implicitly casted.
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
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 [])’.
`java Test.java` prints 20 on to the console.
`java –source 11 Test.java` instructs the java command to process the Test.java file as Java 11 source code. As var reserved type works JDK 10 onwards, hence this command also prints 20 on to the console.
`java –source 10 Test.java` instructs the java command to process the Test.java file as Java 10 source code. As var reserved type works JDK 10 onwards, hence this command also prints 20 on to the console.
`java –source 9 Test.java` instructs the java command to process the Test.java file as Java 9 source code. As var reserved type works JDK 10 onwards, hence this command causes error.
`java –source 8 Test.java` instructs the java command to process the Test.java file as Java 8 source code. As var reserved type works JDK 10 onwards, hence this command causes error.
SCP43832:
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.
Hence at Line n1, java compiler automatically infers x to be of int type as right side expression is int literal.
Line n2 compiles successfully. As x is a final variable, so x + 10 is a constant expression. If you are working with constant expression and the resultant value of the constant expression is within the range, then resultant value is implicitly casted. In this case, resultant value 20 is implicitly casted.
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
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 [])’.
`java Test.java` prints 20 on to the console.
`java –source 11 Test.java` instructs the java command to process the Test.java file as Java 11 source code. As var reserved type works JDK 10 onwards, hence this command also prints 20 on to the console.
`java –source 10 Test.java` instructs the java command to process the Test.java file as Java 10 source code. As var reserved type works JDK 10 onwards, hence this command also prints 20 on to the console.
`java –source 9 Test.java` instructs the java command to process the Test.java file as Java 9 source code. As var reserved type works JDK 10 onwards, hence this command causes error.
`java –source 8 Test.java` instructs the java command to process the Test.java file as Java 8 source code. As var reserved type works JDK 10 onwards, hence this command causes error.
abstract class Animal {}
class Dog extends Animal{}
public class Test {
public static void main(String [] args) {
List list = new ArrayList();
list.add(0, new Dog());
System.out.println(list.size() > 0);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP16193:
List is super type and ArrayList is sub type, hence List l = new ArrayList(); is valid syntax.Â
Animal is super type and Dog is sub type, hence Animal a = new Dog(); is valid syntax. Both depicts Polymorphism.
But in generics syntax, Parameterized types are not polymorphic, this means ArrayList is not super type of ArrayList. Remember this point. So below syntaxes are not allowed:Â
ArrayList list = new ArrayList(); OR List list = new ArrayList();
Incorrect
SCP16193:
List is super type and ArrayList is sub type, hence List l = new ArrayList(); is valid syntax.Â
Animal is super type and Dog is sub type, hence Animal a = new Dog(); is valid syntax. Both depicts Polymorphism.
But in generics syntax, Parameterized types are not polymorphic, this means ArrayList is not super type of ArrayList. Remember this point. So below syntaxes are not allowed:Â
ArrayList list = new ArrayList(); OR List list = new ArrayList();
Unattempted
SCP16193:
List is super type and ArrayList is sub type, hence List l = new ArrayList(); is valid syntax.Â
Animal is super type and Dog is sub type, hence Animal a = new Dog(); is valid syntax. Both depicts Polymorphism.
But in generics syntax, Parameterized types are not polymorphic, this means ArrayList is not super type of ArrayList. Remember this point. So below syntaxes are not allowed:Â
ArrayList list = new ArrayList(); OR List list = new ArrayList();
Question 17 of 65
17. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
static int i1 = 10;
int i2 = 20;
What will be the result of compiling and executing Test class?
Correct
SCP65816:
i1 is a static variable and i2 is an instance variable. Preferred way to access static variable i1 inside add() method is by using ‘i1’ or ‘Test.i1’. Even though ‘this.i1’ is not the recommended way but it works.
And instance variable i2 can be accessed inside add() method by using ‘i2’ or ‘this.i2’. Hence, Line n1 compiles successfully.
As add() is an instance method of Test class, so an instance of Test class is needed to invoke the add() method. `new Test().add()` correctly invokes the add() method of Test class and returns 30. Line n2 prints 30 on to the console.
Incorrect
SCP65816:
i1 is a static variable and i2 is an instance variable. Preferred way to access static variable i1 inside add() method is by using ‘i1’ or ‘Test.i1’. Even though ‘this.i1’ is not the recommended way but it works.
And instance variable i2 can be accessed inside add() method by using ‘i2’ or ‘this.i2’. Hence, Line n1 compiles successfully.
As add() is an instance method of Test class, so an instance of Test class is needed to invoke the add() method. `new Test().add()` correctly invokes the add() method of Test class and returns 30. Line n2 prints 30 on to the console.
Unattempted
SCP65816:
i1 is a static variable and i2 is an instance variable. Preferred way to access static variable i1 inside add() method is by using ‘i1’ or ‘Test.i1’. Even though ‘this.i1’ is not the recommended way but it works.
And instance variable i2 can be accessed inside add() method by using ‘i2’ or ‘this.i2’. Hence, Line n1 compiles successfully.
As add() is an instance method of Test class, so an instance of Test class is needed to invoke the add() method. `new Test().add()` correctly invokes the add() method of Test class and returns 30. Line n2 prints 30 on to the console.
Question 18 of 65
18. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
import java.util.*;
public class Test {
public static void main(String[] args) {
String [] arr = {“EARTH”, “MOON”, “SUN”, “PLUTO”};
var list = /*INSERT*/;
list.set(3, “JUPITER”); //Line n1
list.forEach(str -> System.out.println(str)); //Line n2
}
}
Which of the following options can replace /*INSERT*/ such that output is:
EARTH
MOON
SUN
JUPITER
Select ALL that apply.
Correct
SCP57581:
Arrays.asList(…) method returns a fixed-size list backed by the specified array and as list is backed by the specified array therefore, you cannot add or remove elements from this list. Using add/remove methods cause an exception at runtime. But you can invoke the set(int index, E element) method on the returned list.
This behavior is bit different from the List.of(…) method, which returns unmodifiable list, hence calling add/remove/set methods on the unmodifiable list throws an exception at runtime.
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.
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
If you replace /*INSERT*/ with List.of(arr), then for the statement `var list = List.of(arr);`, list refers to a List of String type.
Let’s check all the options one by one:
List.of(arr) ? Line n1 will throw an exception at runtime.
Arrays.asList(arr) ? set(…) method can be invoked on the list object returned by Arrays.asList(arr) method. Line n1 will change the last list element from “PLUTO” to “JUPITER”. Line n2 will display the expected output.
new ArrayList<>(List.of(arr)) ? It constructs the ArrayList instance containing the elements of the specified collection (list object returned by List.of(arr)). This ArrayList object is not backed by the passed collection and hence can be modified without any issues. Line n1 will change the last list element from “PLUTO” to “JUPITER”. Line n2 will display the expected output.
ArrayList.of(arr) ? static overloaded methods of(…) were added to List interface in Java 9 and can only be invoked by using List.of(…). This statement causes compilation error.
new ArrayList<>(ArrayList.of(arr)) ? static overloaded methods of(…) were added to List interface in Java 9 and can only be invoked by using List.of(…). This statement causes compilation error.
Incorrect
SCP57581:
Arrays.asList(…) method returns a fixed-size list backed by the specified array and as list is backed by the specified array therefore, you cannot add or remove elements from this list. Using add/remove methods cause an exception at runtime. But you can invoke the set(int index, E element) method on the returned list.
This behavior is bit different from the List.of(…) method, which returns unmodifiable list, hence calling add/remove/set methods on the unmodifiable list throws an exception at runtime.
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.
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
If you replace /*INSERT*/ with List.of(arr), then for the statement `var list = List.of(arr);`, list refers to a List of String type.
Let’s check all the options one by one:
List.of(arr) ? Line n1 will throw an exception at runtime.
Arrays.asList(arr) ? set(…) method can be invoked on the list object returned by Arrays.asList(arr) method. Line n1 will change the last list element from “PLUTO” to “JUPITER”. Line n2 will display the expected output.
new ArrayList<>(List.of(arr)) ? It constructs the ArrayList instance containing the elements of the specified collection (list object returned by List.of(arr)). This ArrayList object is not backed by the passed collection and hence can be modified without any issues. Line n1 will change the last list element from “PLUTO” to “JUPITER”. Line n2 will display the expected output.
ArrayList.of(arr) ? static overloaded methods of(…) were added to List interface in Java 9 and can only be invoked by using List.of(…). This statement causes compilation error.
new ArrayList<>(ArrayList.of(arr)) ? static overloaded methods of(…) were added to List interface in Java 9 and can only be invoked by using List.of(…). This statement causes compilation error.
Unattempted
SCP57581:
Arrays.asList(…) method returns a fixed-size list backed by the specified array and as list is backed by the specified array therefore, you cannot add or remove elements from this list. Using add/remove methods cause an exception at runtime. But you can invoke the set(int index, E element) method on the returned list.
This behavior is bit different from the List.of(…) method, which returns unmodifiable list, hence calling add/remove/set methods on the unmodifiable list throws an exception at runtime.
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.
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
If you replace /*INSERT*/ with List.of(arr), then for the statement `var list = List.of(arr);`, list refers to a List of String type.
Let’s check all the options one by one:
List.of(arr) ? Line n1 will throw an exception at runtime.
Arrays.asList(arr) ? set(…) method can be invoked on the list object returned by Arrays.asList(arr) method. Line n1 will change the last list element from “PLUTO” to “JUPITER”. Line n2 will display the expected output.
new ArrayList<>(List.of(arr)) ? It constructs the ArrayList instance containing the elements of the specified collection (list object returned by List.of(arr)). This ArrayList object is not backed by the passed collection and hence can be modified without any issues. Line n1 will change the last list element from “PLUTO” to “JUPITER”. Line n2 will display the expected output.
ArrayList.of(arr) ? static overloaded methods of(…) were added to List interface in Java 9 and can only be invoked by using List.of(…). This statement causes compilation error.
new ArrayList<>(ArrayList.of(arr)) ? static overloaded methods of(…) were added to List interface in Java 9 and can only be invoked by using List.of(…). This statement causes compilation error.
public class Test {
public static void main(String[] args) {
List objects = new ArrayList<>();
objects.add(“Watch”);
objects.add(“Arrow”);
objects.add(“Anchor”);
objects.add(“Drum”);
What will be the result of compiling and executing Test class?
Correct
SCP75188:
If you want to remove the items from ArrayList, while using Iterator or ListIterator, then use Iterator.remove() or ListIterator.remove() method and NOT List.remove() method.
In this case ListIterator.remove() method is used. startsWith(“A”) returns true for “Arrow” and “Anchor” so these elements are removed from the list. In the output, [Watch, Drum] is displayed.
Incorrect
SCP75188:
If you want to remove the items from ArrayList, while using Iterator or ListIterator, then use Iterator.remove() or ListIterator.remove() method and NOT List.remove() method.
In this case ListIterator.remove() method is used. startsWith(“A”) returns true for “Arrow” and “Anchor” so these elements are removed from the list. In the output, [Watch, Drum] is displayed.
Unattempted
SCP75188:
If you want to remove the items from ArrayList, while using Iterator or ListIterator, then use Iterator.remove() or ListIterator.remove() method and NOT List.remove() method.
In this case ListIterator.remove() method is used. startsWith(“A”) returns true for “Arrow” and “Anchor” so these elements are removed from the list. In the output, [Watch, Drum] is displayed.
public class TestEmployee {
public static void main(String[] args) {
Employee emp = new Employee();
System.out.println(emp.name + “:” + emp.age); //Line n2
}
}
What will be the result of compiling and executing TestEmployee class?
Correct
SCP51624:
Employee class has overloaded constructors: Employee() is a no-argument constructor and Employee(String, int) is a parameterized constructor.
A constructor can call another constructor by using this(…) and not the constructor name. Hence Line n1 causes compilation error.
As both Employee and TestEmployee classes are defined in the same package, hence emp.name and emp.age are valid syntaxes. Line n2 compiles successfully.
Incorrect
SCP51624:
Employee class has overloaded constructors: Employee() is a no-argument constructor and Employee(String, int) is a parameterized constructor.
A constructor can call another constructor by using this(…) and not the constructor name. Hence Line n1 causes compilation error.
As both Employee and TestEmployee classes are defined in the same package, hence emp.name and emp.age are valid syntaxes. Line n2 compiles successfully.
Unattempted
SCP51624:
Employee class has overloaded constructors: Employee() is a no-argument constructor and Employee(String, int) is a parameterized constructor.
A constructor can call another constructor by using this(…) and not the constructor name. Hence Line n1 causes compilation error.
As both Employee and TestEmployee classes are defined in the same package, hence emp.name and emp.age are valid syntaxes. Line n2 compiles successfully.
Question 21 of 65
21. Question
What will be the result of compiling and executing Test class?
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
String sport = “swimming”;
switch (sport) {
default:
System.out.println(“RUNNING”);
case “Tennis”:
System.out.println(“TENNIS”);
case “Swimming”:
System.out.println(“SWIMMING”);
case “Football”:
System.out.println(“FOOTBALL”);
break;
}
}
}
Correct
SCP27396:
“swimming” is different from “Swimming”, so there is no matching case available. default block is executed, “RUNNING” is printed on to the console. No break statement inside default, hence control enters in fall-through and executes remaining blocks until the break; is found or switch block ends. So in this case, it prints TENNIS, SWIMMING, FOOTBALL one after another and break; statement takes control out of switch block. main method ends and program terminates successfully.
Incorrect
SCP27396:
“swimming” is different from “Swimming”, so there is no matching case available. default block is executed, “RUNNING” is printed on to the console. No break statement inside default, hence control enters in fall-through and executes remaining blocks until the break; is found or switch block ends. So in this case, it prints TENNIS, SWIMMING, FOOTBALL one after another and break; statement takes control out of switch block. main method ends and program terminates successfully.
Unattempted
SCP27396:
“swimming” is different from “Swimming”, so there is no matching case available. default block is executed, “RUNNING” is printed on to the console. No break statement inside default, hence control enters in fall-through and executes remaining blocks until the break; is found or switch block ends. So in this case, it prints TENNIS, SWIMMING, FOOTBALL one after another and break; statement takes control out of switch block. main method ends and program terminates successfully.
Question 22 of 65
22. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
/*INSERT*/
public class Test {
public static void main(String[] args) {
MyInterface mi = () -> “”;
}
}
Which of the following interface definitions can replace /*INSERT*/ such that there is no compilation error?
Select ALL that apply.
Correct
SCP54299:
Target type of lambda expression must be a Functional interface.
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].
Let’s check which of the given options are Functional interfaces:
interface MyInterface {
  String toStr();
} ?
MyInterface has only one non-overriding abstract method [toStr()] and hence a Functional interface.
Given lambda expression `() -> “”` means method accepts no argument and returns a String object. It is a correct implementation of toStr() method.
interface MyInterface {
  String toStr();
  String toString();
} ?
MyInterface has only one non-overriding abstract method [toStr()] and toString() method is overriding abstract method, therefore it is also a valid Functional interface.
`() -> “”;` is the correct implementation of toStr() method.
interface MyInterface {
  Object toStr();
  String toString();
  static void print(String str) {
    System.out.println(str);
  }
} ?
MyInterface has only one non-overriding abstract method [toStr()] and toString() method is overriding abstract method & print(String) is the static method, therefore it is also a valid Functional interface.
`() -> “”;` is the correct implementation of toStr() method.
interface MyInterface {
  Object toStr();
  boolean equals(MyInterface);
} ?
My interface has two non-overriding abstract methods. Please note that `boolean equals(Object);` is overriding abstract method but `boolean equals(MyInterface);` is non-overriding abstract method.
interface MyInterface {
  String toString();
} ?
`String toString();` is overriding abstract method and hence in this case, MyInterface doesn’t contain non-overriding abstract method. Therefore it is not a Functional interface.
interface MyInterface {
  CharSequence test();
} ?
MyInterface has only one non-overriding abstract method [test()] and hence a Functional interface.
As String class implements CharSequence, therefore value returned by Lambda expression [“”] (String type) can easily be assigned to CharSequence reference.
`() -> “”;` is the correct implementation of `CharSequence test();`
interface MyInterface {
  StringBuilder m();
} ?
MyInterface has only one non-overriding abstract method [m()] and hence a Functional interface.
Value returned by Lambda expression [“”] (String type) can not be assigned to StringBuilder reference.
`() -> “”;` is NOT the correct implementation of `StringBuilder m();`
Incorrect
SCP54299:
Target type of lambda expression must be a Functional interface.
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].
Let’s check which of the given options are Functional interfaces:
interface MyInterface {
  String toStr();
} ?
MyInterface has only one non-overriding abstract method [toStr()] and hence a Functional interface.
Given lambda expression `() -> “”` means method accepts no argument and returns a String object. It is a correct implementation of toStr() method.
interface MyInterface {
  String toStr();
  String toString();
} ?
MyInterface has only one non-overriding abstract method [toStr()] and toString() method is overriding abstract method, therefore it is also a valid Functional interface.
`() -> “”;` is the correct implementation of toStr() method.
interface MyInterface {
  Object toStr();
  String toString();
  static void print(String str) {
    System.out.println(str);
  }
} ?
MyInterface has only one non-overriding abstract method [toStr()] and toString() method is overriding abstract method & print(String) is the static method, therefore it is also a valid Functional interface.
`() -> “”;` is the correct implementation of toStr() method.
interface MyInterface {
  Object toStr();
  boolean equals(MyInterface);
} ?
My interface has two non-overriding abstract methods. Please note that `boolean equals(Object);` is overriding abstract method but `boolean equals(MyInterface);` is non-overriding abstract method.
interface MyInterface {
  String toString();
} ?
`String toString();` is overriding abstract method and hence in this case, MyInterface doesn’t contain non-overriding abstract method. Therefore it is not a Functional interface.
interface MyInterface {
  CharSequence test();
} ?
MyInterface has only one non-overriding abstract method [test()] and hence a Functional interface.
As String class implements CharSequence, therefore value returned by Lambda expression [“”] (String type) can easily be assigned to CharSequence reference.
`() -> “”;` is the correct implementation of `CharSequence test();`
interface MyInterface {
  StringBuilder m();
} ?
MyInterface has only one non-overriding abstract method [m()] and hence a Functional interface.
Value returned by Lambda expression [“”] (String type) can not be assigned to StringBuilder reference.
`() -> “”;` is NOT the correct implementation of `StringBuilder m();`
Unattempted
SCP54299:
Target type of lambda expression must be a Functional interface.
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].
Let’s check which of the given options are Functional interfaces:
interface MyInterface {
  String toStr();
} ?
MyInterface has only one non-overriding abstract method [toStr()] and hence a Functional interface.
Given lambda expression `() -> “”` means method accepts no argument and returns a String object. It is a correct implementation of toStr() method.
interface MyInterface {
  String toStr();
  String toString();
} ?
MyInterface has only one non-overriding abstract method [toStr()] and toString() method is overriding abstract method, therefore it is also a valid Functional interface.
`() -> “”;` is the correct implementation of toStr() method.
interface MyInterface {
  Object toStr();
  String toString();
  static void print(String str) {
    System.out.println(str);
  }
} ?
MyInterface has only one non-overriding abstract method [toStr()] and toString() method is overriding abstract method & print(String) is the static method, therefore it is also a valid Functional interface.
`() -> “”;` is the correct implementation of toStr() method.
interface MyInterface {
  Object toStr();
  boolean equals(MyInterface);
} ?
My interface has two non-overriding abstract methods. Please note that `boolean equals(Object);` is overriding abstract method but `boolean equals(MyInterface);` is non-overriding abstract method.
interface MyInterface {
  String toString();
} ?
`String toString();` is overriding abstract method and hence in this case, MyInterface doesn’t contain non-overriding abstract method. Therefore it is not a Functional interface.
interface MyInterface {
  CharSequence test();
} ?
MyInterface has only one non-overriding abstract method [test()] and hence a Functional interface.
As String class implements CharSequence, therefore value returned by Lambda expression [“”] (String type) can easily be assigned to CharSequence reference.
`() -> “”;` is the correct implementation of `CharSequence test();`
interface MyInterface {
  StringBuilder m();
} ?
MyInterface has only one non-overriding abstract method [m()] and hence a Functional interface.
Value returned by Lambda expression [“”] (String type) can not be assigned to StringBuilder reference.
`() -> “”;` is NOT the correct implementation of `StringBuilder m();`
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 val = 9;
System.out.println(val += 10 – -val– – –val);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP63443:
Given expression:
val += 10 – -val– – –val
val = val + 10 – -val– – –val
val = val + 10 – -(val–) – –val //Postfix operator has higher precedence than other available operators
val = val + 10 – (-(val–)) – (–val) //Unary minus and prefix operator has same preference
val = (val + 10) – (-(val–)) – (–val) // + and – have same preference and both are left associative, hence grouping + first.
val = ((val + 10) – (-(val–))) – (–val) //Grouping – next
Expression on right side of assignment operator has 2 parts: Left: ((val + 10) – (-(val–))) and Right: (–val). Expression on Left side needs to be evaluated first.
val = ((9 + 10) – (-(val–))) – (–val) //val=9
val = (19 – (-(val–))) – (–val) //val=9
val = (19 – (-9)) – (–val) //val=8
val = 28 – (–val) //val=8
val = 28 – 7 //val=7
val = 21
21 is assigned to val and 21 is printed on to the console as well.
Incorrect
SCP63443:
Given expression:
val += 10 – -val– – –val
val = val + 10 – -val– – –val
val = val + 10 – -(val–) – –val //Postfix operator has higher precedence than other available operators
val = val + 10 – (-(val–)) – (–val) //Unary minus and prefix operator has same preference
val = (val + 10) – (-(val–)) – (–val) // + and – have same preference and both are left associative, hence grouping + first.
val = ((val + 10) – (-(val–))) – (–val) //Grouping – next
Expression on right side of assignment operator has 2 parts: Left: ((val + 10) – (-(val–))) and Right: (–val). Expression on Left side needs to be evaluated first.
val = ((9 + 10) – (-(val–))) – (–val) //val=9
val = (19 – (-(val–))) – (–val) //val=9
val = (19 – (-9)) – (–val) //val=8
val = 28 – (–val) //val=8
val = 28 – 7 //val=7
val = 21
21 is assigned to val and 21 is printed on to the console as well.
Unattempted
SCP63443:
Given expression:
val += 10 – -val– – –val
val = val + 10 – -val– – –val
val = val + 10 – -(val–) – –val //Postfix operator has higher precedence than other available operators
val = val + 10 – (-(val–)) – (–val) //Unary minus and prefix operator has same preference
val = (val + 10) – (-(val–)) – (–val) // + and – have same preference and both are left associative, hence grouping + first.
val = ((val + 10) – (-(val–))) – (–val) //Grouping – next
Expression on right side of assignment operator has 2 parts: Left: ((val + 10) – (-(val–))) and Right: (–val). Expression on Left side needs to be evaluated first.
val = ((9 + 10) – (-(val–))) – (–val) //val=9
val = (19 – (-(val–))) – (–val) //val=9
val = (19 – (-9)) – (–val) //val=8
val = 28 – (–val) //val=8
val = 28 – 7 //val=7
val = 21
21 is assigned to val and 21 is printed on to the console as well.
public class Test {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(100);
list.add(7);
list.add(50);
list.add(17);
list.add(10);
list.add(5);
list.removeIf(a -> a % 10 == 0);
System.out.println(list);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP27946:
removeIf(Predicate) method was added as a default method in Collection interface in JDK 8 and it removes all the elements of this collection that satisfy the given predicate.
Interface java.util.function.Predicate declares below non-overriding abstract method:
boolean test(T t);
Lambda expression passed to removeIf(Predicate) method is: `a -> a % 10 == 0` and is a valid lambda expression for Predicate interface.
Predicate’s test method returns true for all the Integers divisible by 10, so all the list elements which are divisible by 10 (100, 50 and 10] are successfully removed by removeIf(Predicate) method.
`System.out.println(list);` prints remaining elements of the list and hence output is: [7, 17, 5]
Incorrect
SCP27946:
removeIf(Predicate) method was added as a default method in Collection interface in JDK 8 and it removes all the elements of this collection that satisfy the given predicate.
Interface java.util.function.Predicate declares below non-overriding abstract method:
boolean test(T t);
Lambda expression passed to removeIf(Predicate) method is: `a -> a % 10 == 0` and is a valid lambda expression for Predicate interface.
Predicate’s test method returns true for all the Integers divisible by 10, so all the list elements which are divisible by 10 (100, 50 and 10] are successfully removed by removeIf(Predicate) method.
`System.out.println(list);` prints remaining elements of the list and hence output is: [7, 17, 5]
Unattempted
SCP27946:
removeIf(Predicate) method was added as a default method in Collection interface in JDK 8 and it removes all the elements of this collection that satisfy the given predicate.
Interface java.util.function.Predicate declares below non-overriding abstract method:
boolean test(T t);
Lambda expression passed to removeIf(Predicate) method is: `a -> a % 10 == 0` and is a valid lambda expression for Predicate interface.
Predicate’s test method returns true for all the Integers divisible by 10, so all the list elements which are divisible by 10 (100, 50 and 10] are successfully removed by removeIf(Predicate) method.
`System.out.println(list);` prints remaining elements of the list and hence output is: [7, 17, 5]
Question 25 of 65
25. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
class Parent {
int var = 1000; // Line n1
int getVar() {
return var;
}
}
class Child extends Parent {
private int var = 2000; // Line n2
int getVar() {
return super.var; //Line n3
}
}
public class Test {
public static void main(String[] args) {
Child obj = new Child(); // Line n4
System.out.println(obj.var); // Line n5
}
}
There is a compilation error in the code.
Which three modifications, done independently, print 1000 on to the console?
Correct
SCP38442:
Subclass overrides the methods of superclass but it hides the variables of superclass.
Line n2 hides the variable created at Line n1, there is no rules related to hiding (type and access modifier can be changed).
Please note:
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. There is no compilation error in the code for using identifier ‘var’.
Line n5 causes compilation error as obj is of Child type and ‘var’ is declared private in Child class. Variable ‘var’ of Child class cannot be accessed outside the Child class.
Let’s check all the options one by one:
‘Change Line n1 to private int var = 1000;’ => It will not rectify the existing error of Line n5, in fact after this change, Line n3 will also cause compilation error.
‘Delete the Line n2’ => After deleting this line, obj.var at Line n5 will refer to variable ‘var’ of Parent class. Hence, output will be 1000 in this case.
‘Change Line n3 to return var;’ => This will have no effect to the output of the code, as getVar() method has not been invoked.
‘Change Line n4 to Parent obj = new Child();’ => After this modification, obj becomes Parent type, hence obj.var will refer to variable ‘var’ of Parent class. Hence, output will be 1000 in this case.
‘Delete the method getVar() from the Child class’ => This will have no effect to the output of the code, as getVar() method has not been invoked.
‘Change Line n5 to System.out.println(obj.getVar());’ => obj.getVar() will invoke the getVar() method of Child class and this method returns the variable value from Parent class (super.var). Hence, output will be 1000 in this case.
Incorrect
SCP38442:
Subclass overrides the methods of superclass but it hides the variables of superclass.
Line n2 hides the variable created at Line n1, there is no rules related to hiding (type and access modifier can be changed).
Please note:
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. There is no compilation error in the code for using identifier ‘var’.
Line n5 causes compilation error as obj is of Child type and ‘var’ is declared private in Child class. Variable ‘var’ of Child class cannot be accessed outside the Child class.
Let’s check all the options one by one:
‘Change Line n1 to private int var = 1000;’ => It will not rectify the existing error of Line n5, in fact after this change, Line n3 will also cause compilation error.
‘Delete the Line n2’ => After deleting this line, obj.var at Line n5 will refer to variable ‘var’ of Parent class. Hence, output will be 1000 in this case.
‘Change Line n3 to return var;’ => This will have no effect to the output of the code, as getVar() method has not been invoked.
‘Change Line n4 to Parent obj = new Child();’ => After this modification, obj becomes Parent type, hence obj.var will refer to variable ‘var’ of Parent class. Hence, output will be 1000 in this case.
‘Delete the method getVar() from the Child class’ => This will have no effect to the output of the code, as getVar() method has not been invoked.
‘Change Line n5 to System.out.println(obj.getVar());’ => obj.getVar() will invoke the getVar() method of Child class and this method returns the variable value from Parent class (super.var). Hence, output will be 1000 in this case.
Unattempted
SCP38442:
Subclass overrides the methods of superclass but it hides the variables of superclass.
Line n2 hides the variable created at Line n1, there is no rules related to hiding (type and access modifier can be changed).
Please note:
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. There is no compilation error in the code for using identifier ‘var’.
Line n5 causes compilation error as obj is of Child type and ‘var’ is declared private in Child class. Variable ‘var’ of Child class cannot be accessed outside the Child class.
Let’s check all the options one by one:
‘Change Line n1 to private int var = 1000;’ => It will not rectify the existing error of Line n5, in fact after this change, Line n3 will also cause compilation error.
‘Delete the Line n2’ => After deleting this line, obj.var at Line n5 will refer to variable ‘var’ of Parent class. Hence, output will be 1000 in this case.
‘Change Line n3 to return var;’ => This will have no effect to the output of the code, as getVar() method has not been invoked.
‘Change Line n4 to Parent obj = new Child();’ => After this modification, obj becomes Parent type, hence obj.var will refer to variable ‘var’ of Parent class. Hence, output will be 1000 in this case.
‘Delete the method getVar() from the Child class’ => This will have no effect to the output of the code, as getVar() method has not been invoked.
‘Change Line n5 to System.out.println(obj.getVar());’ => obj.getVar() will invoke the getVar() method of Child class and this method returns the variable value from Parent class (super.var). Hence, output will be 1000 in this case.
Question 26 of 65
26. Question
On Windows platform below directories/files are available:
1
C:\codes\com.testing\module-info.java:
module com.testing {
/*INSERT*/
}
And the command executed from C:
javac -d modules –module-source-path codes –module com.testing
Which of the following changes enable above command to execute successfully (i.e. modular code to compile successfully)?
Correct
SCP86236:
Let’s check all the options one by one:
No changes are necessary, code as is compiles successfully ? All modules implicitly requires java.base(which exports java.io package but not java.sql package).
To get a list of all the system modules, use below command:
java –list-modules
And to check details of specific module (e.g. java.base), use below command:
java –describe-module java.base
(you will notice that it exports java.io package)
Replace /*INSERT*/ with requires java.io; ? There is no module with the name java.io, package java.io is exported by java.base, which is implicitly required by all the modules.
Replace /*INSERT*/ with requires java.sql; ? Module java.sql exports java.sql package [java –describe-module java.sql], which is needed for import java.sql.SQLException; to work.
Replace /*INSERT*/ with requires java.*; ? Specific module name needs to be provided, wild-card character (*) is not allowed.
Replace /*INSERT*/ with requires java.base; java.sql; ? requires directive expects only one module. For multiple modules, use multiple requires directive.
Incorrect
SCP86236:
Let’s check all the options one by one:
No changes are necessary, code as is compiles successfully ? All modules implicitly requires java.base(which exports java.io package but not java.sql package).
To get a list of all the system modules, use below command:
java –list-modules
And to check details of specific module (e.g. java.base), use below command:
java –describe-module java.base
(you will notice that it exports java.io package)
Replace /*INSERT*/ with requires java.io; ? There is no module with the name java.io, package java.io is exported by java.base, which is implicitly required by all the modules.
Replace /*INSERT*/ with requires java.sql; ? Module java.sql exports java.sql package [java –describe-module java.sql], which is needed for import java.sql.SQLException; to work.
Replace /*INSERT*/ with requires java.*; ? Specific module name needs to be provided, wild-card character (*) is not allowed.
Replace /*INSERT*/ with requires java.base; java.sql; ? requires directive expects only one module. For multiple modules, use multiple requires directive.
Unattempted
SCP86236:
Let’s check all the options one by one:
No changes are necessary, code as is compiles successfully ? All modules implicitly requires java.base(which exports java.io package but not java.sql package).
To get a list of all the system modules, use below command:
java –list-modules
And to check details of specific module (e.g. java.base), use below command:
java –describe-module java.base
(you will notice that it exports java.io package)
Replace /*INSERT*/ with requires java.io; ? There is no module with the name java.io, package java.io is exported by java.base, which is implicitly required by all the modules.
Replace /*INSERT*/ with requires java.sql; ? Module java.sql exports java.sql package [java –describe-module java.sql], which is needed for import java.sql.SQLException; to work.
Replace /*INSERT*/ with requires java.*; ? Specific module name needs to be provided, wild-card character (*) is not allowed.
Replace /*INSERT*/ with requires java.base; java.sql; ? requires directive expects only one module. For multiple modules, use multiple requires directive.
Question 27 of 65
27. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
var x = 10; //Line n1
if (false)
System.out.println(x); //Line n2
System.out.println(“HELLO”); //Line n3
}
}
What is the result of compiling and executing Test class?
Correct
SCP64927:
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 ‘x’ infers to int type.
Even though compiler is aware that Line n2 will never execute, but it doesn’t tag it as unreachable code. Reason for this odd behavior is explained in the Java Language specification: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Following statement results in a compile-time error:
while (false) { x=3; }
because the statement x=3; is not reachable; but the superficially similar case:
if (false) { x=3; }
does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as “unreachable” in the technical sense specified here.
The rationale for this differing treatment is to allow programmers to define “flag” variables such as:
static final boolean DEBUG = false;
and then write code such as:
if (DEBUG) { x=3; }
The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.
Line n2 is not executed but Line n3 executes successfully and prints HELLO on to the console.
Incorrect
SCP64927:
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 ‘x’ infers to int type.
Even though compiler is aware that Line n2 will never execute, but it doesn’t tag it as unreachable code. Reason for this odd behavior is explained in the Java Language specification: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Following statement results in a compile-time error:
while (false) { x=3; }
because the statement x=3; is not reachable; but the superficially similar case:
if (false) { x=3; }
does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as “unreachable” in the technical sense specified here.
The rationale for this differing treatment is to allow programmers to define “flag” variables such as:
static final boolean DEBUG = false;
and then write code such as:
if (DEBUG) { x=3; }
The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.
Line n2 is not executed but Line n3 executes successfully and prints HELLO on to the console.
Unattempted
SCP64927:
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 ‘x’ infers to int type.
Even though compiler is aware that Line n2 will never execute, but it doesn’t tag it as unreachable code. Reason for this odd behavior is explained in the Java Language specification: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Following statement results in a compile-time error:
while (false) { x=3; }
because the statement x=3; is not reachable; but the superficially similar case:
if (false) { x=3; }
does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as “unreachable” in the technical sense specified here.
The rationale for this differing treatment is to allow programmers to define “flag” variables such as:
static final boolean DEBUG = false;
and then write code such as:
if (DEBUG) { x=3; }
The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.
Line n2 is not executed but Line n3 executes successfully and prints HELLO on to the console.
Question 28 of 65
28. Question
Consider below code snippet available in the same package:
abstract class Traveller {
void travel(String place){}
}
abstract class BeachTraveller extends Traveller {
/*INSERT*/
}
Which of the following declarations/definitions can replace /*INSERT*/ such that there is no compilation error?
Select ALL that apply.
Correct
SCP89518:
Both Traveller and BeachTraveller are abstract classes and BeachTraveller extends Traveller. It is possible to have abstract class without any abstract method. Code as is compiles successfully as BeachTraveller inherits travel(String) method of Traveller class.
But as per the question, /*INSERT*/ must be replaced such that there is no compilation error.
Let’s check all the options one by one:
abstract void travel(); ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `abstract void travel()`.
abstract void travel(String beach); ? As BeachTraveller is abstract, hence travel(String) method can be declared abstract.
public abstract void travel(); ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `abstract void travel()`.
public void travel() throws RuntimeException {}: ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `public void travel() throws RuntimeException {}`.
public void travel(String beach) throws Exception {}: ? As overridden method doesn’t declare to throw any checked Exception hence overriding method is not allowed to declare to throw Exception.
void travel(String beach) throws java.io.IOException {} ? As overridden method doesn’t declare to throw any checked Exception hence overriding method is not allowed to declare to throw java.io.IOException.
public void travel(Object obj) {} ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `public void travel(Object){}`.
Incorrect
SCP89518:
Both Traveller and BeachTraveller are abstract classes and BeachTraveller extends Traveller. It is possible to have abstract class without any abstract method. Code as is compiles successfully as BeachTraveller inherits travel(String) method of Traveller class.
But as per the question, /*INSERT*/ must be replaced such that there is no compilation error.
Let’s check all the options one by one:
abstract void travel(); ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `abstract void travel()`.
abstract void travel(String beach); ? As BeachTraveller is abstract, hence travel(String) method can be declared abstract.
public abstract void travel(); ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `abstract void travel()`.
public void travel() throws RuntimeException {}: ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `public void travel() throws RuntimeException {}`.
public void travel(String beach) throws Exception {}: ? As overridden method doesn’t declare to throw any checked Exception hence overriding method is not allowed to declare to throw Exception.
void travel(String beach) throws java.io.IOException {} ? As overridden method doesn’t declare to throw any checked Exception hence overriding method is not allowed to declare to throw java.io.IOException.
public void travel(Object obj) {} ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `public void travel(Object){}`.
Unattempted
SCP89518:
Both Traveller and BeachTraveller are abstract classes and BeachTraveller extends Traveller. It is possible to have abstract class without any abstract method. Code as is compiles successfully as BeachTraveller inherits travel(String) method of Traveller class.
But as per the question, /*INSERT*/ must be replaced such that there is no compilation error.
Let’s check all the options one by one:
abstract void travel(); ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `abstract void travel()`.
abstract void travel(String beach); ? As BeachTraveller is abstract, hence travel(String) method can be declared abstract.
public abstract void travel(); ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `abstract void travel()`.
public void travel() throws RuntimeException {}: ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `public void travel() throws RuntimeException {}`.
public void travel(String beach) throws Exception {}: ? As overridden method doesn’t declare to throw any checked Exception hence overriding method is not allowed to declare to throw Exception.
void travel(String beach) throws java.io.IOException {} ? As overridden method doesn’t declare to throw any checked Exception hence overriding method is not allowed to declare to throw java.io.IOException.
public void travel(Object obj) {} ? This is method overloading. BeachTraveller has 2 methods: `void travel(String){}` and `public void travel(Object){}`.
public class Test {
public static void main(String[] args) {
System.out.println(new String(“Imperfectly Perfect”));
System.out.println(new StringBuilder(“Imperfectly Perfect”));
System.out.println(new SpecialString(“Imperfectly Perfect”));
}
}
What will be the result of compiling and executing Test class?
Correct
SCP41672:
String and StringBuilder classes override toString() method, which prints the text stored in these classes.
SpecialString class doesn’t override toString() method, therefore when instance of SpecialString is printed on to the console, toString() method defined in Object class is invoked and that is why you get: @.
Incorrect
SCP41672:
String and StringBuilder classes override toString() method, which prints the text stored in these classes.
SpecialString class doesn’t override toString() method, therefore when instance of SpecialString is printed on to the console, toString() method defined in Object class is invoked and that is why you get: @.
Unattempted
SCP41672:
String and StringBuilder classes override toString() method, which prints the text stored in these classes.
SpecialString class doesn’t override toString() method, therefore when instance of SpecialString is printed on to the console, toString() method defined in Object class is invoked and that is why you get: @.
Question 30 of 65
30. Question
Which one of these top level classes cannot be sub-classed?
Correct
SCP62515:
class Dog {}: can be sub-classed within the same package.
abstract class Cat {}: can be sub-classed within the same package.
final class Electronics {}: a class with final modifier cannot be sub-classed.
private class Car {}: a top level class cannot be declared with private modifier.
Incorrect
SCP62515:
class Dog {}: can be sub-classed within the same package.
abstract class Cat {}: can be sub-classed within the same package.
final class Electronics {}: a class with final modifier cannot be sub-classed.
private class Car {}: a top level class cannot be declared with private modifier.
Unattempted
SCP62515:
class Dog {}: can be sub-classed within the same package.
abstract class Cat {}: can be sub-classed within the same package.
final class Electronics {}: a class with final modifier cannot be sub-classed.
private class Car {}: a top level class cannot be declared with private modifier.
Question 31 of 65
31. 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(“TOMATO”);
System.out.println(sb.reverse().replace(“O”, “A”)); //Line n1
}
}
What will be the result of compiling and executing Test class?
Correct
SCP53403:
sb –> {“TOMATO”}
sb.reverse() –> {“OTAMOT”}. reverse() method returns a StringBuilder object.
replace method of StringBuilder class accepts 3 arguments: `replace(int start, int end, String str)`. At Line n1, replace(“O”, “A”) method accepts 2 arguments and hence it causes compilation error.
Incorrect
SCP53403:
sb –> {“TOMATO”}
sb.reverse() –> {“OTAMOT”}. reverse() method returns a StringBuilder object.
replace method of StringBuilder class accepts 3 arguments: `replace(int start, int end, String str)`. At Line n1, replace(“O”, “A”) method accepts 2 arguments and hence it causes compilation error.
Unattempted
SCP53403:
sb –> {“TOMATO”}
sb.reverse() –> {“OTAMOT”}. reverse() method returns a StringBuilder object.
replace method of StringBuilder class accepts 3 arguments: `replace(int start, int end, String str)`. At Line n1, replace(“O”, “A”) method accepts 2 arguments and hence it causes compilation error.
Question 32 of 65
32. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
check(); //Line n1
}
What will be the result of compiling and executing Test class?
Correct
SCP88676:
If a method declares to throw Exception or its sub-type other than RuntimeException types, then calling method should follow handle or declare rule.
In this case, as method check() declares to throw Exception, so main method should either declare the same exception or its super type in its throws clause OR check(); should be surrounded by try-catch block.
Line n1 in this case causes compilation error.
Incorrect
SCP88676:
If a method declares to throw Exception or its sub-type other than RuntimeException types, then calling method should follow handle or declare rule.
In this case, as method check() declares to throw Exception, so main method should either declare the same exception or its super type in its throws clause OR check(); should be surrounded by try-catch block.
Line n1 in this case causes compilation error.
Unattempted
SCP88676:
If a method declares to throw Exception or its sub-type other than RuntimeException types, then calling method should follow handle or declare rule.
In this case, as method check() declares to throw Exception, so main method should either declare the same exception or its super type in its throws clause OR check(); should be surrounded by try-catch block.
Line n1 in this case causes compilation error.
Question 33 of 65
33. 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[2]; //Line n1
sb[0] = new StringBuilder(“PLAY”); //Line n2
boolean[] flag = new boolean[1]; //Line n3
if (flag[0]) { //Line n4
sb[1] = new StringBuilder(“GROUP”); //Line n5
}
What will be the result of compiling and executing Test class?
Correct
SCP36692:
Line n1 declares a StringBuilder [] object of 2 elements and both the elements are initialized to default value null. So, sb –> {null, null}.
Line n2 initializes 1st array element to [“PLAY”]. So, sb –> {[“PLAY”], null}.
Line n3 creates a boolean array object of 1 element and this element is initialized to default value of boolean, which is false. flag –> {false}.
At Line n4, boolean expression of if-block is ‘flag[0]’, which evaluates to false, control doesn’t enter if block and Line n5 is not executed.
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 StringBuilder implements CharSequence, hence `String.join(“-“, sb)` is valid as ‘sb’ refers to StringBuilder[] object.
As per above explanation, `String.join(“-“, sb)` will return PLAY-null and Line n6 will print PLAY-null on to the console.
Incorrect
SCP36692:
Line n1 declares a StringBuilder [] object of 2 elements and both the elements are initialized to default value null. So, sb –> {null, null}.
Line n2 initializes 1st array element to [“PLAY”]. So, sb –> {[“PLAY”], null}.
Line n3 creates a boolean array object of 1 element and this element is initialized to default value of boolean, which is false. flag –> {false}.
At Line n4, boolean expression of if-block is ‘flag[0]’, which evaluates to false, control doesn’t enter if block and Line n5 is not executed.
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 StringBuilder implements CharSequence, hence `String.join(“-“, sb)` is valid as ‘sb’ refers to StringBuilder[] object.
As per above explanation, `String.join(“-“, sb)` will return PLAY-null and Line n6 will print PLAY-null on to the console.
Unattempted
SCP36692:
Line n1 declares a StringBuilder [] object of 2 elements and both the elements are initialized to default value null. So, sb –> {null, null}.
Line n2 initializes 1st array element to [“PLAY”]. So, sb –> {[“PLAY”], null}.
Line n3 creates a boolean array object of 1 element and this element is initialized to default value of boolean, which is false. flag –> {false}.
At Line n4, boolean expression of if-block is ‘flag[0]’, which evaluates to false, control doesn’t enter if block and Line n5 is not executed.
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 StringBuilder implements CharSequence, hence `String.join(“-“, sb)` is valid as ‘sb’ refers to StringBuilder[] object.
As per above explanation, `String.join(“-“, sb)` will return PLAY-null and Line n6 will print PLAY-null on to the console.
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) {
/*INSERT*/ x = 7, y = 200;
System.out.println(String.valueOf(x + y).length());
}
}
Which of the following options, if used to replace /*INSERT*/, will compile successfully and on execution will print 3 on to the console?
Select ALL that apply.
Correct
SCP76777:
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.
Compound declarations are allowed in Java for primitive type and reference type but not for var type. Hence, var cannot be used to replace /*INSERT*/.
Range of byte data type is from -128 to 127, hence if byte is used to replace /*INSERT*/, then y = 200 would cause compilation error as 200 is out of range value for byte type. Hence, byte cannot be used to replace /*INSERT*/.
short, int, long, float & double can replace /*INSERT*/ without causing any error. x + y will evaluate to 207 for short, int and long types whereas, x + y will evaluate to 207.0 for float and double types.
String class has overloaded valueOf methods for int, char, long, float, double, boolean, char[] and Object types. valueOf method returns the corresponding String object and length() method returns number of characters in the String object.
So, `String.valueOf(x + y).length()` in case of short, int and long returns 3, on the other hand, in case of float and double it would return 5.
Hence, only 3 options (short, int and long) print expected output on to the console.
SCP76777:
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.
Compound declarations are allowed in Java for primitive type and reference type but not for var type. Hence, var cannot be used to replace /*INSERT*/.
Range of byte data type is from -128 to 127, hence if byte is used to replace /*INSERT*/, then y = 200 would cause compilation error as 200 is out of range value for byte type. Hence, byte cannot be used to replace /*INSERT*/.
short, int, long, float & double can replace /*INSERT*/ without causing any error. x + y will evaluate to 207 for short, int and long types whereas, x + y will evaluate to 207.0 for float and double types.
String class has overloaded valueOf methods for int, char, long, float, double, boolean, char[] and Object types. valueOf method returns the corresponding String object and length() method returns number of characters in the String object.
So, `String.valueOf(x + y).length()` in case of short, int and long returns 3, on the other hand, in case of float and double it would return 5.
Hence, only 3 options (short, int and long) print expected output on to the console.
SCP76777:
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.
Compound declarations are allowed in Java for primitive type and reference type but not for var type. Hence, var cannot be used to replace /*INSERT*/.
Range of byte data type is from -128 to 127, hence if byte is used to replace /*INSERT*/, then y = 200 would cause compilation error as 200 is out of range value for byte type. Hence, byte cannot be used to replace /*INSERT*/.
short, int, long, float & double can replace /*INSERT*/ without causing any error. x + y will evaluate to 207 for short, int and long types whereas, x + y will evaluate to 207.0 for float and double types.
String class has overloaded valueOf methods for int, char, long, float, double, boolean, char[] and Object types. valueOf method returns the corresponding String object and length() method returns number of characters in the String object.
So, `String.valueOf(x + y).length()` in case of short, int and long returns 3, on the other hand, in case of float and double it would return 5.
Hence, only 3 options (short, int and long) print expected output on to the console.
In a modular graph, [POSITION-1] are represented by nodes and [POSITION-2] between the modules are represented by arrows/edges.
Correct
SCP57721:
Module graph is all about modules and their dependencies.
In a modular graph, modules are represented by nodes and dependencies between the modules are represented by arrows/edges. For example,
java.se ??????> java.compiler ??????> java.base
In the above module graph portion, the nodes ‘java.se’, ‘java.compiler’ and ‘java.base’ are modules and ??????> represents dependencies between the modules.
‘java.se’ module depends upon ‘java.compiler’ module and ‘java.compiler’ module depends upon ‘java.base’ module.
Incorrect
SCP57721:
Module graph is all about modules and their dependencies.
In a modular graph, modules are represented by nodes and dependencies between the modules are represented by arrows/edges. For example,
java.se ??????> java.compiler ??????> java.base
In the above module graph portion, the nodes ‘java.se’, ‘java.compiler’ and ‘java.base’ are modules and ??????> represents dependencies between the modules.
‘java.se’ module depends upon ‘java.compiler’ module and ‘java.compiler’ module depends upon ‘java.base’ module.
Unattempted
SCP57721:
Module graph is all about modules and their dependencies.
In a modular graph, modules are represented by nodes and dependencies between the modules are represented by arrows/edges. For example,
java.se ??????> java.compiler ??????> java.base
In the above module graph portion, the nodes ‘java.se’, ‘java.compiler’ and ‘java.base’ are modules and ??????> represents dependencies between the modules.
‘java.se’ module depends upon ‘java.compiler’ module and ‘java.compiler’ module depends upon ‘java.base’ module.
Question 36 of 65
36. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
String str = “Think”; //Line n3
change(str); //Line n4
System.out.println(str); //Line n5
}
What will be the result of compiling and executing Test class?
Correct
SCP52779:
At Line n3, String reference variable ‘str’ refers to String object “Think”.
When change(String) method is invoked by Line n4, both variables ‘s’ and ‘str’ refer to the same String object “Think”.
As String is immutable, so Line 9 doesn’t modify the passed object, instead it creates a new String object “Think_Twice”.
But this newly created object is not referred and hence is a candidate for GC.
When control goes back to calling method main(String[]), ‘str’ still refers to “Think”.
Line n5 prints “Think” on to the console.
Incorrect
SCP52779:
At Line n3, String reference variable ‘str’ refers to String object “Think”.
When change(String) method is invoked by Line n4, both variables ‘s’ and ‘str’ refer to the same String object “Think”.
As String is immutable, so Line 9 doesn’t modify the passed object, instead it creates a new String object “Think_Twice”.
But this newly created object is not referred and hence is a candidate for GC.
When control goes back to calling method main(String[]), ‘str’ still refers to “Think”.
Line n5 prints “Think” on to the console.
Unattempted
SCP52779:
At Line n3, String reference variable ‘str’ refers to String object “Think”.
When change(String) method is invoked by Line n4, both variables ‘s’ and ‘str’ refer to the same String object “Think”.
As String is immutable, so Line 9 doesn’t modify the passed object, instead it creates a new String object “Think_Twice”.
But this newly created object is not referred and hence is a candidate for GC.
When control goes back to calling method main(String[]), ‘str’ still refers to “Think”.
Line n5 prints “Think” on to the console.
Question 37 of 65
37. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
boolean b1 = 0;
boolean b2 = 1;
System.out.println(b1 + b2);
}
}
What is the result of compiling and executing Test class?
Correct
SCP15318:
In Java language, boolean type can store only two values: true and false and these values are not compatible with int type.
Also + operator is not defined for boolean types. Hence, all the 3 statements inside main method causes compilation error.
Incorrect
SCP15318:
In Java language, boolean type can store only two values: true and false and these values are not compatible with int type.
Also + operator is not defined for boolean types. Hence, all the 3 statements inside main method causes compilation error.
Unattempted
SCP15318:
In Java language, boolean type can store only two values: true and false and these values are not compatible with int type.
Also + operator is not defined for boolean types. Hence, all the 3 statements inside main method causes compilation error.
public class Test {
public static void main(String[] args) {
I1 obj = new C1();
obj.print(“Java”);
}
}
Which of the following statements is correct?
Correct
SCP42275:
As per Java 8, default and static methods were added in the interface. Interface I1 defines static method print(String), there is no compilation error in interface I1.
Also the scope of print(String) method of I1 is limited to interface I1 and it can be invoked by using Interface name only, I1.print(“”).
class C1 implements I1 and it also defines print(String) instance method. Even though class C1 implements I1, it doesn’t have static print(String) method in its scope, therefore class C1 compiles successfully.
Super type reference variable can refer to an instance of Sub type, therefore the statement `I1 obj = new C1();` compiles successfully.
obj is of I1 type, hence `obj.print(“Java”);` tries to tag the static method of I1 but static print(String) method of I1 can only be invoked by using I1.print(“Java”);.
Therefore, `obj.print(“Java”);` causes compilation error.
Incorrect
SCP42275:
As per Java 8, default and static methods were added in the interface. Interface I1 defines static method print(String), there is no compilation error in interface I1.
Also the scope of print(String) method of I1 is limited to interface I1 and it can be invoked by using Interface name only, I1.print(“”).
class C1 implements I1 and it also defines print(String) instance method. Even though class C1 implements I1, it doesn’t have static print(String) method in its scope, therefore class C1 compiles successfully.
Super type reference variable can refer to an instance of Sub type, therefore the statement `I1 obj = new C1();` compiles successfully.
obj is of I1 type, hence `obj.print(“Java”);` tries to tag the static method of I1 but static print(String) method of I1 can only be invoked by using I1.print(“Java”);.
Therefore, `obj.print(“Java”);` causes compilation error.
Unattempted
SCP42275:
As per Java 8, default and static methods were added in the interface. Interface I1 defines static method print(String), there is no compilation error in interface I1.
Also the scope of print(String) method of I1 is limited to interface I1 and it can be invoked by using Interface name only, I1.print(“”).
class C1 implements I1 and it also defines print(String) instance method. Even though class C1 implements I1, it doesn’t have static print(String) method in its scope, therefore class C1 compiles successfully.
Super type reference variable can refer to an instance of Sub type, therefore the statement `I1 obj = new C1();` compiles successfully.
obj is of I1 type, hence `obj.print(“Java”);` tries to tag the static method of I1 but static print(String) method of I1 can only be invoked by using I1.print(“Java”);.
Therefore, `obj.print(“Java”);` causes compilation error.
Question 39 of 65
39. Question
Which of the following is the correct package declaration to declare Exam class in com.university.sem1 package?
Correct
SCP51430:
To declare Test class in com.university.sem1 package, use following declaration:Â
package com.university.sem1;Â
No wild-card (*) allowed in package declaration. Don’t include class name in package declaration. NOTE: all small case letters in package keyword.
Incorrect
SCP51430:
To declare Test class in com.university.sem1 package, use following declaration:Â
package com.university.sem1;Â
No wild-card (*) allowed in package declaration. Don’t include class name in package declaration. NOTE: all small case letters in package keyword.
Unattempted
SCP51430:
To declare Test class in com.university.sem1 package, use following declaration:Â
package com.university.sem1;Â
No wild-card (*) allowed in package declaration. Don’t include class name in package declaration. NOTE: all small case letters in package keyword.
Question 40 of 65
40. Question
Given below the directory/file structure on Windows platform:
C:
\—src
\—com.udayankhattry.utility
| module-info.java
|
\—com
\—udayankhattry
\—utility
| FileUtility.java
| StringUtility.java
|
\—internal
DateUtility.java
Name of the module: com.udayankhattry.utility
and there are three public classes available:
com.udayankhattry.utility.FileUtility
com.udayankhattry.utility.StringUtility
com.udayankhattry.utility.internal.DateUtility
Currently module-info.java file is blank, which of the following options correctly describes the content of module-info.java file such that FileUtility and StringUtility classes are available for public use but not the DateUtility class?
Correct
SCP56887:
By default a module doesn’t export anything.
Package name without any wild-card (*) is expected after exports directive. And all the public type members (classes, interfaces, enums) of the exported package become available for public use.
But yes the reading module code must have requires directive in its module descriptor file.
Hence, out of all the option below option is correct:
module com.udayankhattry.utility {
exports com.udayankhattry.utility;
}
Both the classes FileUtility and StringUtility are defined in exported package (com.udayankhattry.utility) and hence become available for public use.
There is no ‘not exports’ directive and with exports directives class names are not allowed.
Please note that module names live in a global namespace, separate from other namespaces in Java. Hence, module name can use the name of the package, class or interface.
Incorrect
SCP56887:
By default a module doesn’t export anything.
Package name without any wild-card (*) is expected after exports directive. And all the public type members (classes, interfaces, enums) of the exported package become available for public use.
But yes the reading module code must have requires directive in its module descriptor file.
Hence, out of all the option below option is correct:
module com.udayankhattry.utility {
exports com.udayankhattry.utility;
}
Both the classes FileUtility and StringUtility are defined in exported package (com.udayankhattry.utility) and hence become available for public use.
There is no ‘not exports’ directive and with exports directives class names are not allowed.
Please note that module names live in a global namespace, separate from other namespaces in Java. Hence, module name can use the name of the package, class or interface.
Unattempted
SCP56887:
By default a module doesn’t export anything.
Package name without any wild-card (*) is expected after exports directive. And all the public type members (classes, interfaces, enums) of the exported package become available for public use.
But yes the reading module code must have requires directive in its module descriptor file.
Hence, out of all the option below option is correct:
module com.udayankhattry.utility {
exports com.udayankhattry.utility;
}
Both the classes FileUtility and StringUtility are defined in exported package (com.udayankhattry.utility) and hence become available for public use.
There is no ‘not exports’ directive and with exports directives class names are not allowed.
Please note that module names live in a global namespace, separate from other namespaces in Java. Hence, module name can use the name of the package, class or interface.
Question 41 of 65
41. Question
Given the following definitions of the class Insect and the interface Flyable, the task is to declare a class Mosquito that inherits from the class Insect and implements the interface Flyable.
class Insect {}
interface Flyable {}
Select the correct option to accomplish this task:
Correct
SCP46647:
A class in Java extends from another class and implements interface(s). Hence correct syntax is:
class Mosquito extends Insect implements Flyable{}
Incorrect
SCP46647:
A class in Java extends from another class and implements interface(s). Hence correct syntax is:
class Mosquito extends Insect implements Flyable{}
Unattempted
SCP46647:
A class in Java extends from another class and implements interface(s). Hence correct syntax is:
class Mosquito extends Insect implements Flyable{}
public class Test {
public static void main(String[] args) {
Formatter f1 = (str1, str2) -> str1 + “_” + str2.toUpperCase();
System.out.println(f1.format(“Udayan”, “Khattry”));
}
}
What will be the result of compiling and executing Test class?
Correct
SCP23340:
Dot (.) operator has higher precedence than concatenation operator, hence toUpperCase() is invoked on str2 and not on the result of (str1 + “_” + str2).
Incorrect
SCP23340:
Dot (.) operator has higher precedence than concatenation operator, hence toUpperCase() is invoked on str2 and not on the result of (str1 + “_” + str2).
Unattempted
SCP23340:
Dot (.) operator has higher precedence than concatenation operator, hence toUpperCase() is invoked on str2 and not on the result of (str1 + “_” + str2).
Question 43 of 65
43. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3 }; //Line n1
int[] arr2 = { ‘A’, ‘B’ }; //Line n2
arr1 = arr2; //Line n3
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " "); //Line n4
}
}
}
ASCII code of 'A' is 65 and 'B' is 66. What will be the result of compiling and executing Test class?
Correct
SCP68010:
Line n1 creates an int array object of 3 elements: 1, 2, 3 and arr1 refers to it.
Line n2 creates and int array object of 2 elements: 65, 66 [char type is compatible with int type] and arr2 refers to it.
At Line n3, variable arr1 copies the content of arr2, as arr2 refers to an int array object of 2 elements: 65, 66 hence arr1 also starts referring to the same array object.
At Line n4, `arr1[i] + ” “`, + operator behaves as concatenation operator as left operand (arr1[i]) is of int type and right operand (” “) is of String type.
for loop prints all the elements of an array object referred by arr1, which is 65 66Â
Incorrect
SCP68010:
Line n1 creates an int array object of 3 elements: 1, 2, 3 and arr1 refers to it.
Line n2 creates and int array object of 2 elements: 65, 66 [char type is compatible with int type] and arr2 refers to it.
At Line n3, variable arr1 copies the content of arr2, as arr2 refers to an int array object of 2 elements: 65, 66 hence arr1 also starts referring to the same array object.
At Line n4, `arr1[i] + ” “`, + operator behaves as concatenation operator as left operand (arr1[i]) is of int type and right operand (” “) is of String type.
for loop prints all the elements of an array object referred by arr1, which is 65 66Â
Unattempted
SCP68010:
Line n1 creates an int array object of 3 elements: 1, 2, 3 and arr1 refers to it.
Line n2 creates and int array object of 2 elements: 65, 66 [char type is compatible with int type] and arr2 refers to it.
At Line n3, variable arr1 copies the content of arr2, as arr2 refers to an int array object of 2 elements: 65, 66 hence arr1 also starts referring to the same array object.
At Line n4, `arr1[i] + ” “`, + operator behaves as concatenation operator as left operand (arr1[i]) is of int type and right operand (” “) is of String type.
for loop prints all the elements of an array object referred by arr1, which is 65 66Â
Question 44 of 65
44. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
class A {
public String toString() {
return null;
}
}
public class Test {
public static void main(String [] args) {
String text = null;
text = text + new A(); //Line n1
System.out.println(text.length()); //Line n2
}
}
What will be the result of compiling and executing Test class?
Correct
SCP31408:
You need to keep in mind an important point related to String Concatenation:
If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time.
If one of the operand is null, it is converted to the string “null”.
If operand is not null, then the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string “null” is used instead.
Let’s check the expression of Line n1:
text = text + new A(); –> As text is of String type, hence + operator behaves as concatenation operator.
As text is null, so “null” is used in the Expression.
new A() represents the object of A class, so toString() method of A class is invoked, but as toString() method of A class returns null, hence “null” is used in the given expression.
So, given expression is written as:
text = “null” + “null”;
text = “nullnull”;
Hence, Line n2 prints 8 on to the console.
Incorrect
SCP31408:
You need to keep in mind an important point related to String Concatenation:
If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time.
If one of the operand is null, it is converted to the string “null”.
If operand is not null, then the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string “null” is used instead.
Let’s check the expression of Line n1:
text = text + new A(); –> As text is of String type, hence + operator behaves as concatenation operator.
As text is null, so “null” is used in the Expression.
new A() represents the object of A class, so toString() method of A class is invoked, but as toString() method of A class returns null, hence “null” is used in the given expression.
So, given expression is written as:
text = “null” + “null”;
text = “nullnull”;
Hence, Line n2 prints 8 on to the console.
Unattempted
SCP31408:
You need to keep in mind an important point related to String Concatenation:
If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time.
If one of the operand is null, it is converted to the string “null”.
If operand is not null, then the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string “null” is used instead.
Let’s check the expression of Line n1:
text = text + new A(); –> As text is of String type, hence + operator behaves as concatenation operator.
As text is null, so “null” is used in the Expression.
new A() represents the object of A class, so toString() method of A class is invoked, but as toString() method of A class returns null, hence “null” is used in the given expression.
So, given expression is written as:
text = “null” + “null”;
text = “nullnull”;
And the statements:
1. Given code compiles successfully if it is used inside the class named ’emp’
2. Given code compiles successfully if it is used inside the class named ‘Emp’
3. Given code compiles successfully if it is used inside the class named ’employee’
4. Given code compiles successfully if it is used inside the class named ‘Employee’
5. Given code compiles successfully if it is used inside the class named ‘Student’
6. Given code compiles successfully if it is used inside the class named ‘_emp_’
How many statements are true?
Correct
SCP74522:
`private void emp() {}` is a valid method declaration.
Class name and method name can be same and that is why given method can be declared in any of the given classes: ’emp’, ‘Emp’, ’employee’, ‘Employee’, ‘Student’ and ‘_emp_’.
‘_emp_’ is also a valid Java identifier.
Incorrect
SCP74522:
`private void emp() {}` is a valid method declaration.
Class name and method name can be same and that is why given method can be declared in any of the given classes: ’emp’, ‘Emp’, ’employee’, ‘Employee’, ‘Student’ and ‘_emp_’.
‘_emp_’ is also a valid Java identifier.
Unattempted
SCP74522:
`private void emp() {}` is a valid method declaration.
Class name and method name can be same and that is why given method can be declared in any of the given classes: ’emp’, ‘Emp’, ’employee’, ‘Employee’, ‘Student’ and ‘_emp_’.
‘_emp_’ is also a valid Java identifier.
Question 46 of 65
46. Question
Consider below codes of 4 java files:
//I1.java
package com.udayankhattry.ocp1;
public interface I1 {
int i = 10;
}
//I2.java
package com.udayankhattry.ocp1;
public interface I2 {
int i = 20;
}
//I3.java
package com.udayankhattry.ocp1;
public interface I3 extends I1, I2 { //Line n1
}
//Test.java
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
System.out.println(I1.i); //Line n2
System.out.println(I2.i); //Line n3
System.out.println(I3.i); //Line n4
}
}
Which of the following statements is correct?
Correct
SCP59703:
Variable ‘i’ declared inside interface I1 is implicitly public, static and final and similarly variable i declared inside interface I2 is implicitly public, static and final as well.
In Java a class can extend from only one class but an interface can extend from multiple interfaces. static variables are not inherited and hence there is no issue with Line n1.
I1.i points to variable ‘i’ of interface I1.
I2.i points to variable ‘i’ of interface I2.
I3.i is an ambiguous call as compiler is not sure whether to point to I1.i or I2.i and therefore, Line n4 causes compilation error.
Incorrect
SCP59703:
Variable ‘i’ declared inside interface I1 is implicitly public, static and final and similarly variable i declared inside interface I2 is implicitly public, static and final as well.
In Java a class can extend from only one class but an interface can extend from multiple interfaces. static variables are not inherited and hence there is no issue with Line n1.
I1.i points to variable ‘i’ of interface I1.
I2.i points to variable ‘i’ of interface I2.
I3.i is an ambiguous call as compiler is not sure whether to point to I1.i or I2.i and therefore, Line n4 causes compilation error.
Unattempted
SCP59703:
Variable ‘i’ declared inside interface I1 is implicitly public, static and final and similarly variable i declared inside interface I2 is implicitly public, static and final as well.
In Java a class can extend from only one class but an interface can extend from multiple interfaces. static variables are not inherited and hence there is no issue with Line n1.
I1.i points to variable ‘i’ of interface I1.
I2.i points to variable ‘i’ of interface I2.
I3.i is an ambiguous call as compiler is not sure whether to point to I1.i or I2.i and therefore, Line n4 causes compilation error.
Question 47 of 65
47. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
int [] arr = {2, 1, 0};
for(int i : arr) {
System.out.println(arr[i]);
}
}
}
What will be the result of compiling and executing Test class?
Correct
SCP83672:
Inside for-each loop, System.out.println(arr[i]); is used instead of System.out.println(i);Â
When loop executes 1st time, i stores the first array element, which is 2 but System.out.println statement prints arr[2] which is 0. Loop executes in this manner and prints 0 1 2 on to the console.
Incorrect
SCP83672:
Inside for-each loop, System.out.println(arr[i]); is used instead of System.out.println(i);Â
When loop executes 1st time, i stores the first array element, which is 2 but System.out.println statement prints arr[2] which is 0. Loop executes in this manner and prints 0 1 2 on to the console.
Unattempted
SCP83672:
Inside for-each loop, System.out.println(arr[i]); is used instead of System.out.println(i);Â
When loop executes 1st time, i stores the first array element, which is 2 but System.out.println statement prints arr[2] which is 0. Loop executes in this manner and prints 0 1 2 on to the console.
Question 48 of 65
48. Question
Consider below code of Child.java file:
class Parent {
public static void main(String [] args) {
System.out.println(“Parent”);
}
}
class Child extends Parent {
public static void main(String [] args) {
System.out.println(“Child”);
}
}
And the command:
java Child.java
What is the result?
Correct
SCP14478:
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 Child.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java Child.java` is equivalent to (but not exactly same as):
javac -d Child.java
java -cp Parent
Hence in this case, output is: Parent.
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 [])’.
Also note that file name can be any name supported by underlying operating system, such as if you rename ‘Child.java’ to ‘123.java’.
java 123.java will be equivalent to:
javac -d 123.java
java -cp Parent
SCP14478:
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 Child.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java Child.java` is equivalent to (but not exactly same as):
javac -d Child.java
java -cp Parent
Hence in this case, output is: Parent.
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 [])’.
Also note that file name can be any name supported by underlying operating system, such as if you rename ‘Child.java’ to ‘123.java’.
java 123.java will be equivalent to:
javac -d 123.java
java -cp Parent
SCP14478:
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 Child.java` command is that the source file is compiled into memory and the first class found in the source file is executed. Hence `java Child.java` is equivalent to (but not exactly same as):
javac -d Child.java
java -cp Parent
Hence in this case, output is: Parent.
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 [])’.
Also note that file name can be any name supported by underlying operating system, such as if you rename ‘Child.java’ to ‘123.java’.
java 123.java will be equivalent to:
javac -d 123.java
java -cp Parent
public class Test {
public static void main(String[] args) {
for(var var = 0; var <= 2; var++){} //Line n1
System.out.println(var); //Line n2
}
}
What will be the result of compiling and executing Test class?
Correct
SCP26874:
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, initialization expression of for loop is: `var var = 0;`. Java compiler automatically infers ‘var’ to be of int type as right side expression is int literal.
Variable ‘var’ is declared inside for loop, hence it is not accessible beyond loop’s body. Line n2 causes compilation error.
SCP26874:
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, initialization expression of for loop is: `var var = 0;`. Java compiler automatically infers ‘var’ to be of int type as right side expression is int literal.
Variable ‘var’ is declared inside for loop, hence it is not accessible beyond loop’s body. Line n2 causes compilation error.
SCP26874:
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, initialization expression of for loop is: `var var = 0;`. Java compiler automatically infers ‘var’ to be of int type as right side expression is int literal.
Variable ‘var’ is declared inside for loop, hence it is not accessible beyond loop’s body. Line n2 causes compilation error.
What will be the result of compiling and executing Test class?
Correct
SCP56902:
127 + 21 = 148 (int type: 32-bits) = 00000000 00000000 00000000 10010100Â
Above binary number is positive, as left most bit is 0.Â
Same binary number after type-casting to byte (8-bits): 10010100, negative number as left most bit is 1.Â
There is only one negative number in the option and hence -108 is the correct answer.
Binary 10010100 = -108.
Incorrect
SCP56902:
127 + 21 = 148 (int type: 32-bits) = 00000000 00000000 00000000 10010100Â
Above binary number is positive, as left most bit is 0.Â
Same binary number after type-casting to byte (8-bits): 10010100, negative number as left most bit is 1.Â
There is only one negative number in the option and hence -108 is the correct answer.
Binary 10010100 = -108.
Unattempted
SCP56902:
127 + 21 = 148 (int type: 32-bits) = 00000000 00000000 00000000 10010100Â
Above binary number is positive, as left most bit is 0.Â
Same binary number after type-casting to byte (8-bits): 10010100, negative number as left most bit is 1.Â
There is only one negative number in the option and hence -108 is the correct answer.
Binary 10010100 = -108.
Question 51 of 65
51. Question
Given code of Test.java file:
public class Test {
public static void main(String[] args) {
args[1] = “Day!”;
System.out.println(args[0] + ” ” + args[1]);
}
}
And the commands:
javac Test.java
java Test Good
What is the result?
Correct
SCP24067:
public static void main(String[] args) method is invoked by JVM.
Variable args is initialized and assigned with Program arguments. For example,
java Test: args refers to String [] of size 0.
java Test Hello: args refers to String [] of size 1 and 1st array element refers to “Hello”
java Test 1 2 3: args refers to String [] of size 3 and 1st array element refers to “1”, 2nd array element refers to “2” and 3rd array element refers to “3”.
Command used in this question: java Test Good, so args refers to String[] of size 1 and element at 0th index is “Good”.
args[1] = “Day!”; is trying to access 2nd array element at index 1, which is not available and hence an exception is thrown at runtime.
Incorrect
SCP24067:
public static void main(String[] args) method is invoked by JVM.
Variable args is initialized and assigned with Program arguments. For example,
java Test: args refers to String [] of size 0.
java Test Hello: args refers to String [] of size 1 and 1st array element refers to “Hello”
java Test 1 2 3: args refers to String [] of size 3 and 1st array element refers to “1”, 2nd array element refers to “2” and 3rd array element refers to “3”.
Command used in this question: java Test Good, so args refers to String[] of size 1 and element at 0th index is “Good”.
args[1] = “Day!”; is trying to access 2nd array element at index 1, which is not available and hence an exception is thrown at runtime.
Unattempted
SCP24067:
public static void main(String[] args) method is invoked by JVM.
Variable args is initialized and assigned with Program arguments. For example,
java Test: args refers to String [] of size 0.
java Test Hello: args refers to String [] of size 1 and 1st array element refers to “Hello”
java Test 1 2 3: args refers to String [] of size 3 and 1st array element refers to “1”, 2nd array element refers to “2” and 3rd array element refers to “3”.
Command used in this question: java Test Good, so args refers to String[] of size 1 and element at 0th index is “Good”.
args[1] = “Day!”; is trying to access 2nd array element at index 1, which is not available and hence an exception is thrown at runtime.
Question 52 of 65
52. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
interface Leveller {
int level();
}
public class Test {
int i = 100; //Line n1
Leveller level = () -> {
int i = 200; //Line n2
return this.i; //Line n3
};
What will be the result of compiling and executing Test class?
Correct
SCP26849:
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.
Given lambda expression is the correct implementation of the Leveller interface.
Variable ‘i’ at Line n2 shadows the instance variable ‘i’ at Line n1.
Keyword ‘this’ within lambda expression refers to the instance of enclosing class where lambda expression is written, so this.i in lambda expression is 100.
As, ‘level’ is an instance variable of Test class, therefore to access it inside static main(String []) method, an instance of Test class is needed.
‘new Test().level’ correctly refers to the ‘level’ variable and `new Test().level.level()` at Line n4 executes the code of lambda expression and returns 100.
Line n4 prints 100 on to the console.
Incorrect
SCP26849:
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.
Given lambda expression is the correct implementation of the Leveller interface.
Variable ‘i’ at Line n2 shadows the instance variable ‘i’ at Line n1.
Keyword ‘this’ within lambda expression refers to the instance of enclosing class where lambda expression is written, so this.i in lambda expression is 100.
As, ‘level’ is an instance variable of Test class, therefore to access it inside static main(String []) method, an instance of Test class is needed.
‘new Test().level’ correctly refers to the ‘level’ variable and `new Test().level.level()` at Line n4 executes the code of lambda expression and returns 100.
Line n4 prints 100 on to the console.
Unattempted
SCP26849:
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.
Given lambda expression is the correct implementation of the Leveller interface.
Variable ‘i’ at Line n2 shadows the instance variable ‘i’ at Line n1.
Keyword ‘this’ within lambda expression refers to the instance of enclosing class where lambda expression is written, so this.i in lambda expression is 100.
As, ‘level’ is an instance variable of Test class, therefore to access it inside static main(String []) method, an instance of Test class is needed.
‘new Test().level’ correctly refers to the ‘level’ variable and `new Test().level.level()` at Line n4 executes the code of lambda expression and returns 100.
Line n4 prints 100 on to the console.
Question 53 of 65
53. Question
Which of the following correctly defines the Animal class?
Correct
SCP13397:
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.
Incorrect
SCP13397:
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.
Unattempted
SCP13397:
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.
Question 54 of 65
54. Question
java.se is a/an ____________ module.
Correct
SCP42473:
‘java.se’ is the name of the module, hence it is a named module and not unnamed.
In modular JDK, module names starting with “java.” are known as standard modules. Non-standard module names don’t start with “java.”, such as module names starting with “jdk.” are non-standard.
‘java.se’ is standard module and it is not deprecated.
An aggregator module collects and re-exports the content of other modules but adds no content of its own.
It is just re-exporting other java standard modules, hence ‘java.se’ is an aggregator module.
Incorrect
SCP42473:
‘java.se’ is the name of the module, hence it is a named module and not unnamed.
In modular JDK, module names starting with “java.” are known as standard modules. Non-standard module names don’t start with “java.”, such as module names starting with “jdk.” are non-standard.
‘java.se’ is standard module and it is not deprecated.
An aggregator module collects and re-exports the content of other modules but adds no content of its own.
It is just re-exporting other java standard modules, hence ‘java.se’ is an aggregator module.
Unattempted
SCP42473:
‘java.se’ is the name of the module, hence it is a named module and not unnamed.
In modular JDK, module names starting with “java.” are known as standard modules. Non-standard module names don’t start with “java.”, such as module names starting with “jdk.” are non-standard.
‘java.se’ is standard module and it is not deprecated.
An aggregator module collects and re-exports the content of other modules but adds no content of its own.
It is just re-exporting other java standard modules, hence ‘java.se’ is an aggregator module.
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) {
int ctr = 100;
one: for (var i = 0; i < 10; i++) {
two: for (var j = 0; j < 7; j++) {
three: while (true) {
ctr++;
if (i > j) {
break one;
} else if (i == j) {
break two;
} else {
break three;
}
}
}
}
System.out.println(ctr);
}
}
What will be the result of compiling and executing Test class?
Correct
SCP70366:
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.
For the 1st loop variable ‘i’ infers to int type, so no issues for 1st loop and for the 2nd loop variable ‘j’ infers to int type, so no issues for 2nd loop as well.
Let’s check the iteration:
1st iteration of loop one: i = 0
  1st iteration of loop two: j = 0
    1st iteration of loop three: ctr = 101. As `i == j` evaluates to true, hence `break two;` gets executed, which takes the control out of loop two and hence to the increment expression (i++) of loop one.
2nd iteration of loop one; i = 1
  1st iteration of loop two: j = 0
    1st iteration of loop three; ctr = 102. As `i > j` evaluates to true, hence `break one;` gets executed, which takes the control out of the loop one.
`System.out.println(ctr);` prints 102 on to the console.
Incorrect
SCP70366:
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.
For the 1st loop variable ‘i’ infers to int type, so no issues for 1st loop and for the 2nd loop variable ‘j’ infers to int type, so no issues for 2nd loop as well.
Let’s check the iteration:
1st iteration of loop one: i = 0
  1st iteration of loop two: j = 0
    1st iteration of loop three: ctr = 101. As `i == j` evaluates to true, hence `break two;` gets executed, which takes the control out of loop two and hence to the increment expression (i++) of loop one.
2nd iteration of loop one; i = 1
  1st iteration of loop two: j = 0
    1st iteration of loop three; ctr = 102. As `i > j` evaluates to true, hence `break one;` gets executed, which takes the control out of the loop one.
`System.out.println(ctr);` prints 102 on to the console.
Unattempted
SCP70366:
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.
For the 1st loop variable ‘i’ infers to int type, so no issues for 1st loop and for the 2nd loop variable ‘j’ infers to int type, so no issues for 2nd loop as well.
Let’s check the iteration:
1st iteration of loop one: i = 0
  1st iteration of loop two: j = 0
    1st iteration of loop three: ctr = 101. As `i == j` evaluates to true, hence `break two;` gets executed, which takes the control out of loop two and hence to the increment expression (i++) of loop one.
2nd iteration of loop one; i = 1
  1st iteration of loop two: j = 0
    1st iteration of loop three; ctr = 102. As `i > j` evaluates to true, hence `break one;` gets executed, which takes the control out of the loop one.
`System.out.println(ctr);` prints 102 on to the console.
Question 56 of 65
56. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String[] args) {
int [] arr = {1, 2, 3, 4, 5};
int x = 0;
for(/*INSERT*/) {
x += arr[n];
}
System.out.println(x);
}
}
Which 3 options, if used to replace /*INSERT*/, on execution will print 9 on to the console?
Correct
SCP35369:
Logic in for loop is adding array elements. You need to find out which array elements when added will result in 9. Possible options are: {1+3+5, 2+3+4, 4+5}.
Based on these 3 combinations you can select 3 correct options.
Incorrect
SCP35369:
Logic in for loop is adding array elements. You need to find out which array elements when added will result in 9. Possible options are: {1+3+5, 2+3+4, 4+5}.
Based on these 3 combinations you can select 3 correct options.
Unattempted
SCP35369:
Logic in for loop is adding array elements. You need to find out which array elements when added will result in 9. Possible options are: {1+3+5, 2+3+4, 4+5}.
Based on these 3 combinations you can select 3 correct options.
Question 57 of 65
57. Question
Consider below code:
public class Test {
public static void main(String[] args) {
long a = 100_00l;
int b = 100;
float c = 2.02f;
double d = 10_0.35d;
c = a;
d = a;
c = d;
d = c;
c = b;
b = c;
b = (int)d;
}
}
How many statement(s) cause(s) compilation failure?
Correct
SCP53632:
For readability purpose underscore (_) is used to separate numeric values. This is very useful in representing big numbers such as credit card numbers (1234_7654_9876_0987). long data can be suffixed by l, float by f and double by d. So first 4 variable declaration and assignment statements don’t cause any compilation error.
long can be easily assigned to float and double type variables, hence no issues with c = a; and d = a;
double cannot be assigned to float without explicit casting, so c = d; causes compilation error.
float can easily be assigned to double and int can easily be assigned to float, so d = c; and c = b; compile successfully.
float can’t be assigned to int without explicit casting, so b = c; causes compilation error.
double can’t be assigned to int without explicit casting, statement b = (int)d; is casting double to int, so no issues.
In total, two statements are causing compilation error: c = d; and b = c;
Incorrect
SCP53632:
For readability purpose underscore (_) is used to separate numeric values. This is very useful in representing big numbers such as credit card numbers (1234_7654_9876_0987). long data can be suffixed by l, float by f and double by d. So first 4 variable declaration and assignment statements don’t cause any compilation error.
long can be easily assigned to float and double type variables, hence no issues with c = a; and d = a;
double cannot be assigned to float without explicit casting, so c = d; causes compilation error.
float can easily be assigned to double and int can easily be assigned to float, so d = c; and c = b; compile successfully.
float can’t be assigned to int without explicit casting, so b = c; causes compilation error.
double can’t be assigned to int without explicit casting, statement b = (int)d; is casting double to int, so no issues.
In total, two statements are causing compilation error: c = d; and b = c;
Unattempted
SCP53632:
For readability purpose underscore (_) is used to separate numeric values. This is very useful in representing big numbers such as credit card numbers (1234_7654_9876_0987). long data can be suffixed by l, float by f and double by d. So first 4 variable declaration and assignment statements don’t cause any compilation error.
long can be easily assigned to float and double type variables, hence no issues with c = a; and d = a;
double cannot be assigned to float without explicit casting, so c = d; causes compilation error.
float can easily be assigned to double and int can easily be assigned to float, so d = c; and c = b; compile successfully.
float can’t be assigned to int without explicit casting, so b = c; causes compilation error.
double can’t be assigned to int without explicit casting, statement b = (int)d; is casting double to int, so no issues.
In total, two statements are causing compilation error: c = d; and b = c;
Question 58 of 65
58. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
public class Test {
public static void main(String [] args) {
String text = “ONE “;
System.out.println(text.concat(text.concat(“ELEVEN “)).trim());
}
}
What will be the result of compiling and executing Test class?
Correct
SCP89828:
Given statement:
System.out.println(text.concat(text.concat(“ELEVEN “)).trim()); //’text’ refers to “ONE ”
System.out.println(text.concat(“ONE ELEVEN “).trim()); //As String is immutable, hence there is no change in the String object referred by ‘text’, ‘text’ still refers to “ONE ”
System.out.println((“ONE ONE ELEVEN “).trim()); //’text’ still refers to “ONE ”
System.out.println(“ONE ONE ELEVEN”); //trim() method removes the trailing space in this case
ONE ONE ELEVEN is printed on to the console.
Incorrect
SCP89828:
Given statement:
System.out.println(text.concat(text.concat(“ELEVEN “)).trim()); //’text’ refers to “ONE ”
System.out.println(text.concat(“ONE ELEVEN “).trim()); //As String is immutable, hence there is no change in the String object referred by ‘text’, ‘text’ still refers to “ONE ”
System.out.println((“ONE ONE ELEVEN “).trim()); //’text’ still refers to “ONE ”
System.out.println(“ONE ONE ELEVEN”); //trim() method removes the trailing space in this case
ONE ONE ELEVEN is printed on to the console.
Unattempted
SCP89828:
Given statement:
System.out.println(text.concat(text.concat(“ELEVEN “)).trim()); //’text’ refers to “ONE ”
System.out.println(text.concat(“ONE ELEVEN “).trim()); //As String is immutable, hence there is no change in the String object referred by ‘text’, ‘text’ still refers to “ONE ”
System.out.println((“ONE ONE ELEVEN “).trim()); //’text’ still refers to “ONE ”
System.out.println(“ONE ONE ELEVEN”); //trim() method removes the trailing space in this case
ONE ONE ELEVEN is printed on to the console.
Question 59 of 65
59. Question
java.sql.SQLException extends java.lang.Exception
and
java.sql.SQLWarning extends java.sql.SQLException
class Calculator implements Multiplier {
public void multiply(int… x) throws /*INSERT*/ {
}
}
public class Test {
public static void main(String[] args) {
try {
Multiplier obj = new Calculator(); //Line n1
obj.multiply(1, 2, 3);
} catch(SQLException e) {
System.out.println(e);
}
}
}
Which of the options can be used to replace /*INSERT*/ such that there is no compilation error?
Select ALL that apply.
Correct
SCP35921:
At Line n1, reference variable ‘obj’ is of Multiplier type (supertype) and it refers to an instance of Calculator class (subtype). This is polymorphism and allowed in Java.
multiply(int…) method declared in Multiplier interface declares to throw SQLException, hence the catch handler for Line n1 should provide handler for SQLException or its supertype. As catch-handler for SQLException is available, therefore Test class compiles successfully.
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: SQLException is a valid option.
3. May declare to throw the sub class of the exception thrown by super class / interface method: SQLWarning is a valid option.
4. Cannot declare to throw the super class of the exception thrown by super class / interface method: Exception, Throwable are not valid options.
5. Cannot declare to throw unrelated checked exception: java.io.IOException is not a valid option as it is not related java.sql.SQLException in multi-level inheritance.
6. May declare to throw any RuntimeException or Error: RuntimeException, NullPointerException and Error are valid options.
Therefore 5 options can successfully replace /*INSERT*/: SQLException, SQLWarning, RuntimeException, Error and NullPointerException
Incorrect
SCP35921:
At Line n1, reference variable ‘obj’ is of Multiplier type (supertype) and it refers to an instance of Calculator class (subtype). This is polymorphism and allowed in Java.
multiply(int…) method declared in Multiplier interface declares to throw SQLException, hence the catch handler for Line n1 should provide handler for SQLException or its supertype. As catch-handler for SQLException is available, therefore Test class compiles successfully.
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: SQLException is a valid option.
3. May declare to throw the sub class of the exception thrown by super class / interface method: SQLWarning is a valid option.
4. Cannot declare to throw the super class of the exception thrown by super class / interface method: Exception, Throwable are not valid options.
5. Cannot declare to throw unrelated checked exception: java.io.IOException is not a valid option as it is not related java.sql.SQLException in multi-level inheritance.
6. May declare to throw any RuntimeException or Error: RuntimeException, NullPointerException and Error are valid options.
Therefore 5 options can successfully replace /*INSERT*/: SQLException, SQLWarning, RuntimeException, Error and NullPointerException
Unattempted
SCP35921:
At Line n1, reference variable ‘obj’ is of Multiplier type (supertype) and it refers to an instance of Calculator class (subtype). This is polymorphism and allowed in Java.
multiply(int…) method declared in Multiplier interface declares to throw SQLException, hence the catch handler for Line n1 should provide handler for SQLException or its supertype. As catch-handler for SQLException is available, therefore Test class compiles successfully.
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: SQLException is a valid option.
3. May declare to throw the sub class of the exception thrown by super class / interface method: SQLWarning is a valid option.
4. Cannot declare to throw the super class of the exception thrown by super class / interface method: Exception, Throwable are not valid options.
5. Cannot declare to throw unrelated checked exception: java.io.IOException is not a valid option as it is not related java.sql.SQLException in multi-level inheritance.
6. May declare to throw any RuntimeException or Error: RuntimeException, NullPointerException and Error are valid options.
Therefore 5 options can successfully replace /*INSERT*/: SQLException, SQLWarning, RuntimeException, Error and NullPointerException
How many of the above declarations/definitions can be used inside an interface?
Correct
SCP89121:
Let’s check all the options one by one:
void test(); ? By default test method is public and abstract and it is allowed inside an interface.
default void test(String name) {
  System.out.println(“Testing ” + name);
} ?
As per Java 8, default methods were added in the interface. It is a valid syntax for the default method to be used inside an interface.
static void test(int x) {
  System.out.println(x);
} ?
As per Java 8, static methods were added in the interface. It is a valid syntax for the static method to be used inside an interface.
Even if all the above 3 methods [test(), test(String) and test(int)] are available in the same interface, there is no issue at all, it is the case of method overloading.
private default void log1() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static but not default.
private void log2() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static.
private static void log3() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static.
Out of 6 declarations/definitions, 5 can be used inside an interface.
Incorrect
SCP89121:
Let’s check all the options one by one:
void test(); ? By default test method is public and abstract and it is allowed inside an interface.
default void test(String name) {
  System.out.println(“Testing ” + name);
} ?
As per Java 8, default methods were added in the interface. It is a valid syntax for the default method to be used inside an interface.
static void test(int x) {
  System.out.println(x);
} ?
As per Java 8, static methods were added in the interface. It is a valid syntax for the static method to be used inside an interface.
Even if all the above 3 methods [test(), test(String) and test(int)] are available in the same interface, there is no issue at all, it is the case of method overloading.
private default void log1() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static but not default.
private void log2() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static.
private static void log3() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static.
Out of 6 declarations/definitions, 5 can be used inside an interface.
Unattempted
SCP89121:
Let’s check all the options one by one:
void test(); ? By default test method is public and abstract and it is allowed inside an interface.
default void test(String name) {
  System.out.println(“Testing ” + name);
} ?
As per Java 8, default methods were added in the interface. It is a valid syntax for the default method to be used inside an interface.
static void test(int x) {
  System.out.println(x);
} ?
As per Java 8, static methods were added in the interface. It is a valid syntax for the static method to be used inside an interface.
Even if all the above 3 methods [test(), test(String) and test(int)] are available in the same interface, there is no issue at all, it is the case of method overloading.
private default void log1() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static but not default.
private void log2() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static.
private static void log3() {} ? As per Java 9, private methods were added in the interface, these can be static or non-static.
Out of 6 declarations/definitions, 5 can be used inside an interface.
Question 61 of 65
61. Question
Consider below code of Test.java file:
package com.udayankhattry.ocp1;
abstract class Log {
abstract long count(); //Line n1
abstract Object get(); //Line n2
}
class CommunicationLog extends Log {
int count() { //Line n3
return 100;
}
String get() { //Line n4
return “COM-LOG”;
}
}
public class Test {
public static void main(String[] args) {
Log log = new CommunicationLog(); //Line n5
System.out.print(log.count());
System.out.print(log.get());
}
}
Which of the following statement is correct?
Correct
SCP76923:
CommunicationLog class overrides count() and get() methods of Log class.
There are 2 rules related to return types:
1. If return type of overridden method is of primitive type, then overriding method should use same primitive type.
2. If return type of overridden method is of reference type, then overriding method can use same reference type or its sub-type (also known as covariant return type).
count() method at Line n1 returns long but overriding method at Line n3 returns int and that is why Line n3 causes compilation error.
get() method at Line n2 returns Object but overriding method at Line n4 returns String. String is a subclass of Object, so it is a case of covariant return type and hence allowed. Line n4 compiles successfully.
Incorrect
SCP76923:
CommunicationLog class overrides count() and get() methods of Log class.
There are 2 rules related to return types:
1. If return type of overridden method is of primitive type, then overriding method should use same primitive type.
2. If return type of overridden method is of reference type, then overriding method can use same reference type or its sub-type (also known as covariant return type).
count() method at Line n1 returns long but overriding method at Line n3 returns int and that is why Line n3 causes compilation error.
get() method at Line n2 returns Object but overriding method at Line n4 returns String. String is a subclass of Object, so it is a case of covariant return type and hence allowed. Line n4 compiles successfully.
Unattempted
SCP76923:
CommunicationLog class overrides count() and get() methods of Log class.
There are 2 rules related to return types:
1. If return type of overridden method is of primitive type, then overriding method should use same primitive type.
2. If return type of overridden method is of reference type, then overriding method can use same reference type or its sub-type (also known as covariant return type).
count() method at Line n1 returns long but overriding method at Line n3 returns int and that is why Line n3 causes compilation error.
get() method at Line n2 returns Object but overriding method at Line n4 returns String. String is a subclass of Object, so it is a case of covariant return type and hence allowed. Line n4 compiles successfully.
Question 62 of 65
62. Question
Given code of Test.java file:
package com.udayankhattry.ocp1;
import java.util.List;
public class Test {
public static void main(String[] args) {
var list = List.of(new String[]{“A”, “BB”, “CCC”}, new String[]{“DD”, “E”}); //Line n1
list.forEach(x -> System.out.print(x.length)); //Line n2
}
}
What will be the result of compiling and executing Test class?
Correct
SCP33157:
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 n1, list refers to List instance of String [] type, which means variable ‘list’ refers to List instance containing two elements of String[] type. Line n1 compiles successfully.
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.
The lambda expression at Line n2 is the correct implementation of Consumer interface. It compiles successfully and on execution prints the length of each array element.
1st array object has 3 elements and 2nd array object has 2 elements, therefore output is: 32
Incorrect
SCP33157:
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 n1, list refers to List instance of String [] type, which means variable ‘list’ refers to List instance containing two elements of String[] type. Line n1 compiles successfully.
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.
The lambda expression at Line n2 is the correct implementation of Consumer interface. It compiles successfully and on execution prints the length of each array element.
1st array object has 3 elements and 2nd array object has 2 elements, therefore output is: 32
Unattempted
SCP33157:
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 n1, list refers to List instance of String [] type, which means variable ‘list’ refers to List instance containing two elements of String[] type. Line n1 compiles successfully.
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.
The lambda expression at Line n2 is the correct implementation of Consumer interface. It compiles successfully and on execution prints the length of each array element.
1st array object has 3 elements and 2nd array object has 2 elements, therefore output is: 32
Question 63 of 65
63. Question
Consider below code of TestStudent.java file:
package com.udayankhattry.ocp1;
//TestStudent.java
class Student {
String name;
int age;
boolean result;
double height;
}
public class TestStudent {
public static void main(String[] args) {
Student stud = new Student(); //Line n1
System.out.println(stud.name + stud.height + stud.result + stud.age); //Line n2
}
}
What will be the result of compiling and executing TestStudent class?
Correct
SCP40956:
name, height, result and age are instance variables of Student class. And instance variables are initialized to their respective default values.
For the Student object created at Line n1, ‘name’ is initialized to null, ‘age’ to 0, ‘result’ to false and ‘height’ to 0.0.
Hence, Line n2 prints null0.0false0
Incorrect
SCP40956:
name, height, result and age are instance variables of Student class. And instance variables are initialized to their respective default values.
For the Student object created at Line n1, ‘name’ is initialized to null, ‘age’ to 0, ‘result’ to false and ‘height’ to 0.0.
Hence, Line n2 prints null0.0false0
Unattempted
SCP40956:
name, height, result and age are instance variables of Student class. And instance variables are initialized to their respective default values.
For the Student object created at Line n1, ‘name’ is initialized to null, ‘age’ to 0, ‘result’ to false and ‘height’ to 0.0.
Hence, Line n2 prints null0.0false0
Question 64 of 65
64. Question
For the given code:
package com.udayankhattry.ocp1;
interface Operator {
int operate(int i, int j);
}
public class Test {
public static void main(String[] args) {
/*INSERT*/
System.out.println(opr.operate(10, 20));
}
}
Which of the following options successfully replace /*INSERT*/ such that on execution, 30 is printed on to the console?
Correct
SCP24666:
Operator opr = (int x, int y) -> { return x + y; }; => ? operate(int, int) method accepts two int type parameters and returns the addition of passed parameters.
Operator opr = (x, y) -> { return x + y; }; => ? Type is removed from left part, type inference handles it.
Operator opr = (x, y) ->Â return x + y; => ? Compilation error, if there is only one statement in the right side then semicolon inside the body, curly brackets and return keyword(if available) can be removed. But all should be removed. You can’t just remove one and leave others.
Operator opr = (x, y) ->Â x + y; => ? Semicolon inside the body, curly brackets and return keyword, all 3 are removed from right side.
Operator opr = x, y ->Â x + y;Â => ? Compilation error, if there are no parameters or more than one parameter available, then parentheses or round brackets ‘()’ cannot be removed from left side.
Incorrect
SCP24666:
Operator opr = (int x, int y) -> { return x + y; }; => ? operate(int, int) method accepts two int type parameters and returns the addition of passed parameters.
Operator opr = (x, y) -> { return x + y; }; => ? Type is removed from left part, type inference handles it.
Operator opr = (x, y) ->Â return x + y; => ? Compilation error, if there is only one statement in the right side then semicolon inside the body, curly brackets and return keyword(if available) can be removed. But all should be removed. You can’t just remove one and leave others.
Operator opr = (x, y) ->Â x + y; => ? Semicolon inside the body, curly brackets and return keyword, all 3 are removed from right side.
Operator opr = x, y ->Â x + y;Â => ? Compilation error, if there are no parameters or more than one parameter available, then parentheses or round brackets ‘()’ cannot be removed from left side.
Unattempted
SCP24666:
Operator opr = (int x, int y) -> { return x + y; }; => ? operate(int, int) method accepts two int type parameters and returns the addition of passed parameters.
Operator opr = (x, y) -> { return x + y; }; => ? Type is removed from left part, type inference handles it.
Operator opr = (x, y) ->Â return x + y; => ? Compilation error, if there is only one statement in the right side then semicolon inside the body, curly brackets and return keyword(if available) can be removed. But all should be removed. You can’t just remove one and leave others.
Operator opr = (x, y) ->Â x + y; => ? Semicolon inside the body, curly brackets and return keyword, all 3 are removed from right side.
Operator opr = x, y ->Â x + y;Â => ? Compilation error, if there are no parameters or more than one parameter available, then parentheses or round brackets ‘()’ cannot be removed from left side.
public class Test {
public static void main(String[] args) {
Base base = new Derived(); //Line n9
}
}
What will be the result of compiling and executing above code?
Correct
SCP80555:
Method can have same name as that of the Class. Hence, void Base() is a valid method declaration in Base class.
Line n2 invokes the Base() method and not the constructor.
Subclass overrides the methods of superclass but it hides the variables of superclass.
Line n5 hides the variable created at Line n1, there is no rules related to hiding (type and access modifier can be changed).
Line n7 correctly overrides the Base() method of class Base.
Compiler adds super(); as the 1st statement inside the no-argument constructor of Base class and Derived class.
There is no compilation error, so let’s check the execution.
new Derived() at Line n9 invokes the constructor of Base class, at this point instance variable id is declared and 0 is assigned to it. In fact, instance variable id of Base class is also declared and 0 is assigned to it. Compiler added super(); as the first statement inside this constructor, hence control goes to the no-argument constructor of Base class.
Compiler added super(); as the first statement inside this constructor as well, hence it invokes the no-argument constructor of the Object class. No-argument constructor of Object class finishes its execution and control goes back to the constructor of Base class. Before it starts executing remaining statements inside the constructor, instance variable assignment statement (if available) are executed. This means 1000 is assigned to variable id of Base class.
Line n2 is executed next, Base() method defined in Derived class is executed. Which overriding method to invoke, is decided at runtime based on the instance. Instance is of Derived class (because of Line n9), hence control starts executing Base() method of Derived class.
Line n8 is executed next, Derived class hides the id variable of Base class and that is why at Line n8, id points to variable created at Line n5. This id variable still stores the value 0 as Base class’s constructor has not finishes its execution.
value of id is decremented by 1, so id becomes -1 and -1 is printed on to the console. Base() method finishes its execution and control goes back to Line n2. No-argument constructor of Base class finishes its execution and control goes back to the constructor of Derived class. Before it starts executing remaining statements inside the constructor, instance variable assignment statement (if available) are executed. This means 2000 is assigned to variable id of Base class.
No-argument constructor of Derived class finishes its execution and control goes back to Line n9. main(String []) method finishes its execution and program terminates successfully.
Hence, output is -1.
Incorrect
SCP80555:
Method can have same name as that of the Class. Hence, void Base() is a valid method declaration in Base class.
Line n2 invokes the Base() method and not the constructor.
Subclass overrides the methods of superclass but it hides the variables of superclass.
Line n5 hides the variable created at Line n1, there is no rules related to hiding (type and access modifier can be changed).
Line n7 correctly overrides the Base() method of class Base.
Compiler adds super(); as the 1st statement inside the no-argument constructor of Base class and Derived class.
There is no compilation error, so let’s check the execution.
new Derived() at Line n9 invokes the constructor of Base class, at this point instance variable id is declared and 0 is assigned to it. In fact, instance variable id of Base class is also declared and 0 is assigned to it. Compiler added super(); as the first statement inside this constructor, hence control goes to the no-argument constructor of Base class.
Compiler added super(); as the first statement inside this constructor as well, hence it invokes the no-argument constructor of the Object class. No-argument constructor of Object class finishes its execution and control goes back to the constructor of Base class. Before it starts executing remaining statements inside the constructor, instance variable assignment statement (if available) are executed. This means 1000 is assigned to variable id of Base class.
Line n2 is executed next, Base() method defined in Derived class is executed. Which overriding method to invoke, is decided at runtime based on the instance. Instance is of Derived class (because of Line n9), hence control starts executing Base() method of Derived class.
Line n8 is executed next, Derived class hides the id variable of Base class and that is why at Line n8, id points to variable created at Line n5. This id variable still stores the value 0 as Base class’s constructor has not finishes its execution.
value of id is decremented by 1, so id becomes -1 and -1 is printed on to the console. Base() method finishes its execution and control goes back to Line n2. No-argument constructor of Base class finishes its execution and control goes back to the constructor of Derived class. Before it starts executing remaining statements inside the constructor, instance variable assignment statement (if available) are executed. This means 2000 is assigned to variable id of Base class.
No-argument constructor of Derived class finishes its execution and control goes back to Line n9. main(String []) method finishes its execution and program terminates successfully.
Hence, output is -1.
Unattempted
SCP80555:
Method can have same name as that of the Class. Hence, void Base() is a valid method declaration in Base class.
Line n2 invokes the Base() method and not the constructor.
Subclass overrides the methods of superclass but it hides the variables of superclass.
Line n5 hides the variable created at Line n1, there is no rules related to hiding (type and access modifier can be changed).
Line n7 correctly overrides the Base() method of class Base.
Compiler adds super(); as the 1st statement inside the no-argument constructor of Base class and Derived class.
There is no compilation error, so let’s check the execution.
new Derived() at Line n9 invokes the constructor of Base class, at this point instance variable id is declared and 0 is assigned to it. In fact, instance variable id of Base class is also declared and 0 is assigned to it. Compiler added super(); as the first statement inside this constructor, hence control goes to the no-argument constructor of Base class.
Compiler added super(); as the first statement inside this constructor as well, hence it invokes the no-argument constructor of the Object class. No-argument constructor of Object class finishes its execution and control goes back to the constructor of Base class. Before it starts executing remaining statements inside the constructor, instance variable assignment statement (if available) are executed. This means 1000 is assigned to variable id of Base class.
Line n2 is executed next, Base() method defined in Derived class is executed. Which overriding method to invoke, is decided at runtime based on the instance. Instance is of Derived class (because of Line n9), hence control starts executing Base() method of Derived class.
Line n8 is executed next, Derived class hides the id variable of Base class and that is why at Line n8, id points to variable created at Line n5. This id variable still stores the value 0 as Base class’s constructor has not finishes its execution.
value of id is decremented by 1, so id becomes -1 and -1 is printed on to the console. Base() method finishes its execution and control goes back to Line n2. No-argument constructor of Base class finishes its execution and control goes back to the constructor of Derived class. Before it starts executing remaining statements inside the constructor, instance variable assignment statement (if available) are executed. This means 2000 is assigned to variable id of Base class.
No-argument constructor of Derived class finishes its execution and control goes back to Line n9. main(String []) method finishes its execution and program terminates successfully.
Hence, output is -1.
X
Use Page numbers below to navigate to other practice tests