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 12 "
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
Given:
public class Test {
public static void main(String[] args) {
int a = 0, b, c = 2;
int sum = 0;
try {
if (a > c)
throw new RuntimeException();
b = 1;
} catch (RuntimeException e) {
sum = a + b + c;
}
System.out.println(sum);
}
}
What is the program’s output?
Correct
The b variable is declared in the first statement without being initialized. This variable may then be set to 1 in the try block. However, if the expression a > c evaluates to true, this variable will never be initialized. This potential uninitialized state leads to a compile-time error.
Notice the compiler doesn’t execute any expression at compilation time. This means even when the expression a > c evaluates to false, we still see an error because the compiler doesn’t know about such an expression result.
Incorrect
The b variable is declared in the first statement without being initialized. This variable may then be set to 1 in the try block. However, if the expression a > c evaluates to true, this variable will never be initialized. This potential uninitialized state leads to a compile-time error.
Notice the compiler doesn’t execute any expression at compilation time. This means even when the expression a > c evaluates to false, we still see an error because the compiler doesn’t know about such an expression result.
Unattempted
The b variable is declared in the first statement without being initialized. This variable may then be set to 1 in the try block. However, if the expression a > c evaluates to true, this variable will never be initialized. This potential uninitialized state leads to a compile-time error.
Notice the compiler doesn’t execute any expression at compilation time. This means even when the expression a > c evaluates to false, we still see an error because the compiler doesn’t know about such an expression result.
Question 2 of 65
2. Question
Given:
do {
System.out.println(“hi”);
} while (1 < 2);
System.out.println("bye");
What happens when compiling and executing the given code fragment?
Correct
The condition expression of the do statement is a constant expression with the value of true. This means the body of the do block would get executed forever, making the following statements unreachable. This unreachable state prevents the code from being compiled.
This excerpt from section 14.21 of the Java Language Specification should make things clears:
A do statement can complete normally if and only if at least one of the following is true:
The contained statement can complete normally and the condition expression is not a constant expression with value true.
The do statement contains a reachable continue statement with no label, and the do statement is the innermost while, do, or for statement that contains that continue statement, and the continue statement continues that do statement, and the condition expression is not a constant expression with value true.
The do statement contains a reachable continue statement with a label L, and the do statement has label L, and the continue statement continues that do statement, and the condition expression is not a constant expression with value true.
There is a reachable break statement that exits the do statement.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Incorrect
The condition expression of the do statement is a constant expression with the value of true. This means the body of the do block would get executed forever, making the following statements unreachable. This unreachable state prevents the code from being compiled.
This excerpt from section 14.21 of the Java Language Specification should make things clears:
A do statement can complete normally if and only if at least one of the following is true:
The contained statement can complete normally and the condition expression is not a constant expression with value true.
The do statement contains a reachable continue statement with no label, and the do statement is the innermost while, do, or for statement that contains that continue statement, and the continue statement continues that do statement, and the condition expression is not a constant expression with value true.
The do statement contains a reachable continue statement with a label L, and the do statement has label L, and the continue statement continues that do statement, and the condition expression is not a constant expression with value true.
There is a reachable break statement that exits the do statement.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Unattempted
The condition expression of the do statement is a constant expression with the value of true. This means the body of the do block would get executed forever, making the following statements unreachable. This unreachable state prevents the code from being compiled.
This excerpt from section 14.21 of the Java Language Specification should make things clears:
A do statement can complete normally if and only if at least one of the following is true:
The contained statement can complete normally and the condition expression is not a constant expression with value true.
The do statement contains a reachable continue statement with no label, and the do statement is the innermost while, do, or for statement that contains that continue statement, and the continue statement continues that do statement, and the condition expression is not a constant expression with value true.
The do statement contains a reachable continue statement with a label L, and the do statement has label L, and the continue statement continues that do statement, and the condition expression is not a constant expression with value true.
There is a reachable break statement that exits the do statement.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Question 3 of 65
3. Question
Which two options specify the location of application modules when compiling source files with the javac command?
Given:
String string1 = new String(“hello”).intern().toUpperCase();
String string2 = “hello”;
String string3 = “HELLO”.toLowerCase();
How many objects are created when the given code fragment is executed?
Correct
Notice a string created with a string literal, string-valued constant expression or with the String#intern method is always put into the string constant pool.
When the String constructor is called, the first object is created. The intern method then puts this string into the string constant pool and no new object is created. The next method in the chain, toUpperCase, generates a new string object without putting it into the pool. This means after the first statement, two objects are existent.
The second statement just takes the string “hello” from the constant pool and assigns it to the string2 variable. No new object is created here.
In the last statement, a String object with content “HELLO” is created and added to the pool. When the toLowerCase method is called on this string, one more String object is created.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#intern()
Incorrect
Notice a string created with a string literal, string-valued constant expression or with the String#intern method is always put into the string constant pool.
When the String constructor is called, the first object is created. The intern method then puts this string into the string constant pool and no new object is created. The next method in the chain, toUpperCase, generates a new string object without putting it into the pool. This means after the first statement, two objects are existent.
The second statement just takes the string “hello” from the constant pool and assigns it to the string2 variable. No new object is created here.
In the last statement, a String object with content “HELLO” is created and added to the pool. When the toLowerCase method is called on this string, one more String object is created.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#intern()
Unattempted
Notice a string created with a string literal, string-valued constant expression or with the String#intern method is always put into the string constant pool.
When the String constructor is called, the first object is created. The intern method then puts this string into the string constant pool and no new object is created. The next method in the chain, toUpperCase, generates a new string object without putting it into the pool. This means after the first statement, two objects are existent.
The second statement just takes the string “hello” from the constant pool and assigns it to the string2 variable. No new object is created here.
In the last statement, a String object with content “HELLO” is created and added to the pool. When the toLowerCase method is called on this string, one more String object is created.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#intern()
Question 5 of 65
5. Question
Given:
interface Foo {
boolean myMethod(String arg1, Integer arg2);
}
Which of the following statement is valid?
Correct
Option A is incorrect as the number of parameters doesn’t match.
Option B is incorrect as the return type doesn’t match.
Option C is incorrect because when the return keyword is used, the body of a lambda expression must be in its complete form. Specifically, this option would have been correct had a semicolon been inserted right before the closing curly bracket.
Option D is incorrect as the type of the second parameter doesn’t match. It must have been Integer instead of int.
Incorrect
Option A is incorrect as the number of parameters doesn’t match.
Option B is incorrect as the return type doesn’t match.
Option C is incorrect because when the return keyword is used, the body of a lambda expression must be in its complete form. Specifically, this option would have been correct had a semicolon been inserted right before the closing curly bracket.
Option D is incorrect as the type of the second parameter doesn’t match. It must have been Integer instead of int.
Unattempted
Option A is incorrect as the number of parameters doesn’t match.
Option B is incorrect as the return type doesn’t match.
Option C is incorrect because when the return keyword is used, the body of a lambda expression must be in its complete form. Specifically, this option would have been correct had a semicolon been inserted right before the closing curly bracket.
Option D is incorrect as the type of the second parameter doesn’t match. It must have been Integer instead of int.
Question 6 of 65
6. Question
It’s known that the access array[2][3] doesn’t throw an exception. Which of the following is the correct way to declare and initialize the array variable?
Correct
The access array[2][3] is valid, meaning the first dimension of the array must have at least three elements, while the second must have at least four. Array 1 and array 2 have only two elements in the first dimension, hence invalid.
Array 3 has three elements in the first dimension, but the second dimension has no elements. Therefore, an access to any element will lead to a NullPointerException. Notice the for loop seems to initialize elements of the first dimension, but it doesn’t. The reason is that the newly created one-dimensional arrays aren’t assigned back to the original two-dimensional array.
Array 3 would have also been correct had the for loop been replaced by:
for (int i = 0; i < array.length; i++) {
array[i] = new String[4];
}
Incorrect
The access array[2][3] is valid, meaning the first dimension of the array must have at least three elements, while the second must have at least four. Array 1 and array 2 have only two elements in the first dimension, hence invalid.
Array 3 has three elements in the first dimension, but the second dimension has no elements. Therefore, an access to any element will lead to a NullPointerException. Notice the for loop seems to initialize elements of the first dimension, but it doesn’t. The reason is that the newly created one-dimensional arrays aren’t assigned back to the original two-dimensional array.
Array 3 would have also been correct had the for loop been replaced by:
for (int i = 0; i < array.length; i++) {
array[i] = new String[4];
}
Unattempted
The access array[2][3] is valid, meaning the first dimension of the array must have at least three elements, while the second must have at least four. Array 1 and array 2 have only two elements in the first dimension, hence invalid.
Array 3 has three elements in the first dimension, but the second dimension has no elements. Therefore, an access to any element will lead to a NullPointerException. Notice the for loop seems to initialize elements of the first dimension, but it doesn’t. The reason is that the newly created one-dimensional arrays aren’t assigned back to the original two-dimensional array.
Array 3 would have also been correct had the for loop been replaced by:
for (int i = 0; i < array.length; i++) {
array[i] = new String[4];
}
Question 7 of 65
7. Question
Given:
interface Foo {
void m();
}
class Bar {
public static void m() {
System.out.println(“Bar”);
}
}
class FooBar extends Bar implements Foo {
public void m() {
System.out.println(“FooBar”);
}
}
Which of the following changes to the FooBar class enables the given code to compile?
Correct
The existing code cannot compile as the m method in the Bar class is static, while the one with the same signature in the FooBar class is non-static. A non-static method cannot override a static method, thereby causing a compile-time error. Option E is incorrect, then.
Declaring the m method as static doesn’t help because the Foo interface also has a method with the same signature, and this method is non-static. A static method cannot hide a non-static method; thus, the compiler still fails. Removing the m method doesn’t work either as the FooBar class still has a method with the same signature, which is inherited from the Bar class. Therefore, it’s clear that options B and C are incorrect.
Declaring the FooBar class as abstract doesn’t have any influence on method overriding and hiding that we’ve just discussed, meaning option A is incorrect.
In fact, with the given Foo and Bar types, no classes can extend Bar and implement Foo at the same time.
Incorrect
The existing code cannot compile as the m method in the Bar class is static, while the one with the same signature in the FooBar class is non-static. A non-static method cannot override a static method, thereby causing a compile-time error. Option E is incorrect, then.
Declaring the m method as static doesn’t help because the Foo interface also has a method with the same signature, and this method is non-static. A static method cannot hide a non-static method; thus, the compiler still fails. Removing the m method doesn’t work either as the FooBar class still has a method with the same signature, which is inherited from the Bar class. Therefore, it’s clear that options B and C are incorrect.
Declaring the FooBar class as abstract doesn’t have any influence on method overriding and hiding that we’ve just discussed, meaning option A is incorrect.
In fact, with the given Foo and Bar types, no classes can extend Bar and implement Foo at the same time.
Unattempted
The existing code cannot compile as the m method in the Bar class is static, while the one with the same signature in the FooBar class is non-static. A non-static method cannot override a static method, thereby causing a compile-time error. Option E is incorrect, then.
Declaring the m method as static doesn’t help because the Foo interface also has a method with the same signature, and this method is non-static. A static method cannot hide a non-static method; thus, the compiler still fails. Removing the m method doesn’t work either as the FooBar class still has a method with the same signature, which is inherited from the Bar class. Therefore, it’s clear that options B and C are incorrect.
Declaring the FooBar class as abstract doesn’t have any influence on method overriding and hiding that we’ve just discussed, meaning option A is incorrect.
In fact, with the given Foo and Bar types, no classes can extend Bar and implement Foo at the same time.
Question 8 of 65
8. Question
Given:
package foo;
public class MyFoo {
public static String myField = “Foo”;
}
And:
package test;
// Insert here
public class Test {
public static void main(String[] args) {
System.out.println(myField);
}
}
Which import statement when inserted into the Test class enables it to compile?
Correct
To use a static member of a type directly in another type, we must use a static import statement. We can either import that particular static member:
import static foo.MyFoo.myField;
Or import all static members of the enclosing type:
import static foo.MyFoo.*;
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Incorrect
To use a static member of a type directly in another type, we must use a static import statement. We can either import that particular static member:
import static foo.MyFoo.myField;
Or import all static members of the enclosing type:
import static foo.MyFoo.*;
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Unattempted
To use a static member of a type directly in another type, we must use a static import statement. We can either import that particular static member:
import static foo.MyFoo.myField;
Or import all static members of the enclosing type:
import static foo.MyFoo.*;
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Question 9 of 65
9. Question
Given:
public class Test {
void m(int argument) throws IOException /* Position 1 */ {
throw new FileNotFoundException();
}
void m(String argument) throws NullPointerException /* Position 2 */ {
throw new NullPointerException();
}
public static void main(String[] args) /* Position 3 */ {
Test test = new Test();
if (true)
test.m(“0”);
else
test.m(0);
}
}
Which of the following changes enables the given program to compile?
Correct
The compiler doesn’t evaluate any expression at compile time; thus, the code must prepare for all possible workflows.
In the given program, the else branch of the if statement is never executed. Nonetheless, the compiler doesn’t know that. As a result, the IOException listed in the throws clause of the first m method must be handled. The solution mentioned in option C specifies this exception, allowing it to be thrown up the call stack.
The second m method specifies NullPointerException. This exception is unchecked, hence doesn’t need to be handled.
Incorrect
The compiler doesn’t evaluate any expression at compile time; thus, the code must prepare for all possible workflows.
In the given program, the else branch of the if statement is never executed. Nonetheless, the compiler doesn’t know that. As a result, the IOException listed in the throws clause of the first m method must be handled. The solution mentioned in option C specifies this exception, allowing it to be thrown up the call stack.
The second m method specifies NullPointerException. This exception is unchecked, hence doesn’t need to be handled.
Unattempted
The compiler doesn’t evaluate any expression at compile time; thus, the code must prepare for all possible workflows.
In the given program, the else branch of the if statement is never executed. Nonetheless, the compiler doesn’t know that. As a result, the IOException listed in the throws clause of the first m method must be handled. The solution mentioned in option C specifies this exception, allowing it to be thrown up the call stack.
The second m method specifies NullPointerException. This exception is unchecked, hence doesn’t need to be handled.
Question 10 of 65
10. Question
Given:
public class Test {
/* Insert here */ select(short x) {
return x * 10;
}
public static void main(String[] args) {
Test test = new Test();
short s = 10
switch (test.select(s)) {
default:
System.out.println(“switch”);
}
}
}
It’s known that the given program is valid, and the return type of the select method is a primitive data type. Which of the following is correct about this type?
Correct
A switch expression can only work with the byte, short, char, and int primitive data types, meaning options from C to G are all invalid.
In the body of the select method, the operand 10 is of type int, hence the expression x * 10 returns an int value. This value can be cast to more widening primitive types, but none of these types is valid to be used in the switch statement.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Incorrect
A switch expression can only work with the byte, short, char, and int primitive data types, meaning options from C to G are all invalid.
In the body of the select method, the operand 10 is of type int, hence the expression x * 10 returns an int value. This value can be cast to more widening primitive types, but none of these types is valid to be used in the switch statement.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Unattempted
A switch expression can only work with the byte, short, char, and int primitive data types, meaning options from C to G are all invalid.
In the body of the select method, the operand 10 is of type int, hence the expression x * 10 returns an int value. This value can be cast to more widening primitive types, but none of these types is valid to be used in the switch statement.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Question 11 of 65
11. Question
Given:
String s1 = “java”;
String s2 = s1.replace(‘a’, ‘a’);
String s3 = s1.replace(“a”, “a”);
String s4 = s1.replaceAll(“a”, “a”);
System.out.print((s1 == s2) + ” “);
System.out.print((s1 == s3) + ” “);
System.out.print(s1 == s4);
What is the output of the given code fragment?
Correct
The replace method with two char parameters simply returns the String object on which the method are called if those parameters are the same. The replace method with two CharSequence parameters and the replaceAll method always return a new object.
Incorrect
The replace method with two char parameters simply returns the String object on which the method are called if those parameters are the same. The replace method with two CharSequence parameters and the replaceAll method always return a new object.
Unattempted
The replace method with two char parameters simply returns the String object on which the method are called if those parameters are the same. The replace method with two CharSequence parameters and the replaceAll method always return a new object.
Question 12 of 65
12. Question
Given:
public class Test {
void aMethod(int argument) {
System.out.println(“Method A”);
}
public static void main(String[] args) {
Test test = new Test();
char character = 1; // Line 1
test.aMethod(character); // Line 2
}
}
What is the program’s output?
Correct
There’s nothing wrong with the given code. When assigning a literal to a variable of a primitive type, the compiler just checks if the input value is within the range of the declared primitive type. In the main method, the character variable is set to the Unicode character with code point 1.
The three methods with name aMethod are overloaded. When calling these methods with a given argument, the compiler determines the applicable method by following these three phases – which is documented in the section 15.12.2 of the Java Language Specification:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
The cast from char to int or double is widening, hence the first two overloaded methods match the invocation in phase 1. Type int is closer to char than double, implying the first method is executed.
The last method also matches the invocation, but it only happens in phase 2.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Incorrect
There’s nothing wrong with the given code. When assigning a literal to a variable of a primitive type, the compiler just checks if the input value is within the range of the declared primitive type. In the main method, the character variable is set to the Unicode character with code point 1.
The three methods with name aMethod are overloaded. When calling these methods with a given argument, the compiler determines the applicable method by following these three phases – which is documented in the section 15.12.2 of the Java Language Specification:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
The cast from char to int or double is widening, hence the first two overloaded methods match the invocation in phase 1. Type int is closer to char than double, implying the first method is executed.
The last method also matches the invocation, but it only happens in phase 2.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Unattempted
There’s nothing wrong with the given code. When assigning a literal to a variable of a primitive type, the compiler just checks if the input value is within the range of the declared primitive type. In the main method, the character variable is set to the Unicode character with code point 1.
The three methods with name aMethod are overloaded. When calling these methods with a given argument, the compiler determines the applicable method by following these three phases – which is documented in the section 15.12.2 of the Java Language Specification:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
The cast from char to int or double is widening, hence the first two overloaded methods match the invocation in phase 1. Type int is closer to char than double, implying the first method is executed.
The last method also matches the invocation, but it only happens in phase 2.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Question 13 of 65
13. Question
Given:
interface Foo {
boolean compareData(Data d1, Data d2);
}
class Data {
int input;
Data(int input) {
this.input = input;
}
}
public class Test {
static boolean compare(Foo foo, Data data1, Data data2) {
return foo.compareData(data1, data2);
}
public static void main(String[] args) {
Data d1 = new Data(1);
Data d2 = new Data(2);
boolean result = /* Insert here */;
System.out.println(result);
}
}
Which two expressions when inserted independently into the given program allow it to compile?
Correct
In options B and D, the lambda expression parameters are declared with names that have already been used in the main method, thus a compile-time error occurs.
In option C, the lambda expression parameters are incorrectly defined, hence this option is incorrect as well.
Notice option E enables the program to compile, but it may not produce a result we expect. In this case, the lambda expression parameters are ignored, and the comparison is made based on variables declared outside of the expression itself.
In contrast, option A shows a correct use of lambda expressions.
Incorrect
In options B and D, the lambda expression parameters are declared with names that have already been used in the main method, thus a compile-time error occurs.
In option C, the lambda expression parameters are incorrectly defined, hence this option is incorrect as well.
Notice option E enables the program to compile, but it may not produce a result we expect. In this case, the lambda expression parameters are ignored, and the comparison is made based on variables declared outside of the expression itself.
In contrast, option A shows a correct use of lambda expressions.
Unattempted
In options B and D, the lambda expression parameters are declared with names that have already been used in the main method, thus a compile-time error occurs.
In option C, the lambda expression parameters are incorrectly defined, hence this option is incorrect as well.
Notice option E enables the program to compile, but it may not produce a result we expect. In this case, the lambda expression parameters are ignored, and the comparison is made based on variables declared outside of the expression itself.
In contrast, option A shows a correct use of lambda expressions.
Question 14 of 65
14. Question
Given:
class Foo {
void m() throws IOException { }
}
class Bar extends Foo {
void m() throws /* Insert here */ { }
}
Which of the following cannot be inserted into the given code?
Correct
When method overriding occurs, the overriding method cannot specify a checked exception that isn’t specified by the overridden one.
In the given code, the m method in the Foo class specifies IOException. This requires the method in the Bar class not to specify any checked exception that isn’t IOException.
Among all the options, NullPointerException is unchecked, thus it’s valid. FileNotFoundException is a subtype of IOException, meaning it’s valid too.
The Exception class isn’t a subtype of IOException; hence, this exception class cannot be specified.
Incorrect
When method overriding occurs, the overriding method cannot specify a checked exception that isn’t specified by the overridden one.
In the given code, the m method in the Foo class specifies IOException. This requires the method in the Bar class not to specify any checked exception that isn’t IOException.
Among all the options, NullPointerException is unchecked, thus it’s valid. FileNotFoundException is a subtype of IOException, meaning it’s valid too.
The Exception class isn’t a subtype of IOException; hence, this exception class cannot be specified.
Unattempted
When method overriding occurs, the overriding method cannot specify a checked exception that isn’t specified by the overridden one.
In the given code, the m method in the Foo class specifies IOException. This requires the method in the Bar class not to specify any checked exception that isn’t IOException.
Among all the options, NullPointerException is unchecked, thus it’s valid. FileNotFoundException is a subtype of IOException, meaning it’s valid too.
The Exception class isn’t a subtype of IOException; hence, this exception class cannot be specified.
Question 15 of 65
15. Question
Given:
String[] array1 = {“a”, “b”};
String[] array2 = {“a”, “a”};
String[] array3 = {“a”};
int i1 = Arrays.mismatch(array1, array2);
int i2 = Arrays.mismatch(array2, array3);
int i3 = Arrays.mismatch(array3, array1);
System.out.println(i1 + ” ” + i2 + ” ” + i3);
What is the output of the given code fragment?
Given:
List list = List.of(“a”, “b”);
for (String element : list) {
switch (element) {
case “b”:
default:
continue;
}
System.out.println(element);
}
What happens when compiling and executing the given code fragment?
Correct
The continue statement isn’t applicable in a switch construct. In the given code, a continue statement doesn’t skip a switch label but rather the current iteration of the for-each loop.
Each time a switch label is matched, the continue statement gets executed, skipping the rest of the for-each construct. This makes the println statement unreachable, thereby causing a compile-time error.
Incorrect
The continue statement isn’t applicable in a switch construct. In the given code, a continue statement doesn’t skip a switch label but rather the current iteration of the for-each loop.
Each time a switch label is matched, the continue statement gets executed, skipping the rest of the for-each construct. This makes the println statement unreachable, thereby causing a compile-time error.
Unattempted
The continue statement isn’t applicable in a switch construct. In the given code, a continue statement doesn’t skip a switch label but rather the current iteration of the for-each loop.
Each time a switch label is matched, the continue statement gets executed, skipping the rest of the for-each construct. This makes the println statement unreachable, thereby causing a compile-time error.
Question 17 of 65
17. Question
Given:
int i = 0;
i += (i = 10) * ++i;
System.out.println(i);
What is the output of the given code fragment?
Correct
Let’s re-write the given code to make it clearer:
int i = 0;
i = i + (i = 10) * (i + 1);
System.out.println(i);
Because i equals 0, this fragment is equivalent to:
int i = 0;
i = (i = 10) * (i + 1);
System.out.println(i);
Now, re-write it again:
int i = 10;
i = 10 * (i + 1);
System.out.println(i);
At this point, it should be clear that the final value of variable i is 110.
Incorrect
Let’s re-write the given code to make it clearer:
int i = 0;
i = i + (i = 10) * (i + 1);
System.out.println(i);
Because i equals 0, this fragment is equivalent to:
int i = 0;
i = (i = 10) * (i + 1);
System.out.println(i);
Now, re-write it again:
int i = 10;
i = 10 * (i + 1);
System.out.println(i);
At this point, it should be clear that the final value of variable i is 110.
Unattempted
Let’s re-write the given code to make it clearer:
int i = 0;
i = i + (i = 10) * (i + 1);
System.out.println(i);
Because i equals 0, this fragment is equivalent to:
int i = 0;
i = (i = 10) * (i + 1);
System.out.println(i);
Now, re-write it again:
int i = 10;
i = 10 * (i + 1);
System.out.println(i);
At this point, it should be clear that the final value of variable i is 110.
Question 18 of 65
18. Question
Given a class with name my.test.Main:
package my.test;
public class Main {
public static void main(String[] args) {
System.out.println(“Hello”);
}
}
This class is included in a module called my.test.Main, which is wrapped in a JAR file called mytest.jar. Which of the following command executes the given program when the JAR file is put in the working directory?
Correct
Here are a few notes regarding executing a modular program:
The main module and all the dependency modules must be added to the module path This module path is indicated by the m or -module-path option
When adding a module in a JAR file to the module path, we can specify that file or its containing directory
The main class to be run must be specified under the containing module with the m or -module option
Option A is incorrect as a module path option isn’t specified.
Option C is incorrect as the -module option is invalid. We must use -m or –module instead.
Option D is incorrect as the module option is missing, while module path value is invalid.
Option E and G are incorrect as main method mustn’t be specified.
Option F is incorrect as the -m option value is invalid, while the -c option doesn’t exist.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Incorrect
Here are a few notes regarding executing a modular program:
The main module and all the dependency modules must be added to the module path This module path is indicated by the m or -module-path option
When adding a module in a JAR file to the module path, we can specify that file or its containing directory
The main class to be run must be specified under the containing module with the m or -module option
Option A is incorrect as a module path option isn’t specified.
Option C is incorrect as the -module option is invalid. We must use -m or –module instead.
Option D is incorrect as the module option is missing, while module path value is invalid.
Option E and G are incorrect as main method mustn’t be specified.
Option F is incorrect as the -m option value is invalid, while the -c option doesn’t exist.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Unattempted
Here are a few notes regarding executing a modular program:
The main module and all the dependency modules must be added to the module path This module path is indicated by the m or -module-path option
When adding a module in a JAR file to the module path, we can specify that file or its containing directory
The main class to be run must be specified under the containing module with the m or -module option
Option A is incorrect as a module path option isn’t specified.
Option C is incorrect as the -module option is invalid. We must use -m or –module instead.
Option D is incorrect as the module option is missing, while module path value is invalid.
Option E and G are incorrect as main method mustn’t be specified.
Option F is incorrect as the -m option value is invalid, while the -c option doesn’t exist.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Question 19 of 65
19. Question
Given:
interface MyFoo {
int number = 0;
void calculate(int arg);
}
class MyBar implements MyFoo {
int number = 10;
public void calculate(int arg) {
number += arg;
}
}
class Test {
public static void main(String[] args) {
MyFoo foo = new MyBar();
foo.calculate(20);
System.out.println(foo.number);
}
}
What is the output of the given program?
Correct
The foo variable references an object of the MyBar class. When method calculate is called, the number field in this class is changed to 30. However, the reference type of foo is MyFoo, meaning a field accessed via this variable is the one that’s defined in the MyFoo interface. The value of this field is 0, hence number 0 is printed to the console.
Incorrect
The foo variable references an object of the MyBar class. When method calculate is called, the number field in this class is changed to 30. However, the reference type of foo is MyFoo, meaning a field accessed via this variable is the one that’s defined in the MyFoo interface. The value of this field is 0, hence number 0 is printed to the console.
Unattempted
The foo variable references an object of the MyBar class. When method calculate is called, the number field in this class is changed to 30. However, the reference type of foo is MyFoo, meaning a field accessed via this variable is the one that’s defined in the MyFoo interface. The value of this field is 0, hence number 0 is printed to the console.
Question 20 of 65
20. Question
Given:
public class Test {
static int getNumber() throws Exception {
throw new Exception(“test”);
}
public static void main(String[] args) {
int i = 0;
try {
int j = 1 / i * getNumber();
} catch (Exception e) {
System.out.println(j + “: ” + e.getMessage());
}
}
}
What is the given program’s output?
Correct
The j variable is declared within the try block. After that, there’s a catch block. This catch block isn’t enclosed in the try block, hence the declaration of j is invisible in the catch block.
However, in the catch block, there’s a reference to the j variable. A reference to an invisible variable like this leads to a compile-time error.
Incorrect
The j variable is declared within the try block. After that, there’s a catch block. This catch block isn’t enclosed in the try block, hence the declaration of j is invisible in the catch block.
However, in the catch block, there’s a reference to the j variable. A reference to an invisible variable like this leads to a compile-time error.
Unattempted
The j variable is declared within the try block. After that, there’s a catch block. This catch block isn’t enclosed in the try block, hence the declaration of j is invisible in the catch block.
However, in the catch block, there’s a reference to the j variable. A reference to an invisible variable like this leads to a compile-time error.
Question 21 of 65
21. Question
Given:
class Foo {
public void m() {
System.out.println(“Foo”);
}
}
class Bar extends Foo {
public void m(String arg) throws Exception { // Line 1
System.out.println(arg);
}
}
public class Test {
public static void main(String[] args) {
Foo foo = new Bar();
foo.m(“Bar”); // Line 2
Bar bar = (Bar) foo;
bar.m(); // Line 3
}
}
What happens when compiling and executing the given program?
Correct
On line 2, the m method is called on a Bar object. However, the type of the variable referencing that object is Foo. This type doesn’t have an m method with a String parameter. Consequently, the compiler fails over here.
The m method in the Bar class doesn’t have the same signature as the one in the Foo class, meaning it doesn’t override that method. As a result, the method in Bar can specify any exception, and line 1 is valid.
The Bar class inherits the no-parameter method from the Foo class; hence, line 3 is valid as well.
Incorrect
On line 2, the m method is called on a Bar object. However, the type of the variable referencing that object is Foo. This type doesn’t have an m method with a String parameter. Consequently, the compiler fails over here.
The m method in the Bar class doesn’t have the same signature as the one in the Foo class, meaning it doesn’t override that method. As a result, the method in Bar can specify any exception, and line 1 is valid.
The Bar class inherits the no-parameter method from the Foo class; hence, line 3 is valid as well.
Unattempted
On line 2, the m method is called on a Bar object. However, the type of the variable referencing that object is Foo. This type doesn’t have an m method with a String parameter. Consequently, the compiler fails over here.
The m method in the Bar class doesn’t have the same signature as the one in the Foo class, meaning it doesn’t override that method. As a result, the method in Bar can specify any exception, and line 1 is valid.
The Bar class inherits the no-parameter method from the Foo class; hence, line 3 is valid as well.
Question 22 of 65
22. Question
Which two of the following are valid entry methods of a program?
Correct
The entry method of a program must be a public static method. Its name must be main, the parameter type is String[] or String…, and the return type is void. The parameter name as well as the order of modifiers aren’t important.
Incorrect
The entry method of a program must be a public static method. Its name must be main, the parameter type is String[] or String…, and the return type is void. The parameter name as well as the order of modifiers aren’t important.
Unattempted
The entry method of a program must be a public static method. Its name must be main, the parameter type is String[] or String…, and the return type is void. The parameter name as well as the order of modifiers aren’t important.
Question 23 of 65
23. Question
Given:
int select(List list) {
for (int i : list) {
switch (i) {
case 1:
return i;
break; // Line 1
default:
System.out.println(“default”);
}
}
return 0;
}
Which of the following is correct about the break statement on line 1?
Correct
If the iteration variable i is set to 1, the given method returns straight away due to the return statement in the switch construct. This means the break statement can never be reached, leading to a compile-time error.
Incorrect
If the iteration variable i is set to 1, the given method returns straight away due to the return statement in the switch construct. This means the break statement can never be reached, leading to a compile-time error.
Unattempted
If the iteration variable i is set to 1, the given method returns straight away due to the return statement in the switch construct. This means the break statement can never be reached, leading to a compile-time error.
Question 24 of 65
24. Question
Given:
String s1 = “Hello”;
String s2 = ” “;
String s3 = “World!”;
String s = s1 + s2 + s3;
How many objects are created when the given code fragment is executed?
Correct
When each of variables s1, s2 and s3 is initialized, a new String object is constructed. This means after the third statement, three objects have been created.
Notice the String class is immutable, hence any change to a string generates a new object instead of modifying the existing one. In the last statement, the expression s1 + s2 creates a new String object. This object is then concatenated with the string referenced by s3, resulting one more String object.
Incorrect
When each of variables s1, s2 and s3 is initialized, a new String object is constructed. This means after the third statement, three objects have been created.
Notice the String class is immutable, hence any change to a string generates a new object instead of modifying the existing one. In the last statement, the expression s1 + s2 creates a new String object. This object is then concatenated with the string referenced by s3, resulting one more String object.
Unattempted
When each of variables s1, s2 and s3 is initialized, a new String object is constructed. This means after the third statement, three objects have been created.
Notice the String class is immutable, hence any change to a string generates a new object instead of modifying the existing one. In the last statement, the expression s1 + s2 creates a new String object. This object is then concatenated with the string referenced by s3, resulting one more String object.
Question 25 of 65
25. Question
Given:
class Foo {
protected static int myField = 2019;
protected static Object myMethod() {
return myField;
}
}
public class Bar extends Foo {
public String myField = “Bar”;
public static String myMethod() {
return new Bar().myField;
}
public static void main(String[] args) {
Foo foo = new Bar();
System.out.println(foo.myField);
System.out.println(foo.myMethod());
}
}
What is the program’s output?
Correct
In Java, fields and static methods aren’t polymorphic. This means we can hide fields and static methods, not override them.
In the given code, the variable foo has reference type Foo, but the object it refers to is an instance of the Bar class. Since myField is a field and myMethod is a static method, what we see over here is field and method hiding.
When hiding happens, the members of an object that get accessed is determined by the reference type at compile-time. The reference type of variable foo is Foo, thus both myField and myMethod in the main method refer to members of the Foo class.
Notice field hiding occurs even if the fields in the subclass and superclass have different types.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
Incorrect
In Java, fields and static methods aren’t polymorphic. This means we can hide fields and static methods, not override them.
In the given code, the variable foo has reference type Foo, but the object it refers to is an instance of the Bar class. Since myField is a field and myMethod is a static method, what we see over here is field and method hiding.
When hiding happens, the members of an object that get accessed is determined by the reference type at compile-time. The reference type of variable foo is Foo, thus both myField and myMethod in the main method refer to members of the Foo class.
Notice field hiding occurs even if the fields in the subclass and superclass have different types.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
Unattempted
In Java, fields and static methods aren’t polymorphic. This means we can hide fields and static methods, not override them.
In the given code, the variable foo has reference type Foo, but the object it refers to is an instance of the Bar class. Since myField is a field and myMethod is a static method, what we see over here is field and method hiding.
When hiding happens, the members of an object that get accessed is determined by the reference type at compile-time. The reference type of variable foo is Foo, thus both myField and myMethod in the main method refer to members of the Foo class.
Notice field hiding occurs even if the fields in the subclass and superclass have different types.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
Question 26 of 65
26. Question
Given:
int a = 1, b = 2, c = 3, d = 4;
a = b = c;
b = -d;
c *= c;
d %= a;
System.out.println(a + ” ” + b + ” ” + c + ” ” + d);
What is the given code’s output?
Correct
The expression a = b = c simply sets variables a and b to the value of c, hence they are all equal to 3 at this point.
The other statements can be rewritten as:
b = 0 – d;
c = c * c;
d = d % a;
Incorrect
The expression a = b = c simply sets variables a and b to the value of c, hence they are all equal to 3 at this point.
The other statements can be rewritten as:
b = 0 – d;
c = c * c;
d = d % a;
Unattempted
The expression a = b = c simply sets variables a and b to the value of c, hence they are all equal to 3 at this point.
The other statements can be rewritten as:
b = 0 – d;
c = c * c;
d = d % a;
Question 27 of 65
27. Question
Given:
interface Foo {
void methodA();
}
abstract class Bar /* Position 1 */ {
/* Position 2 */
public abstract void methodB();
}
public class FooBar /* Position 3 */ {
@Override /* Position 4 */
public void methodA() {
// a valid body
}
@Override /* Position 5 */
public void methodB() {
// a valid body
}
}
Which of the following changes doesn’t make the given code able to compile?
Correct
Adding a method implementation at position 2 in fact doesn’t solve any problems. When the implements Foo clause is inserted at position 3, it only makes methodA valid. The remaining method in the FooBar class, methodB, carries the @Override annotation without overriding any supertype’s method. Therefore, option D is the correct answer.
Incorrect
Adding a method implementation at position 2 in fact doesn’t solve any problems. When the implements Foo clause is inserted at position 3, it only makes methodA valid. The remaining method in the FooBar class, methodB, carries the @Override annotation without overriding any supertype’s method. Therefore, option D is the correct answer.
Unattempted
Adding a method implementation at position 2 in fact doesn’t solve any problems. When the implements Foo clause is inserted at position 3, it only makes methodA valid. The remaining method in the FooBar class, methodB, carries the @Override annotation without overriding any supertype’s method. Therefore, option D is the correct answer.
Question 28 of 65
28. Question
Given three module declarations:
module bar {
exports bar to foo;
}
And:
module foo {
requires transitive bar;
}
And:
module test {
requires foo;
}
Which graph describes the given modules’ dependencies:
Correct
The test module depends on the foo module, which in turn depends on the bar module. Notice the dependency of foo on bar is transitive, implying the test module depends on the bar module as well.
In addition to dependencies between declared modules, all the modules also depend on the base module. Among all the given graphs, only option D describes the dependencies correctly.
Incorrect
The test module depends on the foo module, which in turn depends on the bar module. Notice the dependency of foo on bar is transitive, implying the test module depends on the bar module as well.
In addition to dependencies between declared modules, all the modules also depend on the base module. Among all the given graphs, only option D describes the dependencies correctly.
Unattempted
The test module depends on the foo module, which in turn depends on the bar module. Notice the dependency of foo on bar is transitive, implying the test module depends on the bar module as well.
In addition to dependencies between declared modules, all the modules also depend on the base module. Among all the given graphs, only option D describes the dependencies correctly.
Question 29 of 65
29. Question
Given:
try {
throw new IOException();
} catch (RuntimeException e1) { // Line 1
System.out.println(“RuntimeException”);
} catch (Exception e2) { // Line 2
System.out.println(“Exception”);
} catch (IOException e3) { // Line 3
System.out.println(“IOException”);
}
What is the output of the given code?
Correct
When an exception is thrown from within a try block, the first exception handler whose exception type matches the exception object takes action.
In the given code, when an IOException is thrown, the second catch block handles it because Exception is the parent of IOException. This means the last catch block can never be reached, leading to a compile-time error.
Notice when specify multiple catch blocks with exception types in the same inheritance hierarchy, the block with the most specific type must go first, and the one with the most general type is the last.
Incorrect
When an exception is thrown from within a try block, the first exception handler whose exception type matches the exception object takes action.
In the given code, when an IOException is thrown, the second catch block handles it because Exception is the parent of IOException. This means the last catch block can never be reached, leading to a compile-time error.
Notice when specify multiple catch blocks with exception types in the same inheritance hierarchy, the block with the most specific type must go first, and the one with the most general type is the last.
Unattempted
When an exception is thrown from within a try block, the first exception handler whose exception type matches the exception object takes action.
In the given code, when an IOException is thrown, the second catch block handles it because Exception is the parent of IOException. This means the last catch block can never be reached, leading to a compile-time error.
Notice when specify multiple catch blocks with exception types in the same inheritance hierarchy, the block with the most specific type must go first, and the one with the most general type is the last.
System.out.println(element);
Which statement when placed on line 1 makes the given code print letter “f”?
Correct
Among all the options, only B and C have valid array access syntax. The statements in theses options reads the second and the forth element in the third array, respectively. In both cases, an ArrayIndexOutOfBoundsException is thrown.
To get the third element in the second array – letter “f”, an access with indexes [1][2] is needed:
String element = matrix[1][2];
Incorrect
Among all the options, only B and C have valid array access syntax. The statements in theses options reads the second and the forth element in the third array, respectively. In both cases, an ArrayIndexOutOfBoundsException is thrown.
To get the third element in the second array – letter “f”, an access with indexes [1][2] is needed:
String element = matrix[1][2];
Unattempted
Among all the options, only B and C have valid array access syntax. The statements in theses options reads the second and the forth element in the third array, respectively. In both cases, an ArrayIndexOutOfBoundsException is thrown.
To get the third element in the second array – letter “f”, an access with indexes [1][2] is needed:
String element = matrix[1][2];
Question 31 of 65
31. Question
Given:
String text = “This is it”;
int index = text.indexOf(“is”);
text = text.substring(index + 3);
text.substring(1, 3);
System.out.println(text);
What is the program’s output?
Correct
The first occurrence of the string “is” in the given text is at index 2, thus the value of text after the first invocation of the substring method is “is it”. The second substring calling returns a new string, but this return value isn’t assigned back to the text variable. Therefore, the string referenced by text is still the same – that’s “is it”. This is the value getting printed.
Incorrect
The first occurrence of the string “is” in the given text is at index 2, thus the value of text after the first invocation of the substring method is “is it”. The second substring calling returns a new string, but this return value isn’t assigned back to the text variable. Therefore, the string referenced by text is still the same – that’s “is it”. This is the value getting printed.
Unattempted
The first occurrence of the string “is” in the given text is at index 2, thus the value of text after the first invocation of the substring method is “is it”. The second substring calling returns a new string, but this return value isn’t assigned back to the text variable. Therefore, the string referenced by text is still the same – that’s “is it”. This is the value getting printed.
Question 32 of 65
32. Question
Given:
int x = 1, y = 2, z = 3;
x -= y += z;
System.out.println(x + ” ” + y);
What is the given code fragment’s output?
Correct
Unlike all other operators in Java, assignment operators are evaluated from right to left. Therefore, the given assignments can be rewritten as:
y = y + z;
x = x – y;
Incorrect
Unlike all other operators in Java, assignment operators are evaluated from right to left. Therefore, the given assignments can be rewritten as:
y = y + z;
x = x – y;
Unattempted
Unlike all other operators in Java, assignment operators are evaluated from right to left. Therefore, the given assignments can be rewritten as:
y = y + z;
x = x – y;
Question 33 of 65
33. Question
Given:
abstract class Foo {
Foo(String arg) { // Line 1
System.out.println(arg);
}
}
public class Bar extends Foo {
Bar(String arg) { // Line 2
super(arg); // Line 3
}
public static void main(String[] args) {
Foo foo = new Foo(“test”); // Line 4
Bar bar = new Bar(“test”); // Line 5
}
}
Which line causes a compilation error?
Correct
Foo is an abstract class, but this doesn’t prevent us from defining its constructors. However, such constructors can only be invoked from within a constructor of its subclasses. The call on line 4 isn’t one of those cases, resulting in a compile-time error.
Incorrect
Foo is an abstract class, but this doesn’t prevent us from defining its constructors. However, such constructors can only be invoked from within a constructor of its subclasses. The call on line 4 isn’t one of those cases, resulting in a compile-time error.
Unattempted
Foo is an abstract class, but this doesn’t prevent us from defining its constructors. However, such constructors can only be invoked from within a constructor of its subclasses. The call on line 4 isn’t one of those cases, resulting in a compile-time error.
Question 34 of 65
34. Question
Given:
class Foo {
CharSequence sequence;
Foo(CharSequence sequence) {
this.sequence = sequence;
}
}
public class Test {
public static void main(String[] args) {
Foo foo1 = new Foo(); // Line 1
Foo foo2 = new Foo(“string”); // Line 2
Foo foo3 = new Foo(new StringBuilder(“builder”)); // Line 3
}
}
Which lines of code cause compile-time errors?
Correct
The compiler only adds the default constructor if a class isn’t defined with an explicit one. In the given code, the Foo class has a constructor with a CharSequence parameter, hence no default constructor is added. Therefore, the invocation of such a constructor on line 1 leads to a compile-time error.
Notice both String and StringBuilder classes implement the CharSequence interface, thus we can use objects of these classes to call the constructor of the Foo class.
Incorrect
The compiler only adds the default constructor if a class isn’t defined with an explicit one. In the given code, the Foo class has a constructor with a CharSequence parameter, hence no default constructor is added. Therefore, the invocation of such a constructor on line 1 leads to a compile-time error.
Notice both String and StringBuilder classes implement the CharSequence interface, thus we can use objects of these classes to call the constructor of the Foo class.
Unattempted
The compiler only adds the default constructor if a class isn’t defined with an explicit one. In the given code, the Foo class has a constructor with a CharSequence parameter, hence no default constructor is added. Therefore, the invocation of such a constructor on line 1 leads to a compile-time error.
Notice both String and StringBuilder classes implement the CharSequence interface, thus we can use objects of these classes to call the constructor of the Foo class.
Question 35 of 65
35. Question
Given:
StringBuilder builder = new StringBuilder(“ABCD”);
builder.replace(1, 3, “C”).insert(4, “Q”);
System.out.println(builder);
What is the program’s output?
Which two of the following aren’t provided in the JDK?
Correct
The tools and commands the JDK provides can be found via the referenced link. Integrated Development Environments (IDE) and Version Control Systems are very important to developing applications, but they aren’t included in the JDK.
Reference: https://docs.oracle.com/en/java/javase/11/tools/
Incorrect
The tools and commands the JDK provides can be found via the referenced link. Integrated Development Environments (IDE) and Version Control Systems are very important to developing applications, but they aren’t included in the JDK.
Reference: https://docs.oracle.com/en/java/javase/11/tools/
Unattempted
The tools and commands the JDK provides can be found via the referenced link. Integrated Development Environments (IDE) and Version Control Systems are very important to developing applications, but they aren’t included in the JDK.
Reference: https://docs.oracle.com/en/java/javase/11/tools/
Question 37 of 65
37. Question
Given:
interface Foo {
int fieldA = 0;
int fieldB = 0;
void methodA();
static void methodB() {
// a valid body
}
}
interface Bar extends Foo {
int fieldA = 1; // Line 1
int fieldB = Foo.fieldB; // Line 2
static void methodA() { // Line 3
// a valid body
}
void methodB(); // Line 4
}
Which lines of code cause compilation failure?
Correct
Lines 1 and 2 are valid as those fields just hide fields of the same name in the Foo interface.
The Foo#methodB method is static and belongs to the Foo interface itself. Subtypes of this interface don’t even inherit that static method, hence they can define a method with the exact same signature.
Line 3 is invalid as a static method cannot override or hide a non-static one.
Incorrect
Lines 1 and 2 are valid as those fields just hide fields of the same name in the Foo interface.
The Foo#methodB method is static and belongs to the Foo interface itself. Subtypes of this interface don’t even inherit that static method, hence they can define a method with the exact same signature.
Line 3 is invalid as a static method cannot override or hide a non-static one.
Unattempted
Lines 1 and 2 are valid as those fields just hide fields of the same name in the Foo interface.
The Foo#methodB method is static and belongs to the Foo interface itself. Subtypes of this interface don’t even inherit that static method, hence they can define a method with the exact same signature.
Line 3 is invalid as a static method cannot override or hide a non-static one.
Question 38 of 65
38. Question
Given the bar module:
module bar {
requires foo;
exports bar;
}
With a class:
package bar;
public class MyBar { }
And here’s the foo module:
module foo {
requires bar;
}
With another class:
package foo;
import bar.MyBar;
public class MyFoo {
public static void main(String[] args) {
new MyBar();
}
}
What happens when compiling and executing the given program?
Correct
In the given program, the dependency between the foo and bar modules is circular. Such a dependency is forbidden in Java, leading to a compile-time error.
Incorrect
In the given program, the dependency between the foo and bar modules is circular. Such a dependency is forbidden in Java, leading to a compile-time error.
Unattempted
In the given program, the dependency between the foo and bar modules is circular. Such a dependency is forbidden in Java, leading to a compile-time error.
Question 39 of 65
39. Question
Given:
String language = “java”;
while (language.equals(“java”)) {
if (language.equals(“java”)) {
language = language.toUpperCase();
}
if (language.equals(“JAVA”)) {
language = language.toLowerCase();
}
}
System.out.println(language);
What is the output of the given code?
Correct
When the while condition expression is executed for the first time, it returns true. Inside the body of the statement, the language variable is flipped to its uppercase version, then back to lowercase right afterward. As a result, the condition expression is evaluated to true over and over again, leading to an infinite loop.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Incorrect
When the while condition expression is executed for the first time, it returns true. Inside the body of the statement, the language variable is flipped to its uppercase version, then back to lowercase right afterward. As a result, the condition expression is evaluated to true over and over again, leading to an infinite loop.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Unattempted
When the while condition expression is executed for the first time, it returns true. Inside the body of the statement, the language variable is flipped to its uppercase version, then back to lowercase right afterward. As a result, the condition expression is evaluated to true over and over again, leading to an infinite loop.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Question 40 of 65
40. Question
Which two of the following statement are correct about exception handling?
Correct
Option A is incorrect as an exception handler may contain only a try and a finally block.
Option D is incorrect because if the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Option E is incorrect as the finally block is just a normal block of code. We can handle an exception thrown from such a block by catching or specifying it in the containing method’s declaration.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Incorrect
Option A is incorrect as an exception handler may contain only a try and a finally block.
Option D is incorrect because if the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Option E is incorrect as the finally block is just a normal block of code. We can handle an exception thrown from such a block by catching or specifying it in the containing method’s declaration.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Unattempted
Option A is incorrect as an exception handler may contain only a try and a finally block.
Option D is incorrect because if the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Option E is incorrect as the finally block is just a normal block of code. We can handle an exception thrown from such a block by catching or specifying it in the containing method’s declaration.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Question 41 of 65
41. Question
Given:
String string = “\t \n”;
System.out.println(string.isEmpty() + ” ” + string.isBlank());
What is the output?
Given:
abstract class Foo {
abstract void methodA();
}
abstract class Bar extends Foo {
void methodA() {
// a valid body
}
void methodB() {
// a valid body
}
abstract void methodC();
}
public class Baz extends Bar {
// method declarations
}
For the Baz class to compile, which concrete methods it must define?
Correct
methodA in the Foo class is abstract, but it’s already overridden in the Bar class, hence the Baz class doesn’t override it. methodB is a concrete method, thus it doesn’t need to be overridden either.
methodC is an abstract method in the Bar class, but it hasn’t been overridden. This is the method the Baz class must override.
Incorrect
methodA in the Foo class is abstract, but it’s already overridden in the Bar class, hence the Baz class doesn’t override it. methodB is a concrete method, thus it doesn’t need to be overridden either.
methodC is an abstract method in the Bar class, but it hasn’t been overridden. This is the method the Baz class must override.
Unattempted
methodA in the Foo class is abstract, but it’s already overridden in the Bar class, hence the Baz class doesn’t override it. methodB is a concrete method, thus it doesn’t need to be overridden either.
methodC is an abstract method in the Bar class, but it hasn’t been overridden. This is the method the Baz class must override.
Question 43 of 65
43. Question
Given:
String[] array1 = {“a”, “b”, “c”};
String[] array2 = {“a”};
int result = Arrays.mismatch(array1, array2);
System.out.println(result);
What is the output?
Correct
As per the JDK API Specification, the Arrays#mismatch method finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array.
If the two arrays share a common prefix, then the returned index is the length of the common prefix and it follows that there is a mismatch between the two elements at that index within the respective arrays. If one array is a proper prefix of the other, then the returned index is the length of the smaller array and it follows that the index is only valid for the larger array. Otherwise, there is no mismatch.
In the given code, array2 is a proper prefix of array1, hence the returned index is the length of array1, which is 1 in this case.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#mismatch(java.lang.Object%5B%5D,java.lang.Object%5B%5D)
Incorrect
As per the JDK API Specification, the Arrays#mismatch method finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array.
If the two arrays share a common prefix, then the returned index is the length of the common prefix and it follows that there is a mismatch between the two elements at that index within the respective arrays. If one array is a proper prefix of the other, then the returned index is the length of the smaller array and it follows that the index is only valid for the larger array. Otherwise, there is no mismatch.
In the given code, array2 is a proper prefix of array1, hence the returned index is the length of array1, which is 1 in this case.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#mismatch(java.lang.Object%5B%5D,java.lang.Object%5B%5D)
Unattempted
As per the JDK API Specification, the Arrays#mismatch method finds and returns the index of the first mismatch between two Object arrays, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array.
If the two arrays share a common prefix, then the returned index is the length of the common prefix and it follows that there is a mismatch between the two elements at that index within the respective arrays. If one array is a proper prefix of the other, then the returned index is the length of the smaller array and it follows that the index is only valid for the larger array. Otherwise, there is no mismatch.
In the given code, array2 is a proper prefix of array1, hence the returned index is the length of array1, which is 1 in this case.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#mismatch(java.lang.Object%5B%5D,java.lang.Object%5B%5D)
Question 44 of 65
44. Question
Given the synopsis of the jdeps command:
jdeps [options] path …
Which three of the following can be specified as a path value?
Correct
Here’s a description of the jdeps command:
The jdeps command shows the package-level or class-level dependencies of Java class files. The input class can be a path name to a .class file, a directory, a JAR file, or it can be a fully qualified class name to analyze all class files. The options determine the output. By default, the jdeps command writes the dependencies to the system output. The command can generate the dependencies in DOT language (stored in .dot files).
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Incorrect
Here’s a description of the jdeps command:
The jdeps command shows the package-level or class-level dependencies of Java class files. The input class can be a path name to a .class file, a directory, a JAR file, or it can be a fully qualified class name to analyze all class files. The options determine the output. By default, the jdeps command writes the dependencies to the system output. The command can generate the dependencies in DOT language (stored in .dot files).
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Unattempted
Here’s a description of the jdeps command:
The jdeps command shows the package-level or class-level dependencies of Java class files. The input class can be a path name to a .class file, a directory, a JAR file, or it can be a fully qualified class name to analyze all class files. The options determine the output. By default, the jdeps command writes the dependencies to the system output. The command can generate the dependencies in DOT language (stored in .dot files).
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Question 45 of 65
45. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.loop(0);
}
void loop(int number) {
loop: // Line 1
while (number < 5) {
number++;
if (number % 2 == 0)
continue loop; // Line 2
System.out.print(number + " ");
}
}
}
What is the program's output?
Correct
There’s nothing wrong with the given code. The fact that the loop label has the same name as the containing method doesn’t matter.
Now, let’s go over iterations of the while construct:
Iteration 1:
Variable number is compared to 5 – the expression evaluates to true, meaning the while body is executed
Variable number is increased to 1
The if expression evaluates to false, thus the continue statement is skipped
The current value of number, which is 1, is printed out
Iteration 2:
Variable number is compared to 5 – the expression evaluates to true, meaning the while body is executed
Variable number is increased to 2
The if expression evaluates to true, thus the continue statement is executed and the current iteration is skipped
Iteration 3: Similar to iteration 1; variable number is increased to 3 and gets printed
Iteration 4: Similar to iteration 2; variable number is increased to 4 and nothing is printed
Iteration 5: Similar to iteration 1; variable number is increased to 5 and gets printed
In the next iteration, the condition expression evaluates to false, hence the while statement exits, and the program terminates.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Incorrect
There’s nothing wrong with the given code. The fact that the loop label has the same name as the containing method doesn’t matter.
Now, let’s go over iterations of the while construct:
Iteration 1:
Variable number is compared to 5 – the expression evaluates to true, meaning the while body is executed
Variable number is increased to 1
The if expression evaluates to false, thus the continue statement is skipped
The current value of number, which is 1, is printed out
Iteration 2:
Variable number is compared to 5 – the expression evaluates to true, meaning the while body is executed
Variable number is increased to 2
The if expression evaluates to true, thus the continue statement is executed and the current iteration is skipped
Iteration 3: Similar to iteration 1; variable number is increased to 3 and gets printed
Iteration 4: Similar to iteration 2; variable number is increased to 4 and nothing is printed
Iteration 5: Similar to iteration 1; variable number is increased to 5 and gets printed
In the next iteration, the condition expression evaluates to false, hence the while statement exits, and the program terminates.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Unattempted
There’s nothing wrong with the given code. The fact that the loop label has the same name as the containing method doesn’t matter.
Now, let’s go over iterations of the while construct:
Iteration 1:
Variable number is compared to 5 – the expression evaluates to true, meaning the while body is executed
Variable number is increased to 1
The if expression evaluates to false, thus the continue statement is skipped
The current value of number, which is 1, is printed out
Iteration 2:
Variable number is compared to 5 – the expression evaluates to true, meaning the while body is executed
Variable number is increased to 2
The if expression evaluates to true, thus the continue statement is executed and the current iteration is skipped
Iteration 3: Similar to iteration 1; variable number is increased to 3 and gets printed
Iteration 4: Similar to iteration 2; variable number is increased to 4 and nothing is printed
Iteration 5: Similar to iteration 1; variable number is increased to 5 and gets printed
In the next iteration, the condition expression evaluates to false, hence the while statement exits, and the program terminates.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Question 46 of 65
46. Question
Given:
public class Test {
public Test() {
text3 = text2 + “c”; // Line 1
}
String text1 = “a” + text2; // Line 2
String text2 = “b”; // Line 3
String text3;
}
Which line fails to compile?
Correct
When a class is compiled, a field initialization statement can be considered an initialization block, and all initialization block bodies are copied to the beginning of each constructor. As a result, at the bytecode level, a constructor body always follows the initialization of any field, hence can reference that field.
Outside of the constructors, however, a field can only reference other fields that have been defined before it; otherwise we’ll have an illegal forward reference error.
On line 2, the text1 field references text2, which hasn’t been defined until line 3. Therefore, the compilation fails on line 2.
Incorrect
When a class is compiled, a field initialization statement can be considered an initialization block, and all initialization block bodies are copied to the beginning of each constructor. As a result, at the bytecode level, a constructor body always follows the initialization of any field, hence can reference that field.
Outside of the constructors, however, a field can only reference other fields that have been defined before it; otherwise we’ll have an illegal forward reference error.
On line 2, the text1 field references text2, which hasn’t been defined until line 3. Therefore, the compilation fails on line 2.
Unattempted
When a class is compiled, a field initialization statement can be considered an initialization block, and all initialization block bodies are copied to the beginning of each constructor. As a result, at the bytecode level, a constructor body always follows the initialization of any field, hence can reference that field.
Outside of the constructors, however, a field can only reference other fields that have been defined before it; otherwise we’ll have an illegal forward reference error.
On line 2, the text1 field references text2, which hasn’t been defined until line 3. Therefore, the compilation fails on line 2.
Question 47 of 65
47. Question
Given:
interface Foo {
void myMethod();
}
abstract class Bar implements Foo { // Line 1
}
public class Test implements Foo extends Bar { // Line 2
@Override // Line 3
public void myMethod() {
// a valid body
}
public static void main(String[] args) {
Foo foo = new Test(); // Line 4
foo.myMethod(); // Line 5
}
}
What line causes a compile-time error?
Correct
When a class declares an extended class and implemented interfaces, the class name must go first, then interface names which are separated by commas. This doesn’t happen in the given code.
Had the Test class declaration been:
public class Test extends Bar implements Foo {
// class body
}
Option F would have been the correct answer.
Incorrect
When a class declares an extended class and implemented interfaces, the class name must go first, then interface names which are separated by commas. This doesn’t happen in the given code.
Had the Test class declaration been:
public class Test extends Bar implements Foo {
// class body
}
Option F would have been the correct answer.
Unattempted
When a class declares an extended class and implemented interfaces, the class name must go first, then interface names which are separated by commas. This doesn’t happen in the given code.
Had the Test class declaration been:
public class Test extends Bar implements Foo {
// class body
}
Option F would have been the correct answer.
Question 48 of 65
48. Question
Which two of the following class declarations apply the encapsulation concept?
Correct
In options A and C, the name field isn’t private, thus it’s accessible to the outside of the class. As a result, the field and its associated accessors no longer form a single unit.
Incorrect
In options A and C, the name field isn’t private, thus it’s accessible to the outside of the class. As a result, the field and its associated accessors no longer form a single unit.
Unattempted
In options A and C, the name field isn’t private, thus it’s accessible to the outside of the class. As a result, the field and its associated accessors no longer form a single unit.
Question 49 of 65
49. Question
Which two of the following statements are correct about the trim and strip methods in the String class?
Given:
class Data { }
class Test {
void playWithData(Data a) {
Data b = new Data();
Data c = new Data();
Data d = a; // Line 1
b = c; // Line 2
c = d; // Line 3
a = null; // Line 4
d = null; // Line 5
c = null; // Line 6
}
}
After which line the Data object passed to the playWithData method is eligible for garbage collection?
Correct
No matter what happens inside the playWithData method, the variable that references the passed-in object still points to the same object after the method completes. As a result, this object isn’t ready to be garbage collected even after the given method returns.
Incorrect
No matter what happens inside the playWithData method, the variable that references the passed-in object still points to the same object after the method completes. As a result, this object isn’t ready to be garbage collected even after the given method returns.
Unattempted
No matter what happens inside the playWithData method, the variable that references the passed-in object still points to the same object after the method completes. As a result, this object isn’t ready to be garbage collected even after the given method returns.
Question 51 of 65
51. Question
Given:
class Foo {
static String text = “Foo”;
}
class Bar extends Foo {
void printText() {
System.out.println(/* Insert here */);
}
}
Which of the following is not a correct way to reference the text field defined in the Foo class?
Correct
Since the text field is static, it can be accessed via both class references and instance references. The Bar class is a subtype of the Foo class, hence inherits that field. This explains why we can access the text field using any of the expressions shown in options A to E.
Incorrect
Since the text field is static, it can be accessed via both class references and instance references. The Bar class is a subtype of the Foo class, hence inherits that field. This explains why we can access the text field using any of the expressions shown in options A to E.
Unattempted
Since the text field is static, it can be accessed via both class references and instance references. The Bar class is a subtype of the Foo class, hence inherits that field. This explains why we can access the text field using any of the expressions shown in options A to E.
Question 52 of 65
52. Question
Given:
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
int quotient = test.divide(1, 0);
System.out.println(quotient);
} catch (RuntimeException e) {
try {
throw e;
} finally {
System.out.println(“finally”);
}
} catch (Exception e) {
System.out.println(“catch”);
}
}
int divide(int dividend, int divisor) {
return dividend / divisor;
}
}
What happens when executing the given program?
Correct
When dividing number 1 by 0, we get an ArithmeticException. This exception is then caught by the first catch block and re-thrown. Before the program exits with an exception, the finally block gets executed, printing out the string “finally”.
Notice the second catch block only processes exceptions thrown by the first try block – it doesn’t belong to the same exception handler as the second try block, thereby taking no action when the ArithmeticException is re-thrown.
Incorrect
When dividing number 1 by 0, we get an ArithmeticException. This exception is then caught by the first catch block and re-thrown. Before the program exits with an exception, the finally block gets executed, printing out the string “finally”.
Notice the second catch block only processes exceptions thrown by the first try block – it doesn’t belong to the same exception handler as the second try block, thereby taking no action when the ArithmeticException is re-thrown.
Unattempted
When dividing number 1 by 0, we get an ArithmeticException. This exception is then caught by the first catch block and re-thrown. Before the program exits with an exception, the finally block gets executed, printing out the string “finally”.
Notice the second catch block only processes exceptions thrown by the first try block – it doesn’t belong to the same exception handler as the second try block, thereby taking no action when the ArithmeticException is re-thrown.
Question 53 of 65
53. Question
Which of the following code fragment compiles?
Correct
Option A is incorrect as variables i and j are defined in the initialization expression and aren’t visible outside of the for construct.
Option B is incorrect as variable i is defined twice: the first is right before the for construct and the second is in the initialization expression;
Option C is incorrect as variable i is defined in the initialization expression but never be set a value, hence its existence in the System.out.println statement leads to a compile-time error.
Option D is incorrect as the if/else construct makes the last statement unreachable, which also results in a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Incorrect
Option A is incorrect as variables i and j are defined in the initialization expression and aren’t visible outside of the for construct.
Option B is incorrect as variable i is defined twice: the first is right before the for construct and the second is in the initialization expression;
Option C is incorrect as variable i is defined in the initialization expression but never be set a value, hence its existence in the System.out.println statement leads to a compile-time error.
Option D is incorrect as the if/else construct makes the last statement unreachable, which also results in a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Unattempted
Option A is incorrect as variables i and j are defined in the initialization expression and aren’t visible outside of the for construct.
Option B is incorrect as variable i is defined twice: the first is right before the for construct and the second is in the initialization expression;
Option C is incorrect as variable i is defined in the initialization expression but never be set a value, hence its existence in the System.out.println statement leads to a compile-time error.
Option D is incorrect as the if/else construct makes the last statement unreachable, which also results in a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Given:
List list = new ArrayList<>(List.of(1, 2));
list.add(1, 3);
System.out.println(list);
What is the output of the given code?
Correct
The add method with two parameters inserts the specified element, denoted by the second parameter, at the specified location, denoted by the first parameter.
In the given code fragment, number 3 is inserted at position 1, hence the resulting list is [1, 3, 2].
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Incorrect
The add method with two parameters inserts the specified element, denoted by the second parameter, at the specified location, denoted by the first parameter.
In the given code fragment, number 3 is inserted at position 1, hence the resulting list is [1, 3, 2].
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Unattempted
The add method with two parameters inserts the specified element, denoted by the second parameter, at the specified location, denoted by the first parameter.
In the given code fragment, number 3 is inserted at position 1, hence the resulting list is [1, 3, 2].
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Question 56 of 65
56. Question
Given an output:
bar,java.base
Which command may produce such an output on the console?
Correct
Here’s a description of the –print-module-deps option of the jdeps command:
Same as –list-reduced-deps with printing a comma-separated list of module dependencies. The output can be used by jlink –add-modules to create a custom image that contains those modules and their transitive dependencies.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Incorrect
Here’s a description of the –print-module-deps option of the jdeps command:
Same as –list-reduced-deps with printing a comma-separated list of module dependencies. The output can be used by jlink –add-modules to create a custom image that contains those modules and their transitive dependencies.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Unattempted
Here’s a description of the –print-module-deps option of the jdeps command:
Same as –list-reduced-deps with printing a comma-separated list of module dependencies. The output can be used by jlink –add-modules to create a custom image that contains those modules and their transitive dependencies.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Question 57 of 65
57. Question
Given:
class Foo {
Object methodA() { return null; }
String methodB() { return “”; }
}
class Bar extends Foo {
// int methodA() { return 0; } // Line 1
// Integer methodA() { return 0; } // Line 2
// Object methodB() { return null; } // Line 3
// void methodB() { } // Line 4
// StringBuilder methodB() { } // Line 5
}
Which line can be uncommented without introducing a compile-time error?
Correct
In the Foo class, methodA has return type Object. In order to override this method, a method in the Bar class must has a return type that is a subtype of Object. On line 1, the return type is a primitive type, hence invalid. On line 2, the return type is a subclass of Object, meaning this line can be uncommented.
Meanwhile, methodB in the Foo class has return type String. None of the methods named methodB in the Bar class has a return type that is a subtype of String. As a result, lines 3, 4 and 5 are all invalid.
Incorrect
In the Foo class, methodA has return type Object. In order to override this method, a method in the Bar class must has a return type that is a subtype of Object. On line 1, the return type is a primitive type, hence invalid. On line 2, the return type is a subclass of Object, meaning this line can be uncommented.
Meanwhile, methodB in the Foo class has return type String. None of the methods named methodB in the Bar class has a return type that is a subtype of String. As a result, lines 3, 4 and 5 are all invalid.
Unattempted
In the Foo class, methodA has return type Object. In order to override this method, a method in the Bar class must has a return type that is a subtype of Object. On line 1, the return type is a primitive type, hence invalid. On line 2, the return type is a subclass of Object, meaning this line can be uncommented.
Meanwhile, methodB in the Foo class has return type String. None of the methods named methodB in the Bar class has a return type that is a subtype of String. As a result, lines 3, 4 and 5 are all invalid.
Question 58 of 65
58. Question
Given:
Integer[] array = {1, 2};
List list = Arrays.asList(array);
list.set(0, 2);
array[1] = 1;
System.out.println(Arrays.toString(array));
System.out.println(list);
What is the output of the given code fragment?
Correct
As per the JDK API Specification, the asList method returns a fixed-size list backed by the specified array. (Changes to the returned list “write through” to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray().
Since all the changes are written through, the created list and its backing array contain the same elements. These are set for the last time in the two statements following the invocation of the asList method.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#asList(T…)
Incorrect
As per the JDK API Specification, the asList method returns a fixed-size list backed by the specified array. (Changes to the returned list “write through” to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray().
Since all the changes are written through, the created list and its backing array contain the same elements. These are set for the last time in the two statements following the invocation of the asList method.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#asList(T…)
Unattempted
As per the JDK API Specification, the asList method returns a fixed-size list backed by the specified array. (Changes to the returned list “write through” to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray().
Since all the changes are written through, the created list and its backing array contain the same elements. These are set for the last time in the two statements following the invocation of the asList method.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#asList(T…)
Question 59 of 65
59. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.loop(0);
}
void loop(int number) {
for ( ; ; ) {
if (number < 10) {
System.out.println(number);
break;
}
}
}
}
What is the program's output?
Correct
All expressions, including initialization, termination and increment, in the for loop are empty. This may look weird but is entirely valid. Instead of relying on such expressions, we must control the for loop using statements in its body.
In the first iteration, variable number starts with the value of 0, making the if expression evaluate to true. Since the body of the if statement is executed, number 0 is printed and the break statement terminates the for loop.
As a result, only number 0 is printed to the console.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Incorrect
All expressions, including initialization, termination and increment, in the for loop are empty. This may look weird but is entirely valid. Instead of relying on such expressions, we must control the for loop using statements in its body.
In the first iteration, variable number starts with the value of 0, making the if expression evaluate to true. Since the body of the if statement is executed, number 0 is printed and the break statement terminates the for loop.
As a result, only number 0 is printed to the console.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Unattempted
All expressions, including initialization, termination and increment, in the for loop are empty. This may look weird but is entirely valid. Instead of relying on such expressions, we must control the for loop using statements in its body.
In the first iteration, variable number starts with the value of 0, making the if expression evaluate to true. Since the body of the if statement is executed, number 0 is printed and the break statement terminates the for loop.
As a result, only number 0 is printed to the console.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Question 60 of 65
60. Question
Given:
import java.util.List;
package test;
public class MyTest {
public static void main(String[] args) {
List numbers = List.of();
for (int number : numbers) {
System.out.print(number + “===”);
}
}
}
What is the program’s output?
Correct
If existent, the package statement must be the first in a source file, before any other statement. In the given code, the package statement follows an import one, resulting in a compile-time error.
Incorrect
If existent, the package statement must be the first in a source file, before any other statement. In the given code, the package statement follows an import one, resulting in a compile-time error.
Unattempted
If existent, the package statement must be the first in a source file, before any other statement. In the given code, the package statement follows an import one, resulting in a compile-time error.
Question 61 of 65
61. Question
Given:
List strings = new ArrayList<>();
strings.addAll(List.of(“A”, “B”));
System.out.println(strings.remove(0));
System.out.println(strings.remove(“A”));
System.out.println(strings.remove(“B”));
What is the output of the given code fragment?
Correct
The remove method with an int parameter removes the element at the specified position and returns the element itself. Thus, the first calling of remove in the given code returns “A”.
The other overloaded method, the one with an Object parameter, removes the first occurrence of the specified element, returning true if the list contains such an element and false otherwise. After the first removal, our list has only one element left: “B”. This means the removal of “A” returns false while that of “B” returns true.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#remove(int) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#remove(java.lang.Object)
Incorrect
The remove method with an int parameter removes the element at the specified position and returns the element itself. Thus, the first calling of remove in the given code returns “A”.
The other overloaded method, the one with an Object parameter, removes the first occurrence of the specified element, returning true if the list contains such an element and false otherwise. After the first removal, our list has only one element left: “B”. This means the removal of “A” returns false while that of “B” returns true.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#remove(int) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#remove(java.lang.Object)
Unattempted
The remove method with an int parameter removes the element at the specified position and returns the element itself. Thus, the first calling of remove in the given code returns “A”.
The other overloaded method, the one with an Object parameter, removes the first occurrence of the specified element, returning true if the list contains such an element and false otherwise. After the first removal, our list has only one element left: “B”. This means the removal of “A” returns false while that of “B” returns true.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#remove(int) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#remove(java.lang.Object)
Question 62 of 65
62. Question
Given:
class Foo {
Foo(String input) /* Position 1 */ {
if (input == null) {
return; /* Position 2 */
} else {
throw new IOException();
}
}
}
public class Test {
public static void main(String[] args) {
try {
new Foo(null /* Position 3 */);
} catch (Exception /* Position 4 */) e{
e.printStackTrace();
}
}
}
Which of the following change enables the given program to compile?
Correct
The Foo constructor may throw an IOException. This is a checked exception, thus must be caught or specified. The solution in option A specifies this exception on the constructor’s declaration, which solves the issue.
Incorrect
The Foo constructor may throw an IOException. This is a checked exception, thus must be caught or specified. The solution in option A specifies this exception on the constructor’s declaration, which solves the issue.
Unattempted
The Foo constructor may throw an IOException. This is a checked exception, thus must be caught or specified. The solution in option A specifies this exception on the constructor’s declaration, which solves the issue.
Question 63 of 65
63. Question
Given:
package foo;
public abstract class MyFoo {
abstract void m();
}
And:
package bar;
import foo.MyFoo;
public class MyBar extends MyFoo {
void m() {
// A valid body
}
}
Which of the following changes enables the given code to compile?
Correct
The MyBar class extends MyFoo but doesn’t inherit its abstract method, which is package-private. This means MyBar doesn’t override the m method defined in MyFoo, resulting in a compile-time error.
Option A is incorrect since such a change would lead to the overriding method having weaker access privilege than the overridden one. Such an overriding behavior is forbidden.
Option B is incorrect as such a change doesn’t modify the fact that MyBar doesn’t have access to the m method in MyFoo, hence cannot override it.
Option C is incorrect as MyFoo would become a non-abstract class that contains an abstract method. This kind of class declaration is invalid.
Option D is correct as this change would turn MyBar into an abstract class, which doesn’t need to override any abstract methods in its super-classes.
Incorrect
The MyBar class extends MyFoo but doesn’t inherit its abstract method, which is package-private. This means MyBar doesn’t override the m method defined in MyFoo, resulting in a compile-time error.
Option A is incorrect since such a change would lead to the overriding method having weaker access privilege than the overridden one. Such an overriding behavior is forbidden.
Option B is incorrect as such a change doesn’t modify the fact that MyBar doesn’t have access to the m method in MyFoo, hence cannot override it.
Option C is incorrect as MyFoo would become a non-abstract class that contains an abstract method. This kind of class declaration is invalid.
Option D is correct as this change would turn MyBar into an abstract class, which doesn’t need to override any abstract methods in its super-classes.
Unattempted
The MyBar class extends MyFoo but doesn’t inherit its abstract method, which is package-private. This means MyBar doesn’t override the m method defined in MyFoo, resulting in a compile-time error.
Option A is incorrect since such a change would lead to the overriding method having weaker access privilege than the overridden one. Such an overriding behavior is forbidden.
Option B is incorrect as such a change doesn’t modify the fact that MyBar doesn’t have access to the m method in MyFoo, hence cannot override it.
Option C is incorrect as MyFoo would become a non-abstract class that contains an abstract method. This kind of class declaration is invalid.
Option D is correct as this change would turn MyBar into an abstract class, which doesn’t need to override any abstract methods in its super-classes.
Question 64 of 65
64. Question
Given:
class Foo {
static String foo = init();
Foo() {
System.out.println(“Super”);
}
static String init() {
System.out.println(“Init Foo”);
return “Foo”;
}
}
public class Bar extends Foo {
static String bar = init();
Bar() {
System.out.println(“Sub”);
}
static String init() {
System.out.println(“Init Bar”);
return “Bar”;
}
public static void main(String[] args) {
new Bar();
}
}
What is the output?
Correct
When classes are loaded, all static fields are initialized, and static methods/initialization blocks are executed. Thus, the strings “Init Foo” and “Init Bar” are printed prior to “Super” and “Sub”.
The Bar class extends Foo, thus has a dependency on this superclass. As a result, Foo is loaded before Bar, meaning “Init Foo” is printed before “Init Bar”.
When the no-argument constructor of the Bar class is invoked, it makes a call to the no-argument constructor of the Foo class. Therefore, the string “Super” goes before “Sub”.
Incorrect
When classes are loaded, all static fields are initialized, and static methods/initialization blocks are executed. Thus, the strings “Init Foo” and “Init Bar” are printed prior to “Super” and “Sub”.
The Bar class extends Foo, thus has a dependency on this superclass. As a result, Foo is loaded before Bar, meaning “Init Foo” is printed before “Init Bar”.
When the no-argument constructor of the Bar class is invoked, it makes a call to the no-argument constructor of the Foo class. Therefore, the string “Super” goes before “Sub”.
Unattempted
When classes are loaded, all static fields are initialized, and static methods/initialization blocks are executed. Thus, the strings “Init Foo” and “Init Bar” are printed prior to “Super” and “Sub”.
The Bar class extends Foo, thus has a dependency on this superclass. As a result, Foo is loaded before Bar, meaning “Init Foo” is printed before “Init Bar”.
When the no-argument constructor of the Bar class is invoked, it makes a call to the no-argument constructor of the Foo class. Therefore, the string “Super” goes before “Sub”.
Question 65 of 65
65. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
int sum = test.sumUp(List.of(1, 2, 3, 4, 5));
System.out.println(sum);
}
int sumUp(List numbers) {
int sum = 0;
myLabel:
do {
for (int number : numbers) {
if (number == 3) break myLabel;
sum += number;
}
} while (sum < 15);
return sum;
}
}
What is the program's output?
Correct
During the first iteration of the do/while construct, when the variable number reaches 3, the break statement gets executed. This is a labeled statement, terminating the do/while construct instead of the for loop. At this point, the value of variable sum is 3, which is the sum of the first two numbers.
Incorrect
During the first iteration of the do/while construct, when the variable number reaches 3, the break statement gets executed. This is a labeled statement, terminating the do/while construct instead of the for loop. At this point, the value of variable sum is 3, which is the sum of the first two numbers.
Unattempted
During the first iteration of the do/while construct, when the variable number reaches 3, the break statement gets executed. This is a labeled statement, terminating the do/while construct instead of the for loop. At this point, the value of variable sum is 3, which is the sum of the first two numbers.
X
Use Page numbers below to navigate to other practice tests