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 10 "
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 a code fragment:
byte b = (byte) ‘b’;
b++;
short s = b;
System.out.println(s – 1);
What is the output when the code is run?
Correct
The char primitive data type represents single 16-bit Unicode characters. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).
Letter b has a Unicode value of 98. The casting in the first statement simply converts this number from the char type to byte.
The third statement is a data type promotion from byte to short – it doesn’t need a casting operator.
The value of variable b gets increased by 1 in the second statement, then decreased by the same amount in the last statement. As a result, the output of the program is the Unicode value of letter b.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Incorrect
The char primitive data type represents single 16-bit Unicode characters. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).
Letter b has a Unicode value of 98. The casting in the first statement simply converts this number from the char type to byte.
The third statement is a data type promotion from byte to short – it doesn’t need a casting operator.
The value of variable b gets increased by 1 in the second statement, then decreased by the same amount in the last statement. As a result, the output of the program is the Unicode value of letter b.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Unattempted
The char primitive data type represents single 16-bit Unicode characters. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).
Letter b has a Unicode value of 98. The casting in the first statement simply converts this number from the char type to byte.
The third statement is a data type promotion from byte to short – it doesn’t need a casting operator.
The value of variable b gets increased by 1 in the second statement, then decreased by the same amount in the last statement. As a result, the output of the program is the Unicode value of letter b.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Question 2 of 65
2. Question
Given:
double x = 3, y = 2;
double z = x % y;
System.out.println(z);
What is the output when executing the code fragment?
Correct
When an operation has an operand is of the double type, its result’s data type is also double.
In the given code fragment, the modulo operation 3 % 2 results in a value of 1, and the double form of this value is 1.0.
Incorrect
When an operation has an operand is of the double type, its result’s data type is also double.
In the given code fragment, the modulo operation 3 % 2 results in a value of 1, and the double form of this value is 1.0.
Unattempted
When an operation has an operand is of the double type, its result’s data type is also double.
In the given code fragment, the modulo operation 3 % 2 results in a value of 1, and the double form of this value is 1.0.
Question 3 of 65
3. Question
Which of the following is not an advantage of exception handling?
Correct
The first three options describe the advantages of exception handling, documented by Oracle.
Option D is incorrect as exception handling cannot keep the program from falling through if an error, such as OutOfMemoryError, occurs.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/advantages.html
Incorrect
The first three options describe the advantages of exception handling, documented by Oracle.
Option D is incorrect as exception handling cannot keep the program from falling through if an error, such as OutOfMemoryError, occurs.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/advantages.html
Unattempted
The first three options describe the advantages of exception handling, documented by Oracle.
Option D is incorrect as exception handling cannot keep the program from falling through if an error, such as OutOfMemoryError, occurs.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/advantages.html
Question 4 of 65
4. Question
Given:
interface Foo {
void myMethod();
}
public class Bar implements Foo {
// method declarations
}
Which method can be declared within the Bar class to make it compile?
Correct
The Bar class is concrete, hence must contain no abstract method. Option A is incorrect then.
All methods in an interface is public by default. This means all overriding methods must also be public as well. As a result, all the other methods are incorrect as well.
Incorrect
The Bar class is concrete, hence must contain no abstract method. Option A is incorrect then.
All methods in an interface is public by default. This means all overriding methods must also be public as well. As a result, all the other methods are incorrect as well.
Unattempted
The Bar class is concrete, hence must contain no abstract method. Option A is incorrect then.
All methods in an interface is public by default. This means all overriding methods must also be public as well. As a result, all the other methods are incorrect as well.
Question 5 of 65
5. Question
Given a module declaration:
module foo {
exports foo;
exports bar;
}
Which of the following is the correct module graph?
Correct
There’s only one explicit module, and this module depends on the base module like any other module. Thus, option A is correct.
Notice the exports directive specify packages – it has nothing to do with the module graph. In the given module, two packages, foo and bar, are exported. One of these packages just happens to have the same name as the module.
Incorrect
There’s only one explicit module, and this module depends on the base module like any other module. Thus, option A is correct.
Notice the exports directive specify packages – it has nothing to do with the module graph. In the given module, two packages, foo and bar, are exported. One of these packages just happens to have the same name as the module.
Unattempted
There’s only one explicit module, and this module depends on the base module like any other module. Thus, option A is correct.
Notice the exports directive specify packages – it has nothing to do with the module graph. In the given module, two packages, foo and bar, are exported. One of these packages just happens to have the same name as the module.
Question 6 of 65
6. Question
Given:
public class Test {
String concatWithMethod(String[] array) {
return array[0].concat(array[1]);
}
String concatWithOperator(String[] array) {
return array[0] + array[1];
}
public static void main(String[] args) {
Test test = new Test();
String[] array = new String[2];
String result1 = test.concatWithMethod(array);
String result2 = test.concatWithOperator(array);
System.out.println(result1 == result2);
}
}
What is the output of the program?
Correct
When the program starts, an array with two elements is created. These elements aren’t initialized, thus they both have value null. As a result, the invocation of the concat method inside concatWithMethod is on a null object, which leads to a NullPointerException.
Incorrect
When the program starts, an array with two elements is created. These elements aren’t initialized, thus they both have value null. As a result, the invocation of the concat method inside concatWithMethod is on a null object, which leads to a NullPointerException.
Unattempted
When the program starts, an array with two elements is created. These elements aren’t initialized, thus they both have value null. As a result, the invocation of the concat method inside concatWithMethod is on a null object, which leads to a NullPointerException.
Question 7 of 65
7. Question
Given:
int[] array1 = {1, 2, 3, 4};
int[] array2 = new int[5];
for (int i = 0; i < array1.length; i++) {
array2[i] = array1[i];
}
System.out.println(array2[4]);
What is the output when executing the given code?
Correct
When an array is created with the new operator, all elements of the array are initialized with the default value of their type. In the given code, elements of array2 are of the int type, thus they are all set to 0 when the array is created.
In the for loop, elements in array2 are set to the values of the corresponding elements in array1. The last element at index 4, however, is not set, meaning it still holds the original value.
Incorrect
When an array is created with the new operator, all elements of the array are initialized with the default value of their type. In the given code, elements of array2 are of the int type, thus they are all set to 0 when the array is created.
In the for loop, elements in array2 are set to the values of the corresponding elements in array1. The last element at index 4, however, is not set, meaning it still holds the original value.
Unattempted
When an array is created with the new operator, all elements of the array are initialized with the default value of their type. In the given code, elements of array2 are of the int type, thus they are all set to 0 when the array is created.
In the for loop, elements in array2 are set to the values of the corresponding elements in array1. The last element at index 4, however, is not set, meaning it still holds the original value.
Question 8 of 65
8. Question
Given:
class Foo {
public String text = “Hello”;
public static String myMethod() {
return new Foo().text;
}
}
public class Bar extends Foo {
static String text = “Bonjour”;
static String myMethod() {
return text;
}
public static void main(String[] args) {
Foo foo = new Bar();
System.out.println(foo.text);
System.out.println(foo.myMethod());
}
}
What is the program’s output?
Correct
When overriding or hiding a method inherited from a superclass, the method in the subclass mustn’t have weaker access privilege.
In the given code, the myMethod method in class Foo has access modifier public, but the one in the Bar class has no modifier, meaning the overriding method is package private. This violation results in a compile-time error.
Notice that even though the text field in class Bar is more restrictive than the field of the same name in class Foo, it doesn’t prevent the program from compiling. The reason is that a subclass’s field always hides a superclass’s field if they have the same name regardless of how the modifiers they carry.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Incorrect
When overriding or hiding a method inherited from a superclass, the method in the subclass mustn’t have weaker access privilege.
In the given code, the myMethod method in class Foo has access modifier public, but the one in the Bar class has no modifier, meaning the overriding method is package private. This violation results in a compile-time error.
Notice that even though the text field in class Bar is more restrictive than the field of the same name in class Foo, it doesn’t prevent the program from compiling. The reason is that a subclass’s field always hides a superclass’s field if they have the same name regardless of how the modifiers they carry.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Unattempted
When overriding or hiding a method inherited from a superclass, the method in the subclass mustn’t have weaker access privilege.
In the given code, the myMethod method in class Foo has access modifier public, but the one in the Bar class has no modifier, meaning the overriding method is package private. This violation results in a compile-time error.
Notice that even though the text field in class Bar is more restrictive than the field of the same name in class Foo, it doesn’t prevent the program from compiling. The reason is that a subclass’s field always hides a superclass’s field if they have the same name regardless of how the modifiers they carry.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Question 9 of 65
9. Question
Given:
try {
throw new IOException();
} catch (RuntimeException | IOException e) { // Line 1
if (e instanceof IOException) {
e = new RuntimeException(e); // Line 2
throw e;
}
}
What is the result?
Correct
If a catch block handles more than one exception type, then the catch parameter is implicitly final. In the given code, a new exception object is assigned to variable e, resulting in a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Incorrect
If a catch block handles more than one exception type, then the catch parameter is implicitly final. In the given code, a new exception object is assigned to variable e, resulting in a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Unattempted
If a catch block handles more than one exception type, then the catch parameter is implicitly final. In the given code, a new exception object is assigned to variable e, resulting in a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Question 10 of 65
10. Question
Given:
StringBuilder builder1 = new StringBuilder(/* Position 1 */);
StringBuilder builder2 = new StringBuilder(“Hello”);
int cap1 = builder1.capacity();
int cap2 = builder2.capacity();
System.out.println(cap1 == cap2);
Which number when inserted at position 1 makes the given code print true to the console?
When a field is initialized with an expression, this expression can be considered an initialization block. During compilation, the body of each instance initialization block is copied to all the constructors in the order the block is declared. This copied code is placed right before the existing code in those constructors. The bytecode of the given program looks similar to this:
public class Test {
When a field is initialized with an expression, this expression can be considered an initialization block. During compilation, the body of each instance initialization block is copied to all the constructors in the order the block is declared. This copied code is placed right before the existing code in those constructors. The bytecode of the given program looks similar to this:
public class Test {
When a field is initialized with an expression, this expression can be considered an initialization block. During compilation, the body of each instance initialization block is copied to all the constructors in the order the block is declared. This copied code is placed right before the existing code in those constructors. The bytecode of the given program looks similar to this:
public class Test {
abstract class Baz extends Bar implements Foo { // Line 1
@Override // Line 2
public abstract void methodA(); // Line 3
@Override // Line 4
public abstract void methodB(); // Line 5
}
Which line of code causes a compile-time error?
Correct
A class can always override instance methods in its super-classes and super-interfaces, regardless of whether it’s abstract or not. Therefore, there’s nothing wrong with the given code.
Incorrect
A class can always override instance methods in its super-classes and super-interfaces, regardless of whether it’s abstract or not. Therefore, there’s nothing wrong with the given code.
Unattempted
A class can always override instance methods in its super-classes and super-interfaces, regardless of whether it’s abstract or not. Therefore, there’s nothing wrong with the given code.
Question 13 of 65
13. Question
Given:
class Foo {
Foo(String input) {
System.out.print(input + ” “);
}
static {
System.out.print(“hello “);
}
}
public class Test {
static public void main(String[] args) {
Foo foo1 = new Foo(“hi”);
Foo foo2 = new Foo(“hey”);
}
static {
System.out.print(“bye “);
}
}
What is the program’s output?
Correct
When a class is loaded, all of its static fields are initialized, and static initialization blocks are executed. When instances of the class are created, these static members aren’t processed anymore as the class has already been loaded into the memory.
In the given code, the Test class contains the entry method of the program. hence its static initialization block is executed first. Next comes the static initialization block in the Foo class. The statement inside the Foo constructor is executed last – when it’s called explicitly with the new operator.
Incorrect
When a class is loaded, all of its static fields are initialized, and static initialization blocks are executed. When instances of the class are created, these static members aren’t processed anymore as the class has already been loaded into the memory.
In the given code, the Test class contains the entry method of the program. hence its static initialization block is executed first. Next comes the static initialization block in the Foo class. The statement inside the Foo constructor is executed last – when it’s called explicitly with the new operator.
Unattempted
When a class is loaded, all of its static fields are initialized, and static initialization blocks are executed. When instances of the class are created, these static members aren’t processed anymore as the class has already been loaded into the memory.
In the given code, the Test class contains the entry method of the program. hence its static initialization block is executed first. Next comes the static initialization block in the Foo class. The statement inside the Foo constructor is executed last – when it’s called explicitly with the new operator.
Question 14 of 65
14. Question
Given:
double x = 1, y = -2, z = 3;
double t = x / y % (z + (x – y)) * z;
System.out.println(t);
What is the given code’s output?
Correct
Notice multiplicative operators (*, /, %) have higher precedence than additive ones (+, -). These all operators are evaluated from left to right.
However, we can use parentheses to override their precedence. Had all the parentheses been removed, option C would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Incorrect
Notice multiplicative operators (*, /, %) have higher precedence than additive ones (+, -). These all operators are evaluated from left to right.
However, we can use parentheses to override their precedence. Had all the parentheses been removed, option C would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Unattempted
Notice multiplicative operators (*, /, %) have higher precedence than additive ones (+, -). These all operators are evaluated from left to right.
However, we can use parentheses to override their precedence. Had all the parentheses been removed, option C would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Question 15 of 65
15. Question
Given:
String string = “Pa ma pa”;
int index1 = string.indexOf(‘p’);
int index2 = string.indexOf(‘a’, index1);
System.out.println(index2);
What is the output?
Here’s a description of the –generate-module-info option of the jdeps command:
Generates module-info.java under the specified directory. The specified JAR files will be analyzed. This option cannot be used with –dot-output or –class-path options.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Incorrect
Here’s a description of the –generate-module-info option of the jdeps command:
Generates module-info.java under the specified directory. The specified JAR files will be analyzed. This option cannot be used with –dot-output or –class-path options.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Unattempted
Here’s a description of the –generate-module-info option of the jdeps command:
Generates module-info.java under the specified directory. The specified JAR files will be analyzed. This option cannot be used with –dot-output or –class-path options.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Question 17 of 65
17. Question
Given:
int[][] matrix = new int[2][];
matrix[0] = new int[]{1, 2};
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}
System.out.println(sum);
What is the output when executing the given code?
Correct
The matrix two-dimensional array contains two sub-arrays. The first sub-array is initialized with two elements – 1 and 2. The second sub-array, however, is never initialized, hence it’s null. An access to the length field of a null object in the second for loop will result in a NullPointerException.
Incorrect
The matrix two-dimensional array contains two sub-arrays. The first sub-array is initialized with two elements – 1 and 2. The second sub-array, however, is never initialized, hence it’s null. An access to the length field of a null object in the second for loop will result in a NullPointerException.
Unattempted
The matrix two-dimensional array contains two sub-arrays. The first sub-array is initialized with two elements – 1 and 2. The second sub-array, however, is never initialized, hence it’s null. An access to the length field of a null object in the second for loop will result in a NullPointerException.
Question 18 of 65
18. Question
Given:
List list = new ArrayList<>();
list.addAll(List.of(“A”));
list.add(2, “B”);
System.out.println(list);
What is the output of the given code fragment?
Given:
package foo;
public class Greeting {
public String say() {
return “Foo”;
}
}
And:
package bar;
public class Greeting {
public String say() {
return “Bar”;
}
}
And:
package test;
import foo.*;
import bar.Greeting; // Line 1
public class MyTest {
public static void main(String[] args) {
Greeting greeting = new Greeting(); // Line 2
System.out.println(greeting.say());
}
}
What is the program’s output?
Correct
In the given code, the Greeting class is declared in two packages, foo and bar. The import of this class from the bar package is explicit, hence it takes precedence over the import from the foo package.
Incorrect
In the given code, the Greeting class is declared in two packages, foo and bar. The import of this class from the bar package is explicit, hence it takes precedence over the import from the foo package.
Unattempted
In the given code, the Greeting class is declared in two packages, foo and bar. The import of this class from the bar package is explicit, hence it takes precedence over the import from the foo package.
Question 20 of 65
20. Question
Given:
String text = “ab”;
text = text.repeat(2);
text = text.replace(‘a’, ‘c’);
text = text.replace(“b”, “d”);
System.out.println(text);
What is the output?
public static void main(String[] args) {
Test test = new Test();
if (!test.x) { // Line 2
System.out.println(“x = 0”);
} else {
System.out.println(“x != 0”);
}
}
}
What is the program’s output?
Correct
In Java, the type of a variable cannot be changed after it’s declared. This means x is always an int number, while the if expression expects a boolean value. This type mismatch leads to a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Incorrect
In Java, the type of a variable cannot be changed after it’s declared. This means x is always an int number, while the if expression expects a boolean value. This type mismatch leads to a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Unattempted
In Java, the type of a variable cannot be changed after it’s declared. This means x is always an int number, while the if expression expects a boolean value. This type mismatch leads to a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Question 22 of 65
22. Question
Given:
public class Test {
void printMessage(short argument) {
System.out.println(“Argument is short”);
}
void printMessage(Integer argument) {
System.out.println(“Argument is Integer”);
}
void printMessage(long argument) {
System.out.println(“Argument is long”);
}
public static void main(String[] args) {
Test test = new Test();
test.printMessage(1);
}
}
What is the program output?
Correct
The first method has a parameter of the short type, but the printMessage method is called with an int argument. An int value isn’t implicitly cast to a narrower type, thus option A is incorrect.
An int primitive value is applicable to both parameter types Integer and long specified in the two remaining methods. The question is which type has the priority.
As per section 15.12.2 of the Java Language Specification, the process of determining applicability begins by determining the potentially applicable methods. Then, to ensure compatibility with the Java programming language prior to Java SE 5.0, the process continues in three phases:
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.
From the Specification, it’s easy to see long takes precedence over Integer, meaning option C is the correct answer.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Incorrect
The first method has a parameter of the short type, but the printMessage method is called with an int argument. An int value isn’t implicitly cast to a narrower type, thus option A is incorrect.
An int primitive value is applicable to both parameter types Integer and long specified in the two remaining methods. The question is which type has the priority.
As per section 15.12.2 of the Java Language Specification, the process of determining applicability begins by determining the potentially applicable methods. Then, to ensure compatibility with the Java programming language prior to Java SE 5.0, the process continues in three phases:
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.
From the Specification, it’s easy to see long takes precedence over Integer, meaning option C is the correct answer.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Unattempted
The first method has a parameter of the short type, but the printMessage method is called with an int argument. An int value isn’t implicitly cast to a narrower type, thus option A is incorrect.
An int primitive value is applicable to both parameter types Integer and long specified in the two remaining methods. The question is which type has the priority.
As per section 15.12.2 of the Java Language Specification, the process of determining applicability begins by determining the potentially applicable methods. Then, to ensure compatibility with the Java programming language prior to Java SE 5.0, the process continues in three phases:
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.
From the Specification, it’s easy to see long takes precedence over Integer, meaning option C is the correct answer.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Question 23 of 65
23. Question
Given:
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
test.isZero(1);
System.out.println(“try”);
} catch (Exception e1) {
try {
throw new ArithmeticException();
} catch (RuntimeException e2) {
System.out.println(“catch”);
}
} finally {
System.out.println(“finally”);
}
}
void isZero(int input) {
if (input != 0)
throw new RuntimeException();
}
}
What is the program’s output?
Correct
RuntimeException is an unchecked exception, thus we don’t need a throws clause on the declaration of the isZero method.
In the given program, when a RuntimeException is thrown by the isZero method, the last statement within the try block is ignored. This exception is then caught and handled by the outer catch block.
Next, an ArithmeticException is thrown. It’s then caught and handled by the inner catch block. At this point, the string “catch” gets printed. After that, the finally block runs.
Incorrect
RuntimeException is an unchecked exception, thus we don’t need a throws clause on the declaration of the isZero method.
In the given program, when a RuntimeException is thrown by the isZero method, the last statement within the try block is ignored. This exception is then caught and handled by the outer catch block.
Next, an ArithmeticException is thrown. It’s then caught and handled by the inner catch block. At this point, the string “catch” gets printed. After that, the finally block runs.
Unattempted
RuntimeException is an unchecked exception, thus we don’t need a throws clause on the declaration of the isZero method.
In the given program, when a RuntimeException is thrown by the isZero method, the last statement within the try block is ignored. This exception is then caught and handled by the outer catch block.
Next, an ArithmeticException is thrown. It’s then caught and handled by the inner catch block. At this point, the string “catch” gets printed. After that, the finally block runs.
Question 24 of 65
24. Question
Given:
public class Test {
static String text = “foo”;
public static void main(String[] args) {
if (!text.equals(“Foo”)) {
String text = “bar”;
} else {
String text = “baz”;
}
System.out.println(text);
}
}
What is the program’s output?
Correct
When a local variable is defined within a code block, it’s invisible outside of that block. As a result, the final value of variable text isn’t affected by the if-else statement.
Incorrect
When a local variable is defined within a code block, it’s invisible outside of that block. As a result, the final value of variable text isn’t affected by the if-else statement.
Unattempted
When a local variable is defined within a code block, it’s invisible outside of that block. As a result, the final value of variable text isn’t affected by the if-else statement.
Question 25 of 65
25. Question
Which of the following is not a feature of the Java language?
Given:
abstract class Foo {
String getName(); // Line 1
}
class Bar extends Foo {
String getName() { // Line 2
return “Bar”;
}
}
public class Baz extends Bar implements Foo { // Line 3
String getName() { // Line 4
return “Baz”;
}
public static void main(String[] args) {
Baz baz = new Baz(); // Line 5
String name = baz.getName(); // Line 6
System.out.println(name);
}
}
Which two lines cause a compile-time error?
Correct
The only method of the Foo class doesn’t have a body, thus it’s abstract and must carry the abstract modifier. Line 1 is invalid, then.
We can only extend a class regardless of whether it’s abstract or not. On line 3, the Baz class implements the Foo class, which is an invalid declaration.
Incorrect
The only method of the Foo class doesn’t have a body, thus it’s abstract and must carry the abstract modifier. Line 1 is invalid, then.
We can only extend a class regardless of whether it’s abstract or not. On line 3, the Baz class implements the Foo class, which is an invalid declaration.
Unattempted
The only method of the Foo class doesn’t have a body, thus it’s abstract and must carry the abstract modifier. Line 1 is invalid, then.
We can only extend a class regardless of whether it’s abstract or not. On line 3, the Baz class implements the Foo class, which is an invalid declaration.
Question 27 of 65
27. Question
Given:
List strings = new ArrayList<>(List.of(“A”, “B”));
Iterator iterator = strings.iterator();
ListIterator listIterator = strings.listIterator();
boolean same1 = true;
boolean same2 = true;
for (String element : strings) {
if (!(element == iterator.next())) same1 = false;
if (!(element == listIterator.next())) same2 = false;
}
System.out.println(same1 + ” ” + same2);
What is the output of the given code?
Correct
Notice these too constructs are basically the same:
for (Object item : list) {
// do something with item
}
and:
for (Iteratori = list.iterator(); i.hasNext(); ) {
Object item = i.next();
// do something with item
}
Therefore, traversing a list using an iterator is no different than doing so with a for-each loop
Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html
Incorrect
Notice these too constructs are basically the same:
for (Object item : list) {
// do something with item
}
and:
for (Iteratori = list.iterator(); i.hasNext(); ) {
Object item = i.next();
// do something with item
}
Therefore, traversing a list using an iterator is no different than doing so with a for-each loop
Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html
Unattempted
Notice these too constructs are basically the same:
for (Object item : list) {
// do something with item
}
and:
for (Iteratori = list.iterator(); i.hasNext(); ) {
Object item = i.next();
// do something with item
}
Therefore, traversing a list using an iterator is no different than doing so with a for-each loop
Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html
Question 28 of 65
28. Question
Which of the following is correct about a module?
Correct
It’s recommended not to use underscores in module names, but this isn’t a requirement. Option A is incorrect, then.
The name of a module should be the same as the root package. However, this isn’t a requirement either. After all, a module may have multiple root packages. Thus, option B is incorrect.
After compilation, a module-info.java file is compiled into a file named module-info.class, meaning option C is incorrect.
We must always have a root directory for each module, regardless of the number of modules. Therefore, option D is incorrect.
Incorrect
It’s recommended not to use underscores in module names, but this isn’t a requirement. Option A is incorrect, then.
The name of a module should be the same as the root package. However, this isn’t a requirement either. After all, a module may have multiple root packages. Thus, option B is incorrect.
After compilation, a module-info.java file is compiled into a file named module-info.class, meaning option C is incorrect.
We must always have a root directory for each module, regardless of the number of modules. Therefore, option D is incorrect.
Unattempted
It’s recommended not to use underscores in module names, but this isn’t a requirement. Option A is incorrect, then.
The name of a module should be the same as the root package. However, this isn’t a requirement either. After all, a module may have multiple root packages. Thus, option B is incorrect.
After compilation, a module-info.java file is compiled into a file named module-info.class, meaning option C is incorrect.
We must always have a root directory for each module, regardless of the number of modules. Therefore, option D is incorrect.
Question 29 of 65
29. Question
Given:
Correct
When the while condition expression is evaluated, the number variable is compared to 0, then decreased by 1. Since the original value of number is 0, the expression returns false, meaning the body of the while statement is never executed. The final value of variable number is thus the value it got after the condition expression was run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Incorrect
When the while condition expression is evaluated, the number variable is compared to 0, then decreased by 1. Since the original value of number is 0, the expression returns false, meaning the body of the while statement is never executed. The final value of variable number is thus the value it got after the condition expression was run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Unattempted
When the while condition expression is evaluated, the number variable is compared to 0, then decreased by 1. Since the original value of number is 0, the expression returns false, meaning the body of the while statement is never executed. The final value of variable number is thus the value it got after the condition expression was run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Question 30 of 65
30. Question
Given a code fragment:
String[] array1 = {“a”, “b”, “c”, “d”, “e”};
System.out.println(Arrays.toString(array2));
What is the output when executing the given code?
Correct
As per the JDK API Specification, the Arrays#copyOfRange method copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length – from. The length of the returned array will be to – from.
In the given code, the initial index is 1 and the final index is 3, meaning that the returned array contains two elements copied from indices 1 and 2 in the original array.
Incorrect
As per the JDK API Specification, the Arrays#copyOfRange method copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length – from. The length of the returned array will be to – from.
In the given code, the initial index is 1 and the final index is 3, meaning that the returned array contains two elements copied from indices 1 and 2 in the original array.
Unattempted
As per the JDK API Specification, the Arrays#copyOfRange method copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length – from. The length of the returned array will be to – from.
In the given code, the initial index is 1 and the final index is 3, meaning that the returned array contains two elements copied from indices 1 and 2 in the original array.
Question 31 of 65
31. Question
Which two fragments print out the date right after the first Monday of November this year?
Correct
In option B, the argument passed to method withMonth has an incorrect type. This must be an int value instead of enum constant.
In option C, the result is the date following the Monday after the first Sunday of November. It isn’t always the same as the date right after the first Monday. For example, in 2021, the provided code prints out “2021-11-09” instead of “2021-11-02”.
Incorrect
In option B, the argument passed to method withMonth has an incorrect type. This must be an int value instead of enum constant.
In option C, the result is the date following the Monday after the first Sunday of November. It isn’t always the same as the date right after the first Monday. For example, in 2021, the provided code prints out “2021-11-09” instead of “2021-11-02”.
Unattempted
In option B, the argument passed to method withMonth has an incorrect type. This must be an int value instead of enum constant.
In option C, the result is the date following the Monday after the first Sunday of November. It isn’t always the same as the date right after the first Monday. For example, in 2021, the provided code prints out “2021-11-09” instead of “2021-11-02”.
Question 32 of 65
32. Question
Given a source file:
package test;
public class Foo {
// a valid body
}
/* Insert here */ class Bar {
// a valid body
}
Which access modifier can be inserted into the declaration of the Bar class?
Correct
At the top level, a class can only be declared with the public or package-private scope. Notice a source file can only contain at most one top-level pubic type. Considering the fact that the Foo class is public, it’s easy to see the Bar class must be package-private. This means no access modifier can be inserted.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Incorrect
At the top level, a class can only be declared with the public or package-private scope. Notice a source file can only contain at most one top-level pubic type. Considering the fact that the Foo class is public, it’s easy to see the Bar class must be package-private. This means no access modifier can be inserted.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Unattempted
At the top level, a class can only be declared with the public or package-private scope. Notice a source file can only contain at most one top-level pubic type. Considering the fact that the Foo class is public, it’s easy to see the Bar class must be package-private. This means no access modifier can be inserted.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Question 33 of 65
33. Question
Given:
class Foo {
void myMethod() {
System.out.println(“Foo”);
}
}
class Bar {
void myMethod() {
System.out.println(“Bar”);
}
}
public class Test {
public static void main(String[] args) {
Foo foo = new Foo();
Bar bar = (Bar) foo;
bar.myMethod();
}
}
What is the program’s output?
Correct
An object reference type casting can only happen if the reference types on two sides of the casting operator are in the same inheritance chain.
If such a casting operation is declared, the compiler knows for sure that the object referenced by a variable of the old type cannot be assigned to a variable of the new type.
Incorrect
An object reference type casting can only happen if the reference types on two sides of the casting operator are in the same inheritance chain.
If such a casting operation is declared, the compiler knows for sure that the object referenced by a variable of the old type cannot be assigned to a variable of the new type.
Unattempted
An object reference type casting can only happen if the reference types on two sides of the casting operator are in the same inheritance chain.
If such a casting operation is declared, the compiler knows for sure that the object referenced by a variable of the old type cannot be assigned to a variable of the new type.
Question 34 of 65
34. Question
Given:
public class Test {
public static void main(String[] strings) {
String output = “”;
for (String string : strings) {
output += output.concat(” “).concat(string);
}
System.out.println(output);
}
}
What is the output when compiling and executing the given program with the following command?
java Test Foo Bar
Correct
When executing a program with the java command, the first argument is the class name while the remaining are arguments to the program. This means the given program is executed with two arguments: “Foo” and “Bar”.
After the first iteration of the for-each loop, the value of output is “Foo “. In the second iteration, it becomes:
output = “Foo” + “Foo”. concat(” “).concat(string)
The result of this expression is “Foo Foo Bar “.
Incorrect
When executing a program with the java command, the first argument is the class name while the remaining are arguments to the program. This means the given program is executed with two arguments: “Foo” and “Bar”.
After the first iteration of the for-each loop, the value of output is “Foo “. In the second iteration, it becomes:
output = “Foo” + “Foo”. concat(” “).concat(string)
The result of this expression is “Foo Foo Bar “.
Unattempted
When executing a program with the java command, the first argument is the class name while the remaining are arguments to the program. This means the given program is executed with two arguments: “Foo” and “Bar”.
After the first iteration of the for-each loop, the value of output is “Foo “. In the second iteration, it becomes:
output = “Foo” + “Foo”. concat(” “).concat(string)
The result of this expression is “Foo Foo Bar “.
Question 35 of 65
35. Question
Given:
List list = new ArrayList<>(List.of(“A”, “A”));
String[] array = list.toArray();
for (int i = 0; i < list.size(); i++) {
list.set(i, list.get(i).toLowerCase());
}
System.out.println(Arrays.toString(array));
What is the output of the given code?
Correct
The toArray method with no parameter returns an array of Object instances. In the given code, the return value of this method is assigned to an array of strings. This type mismatch leads to a compile-time error.
Had the type of the array variable been Object[], option B would have been the correct answer. The reason is that this overloaded toArray method always allocates a new array – any change to the original list doesn’t affect the derived array.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#toArray()
Incorrect
The toArray method with no parameter returns an array of Object instances. In the given code, the return value of this method is assigned to an array of strings. This type mismatch leads to a compile-time error.
Had the type of the array variable been Object[], option B would have been the correct answer. The reason is that this overloaded toArray method always allocates a new array – any change to the original list doesn’t affect the derived array.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#toArray()
Unattempted
The toArray method with no parameter returns an array of Object instances. In the given code, the return value of this method is assigned to an array of strings. This type mismatch leads to a compile-time error.
Had the type of the array variable been Object[], option B would have been the correct answer. The reason is that this overloaded toArray method always allocates a new array – any change to the original list doesn’t affect the derived array.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#toArray()
Question 36 of 65
36. Question
It’s known that this program compiles:
public class Test {
void methodA() throws RuntimeException {
throw new ArithmeticException();
}
void methodB() throws IOException {
throw new FileNotFoundException();
}
void methodC() {
/* Insert here */
}
public static void main(String[] args) {
Test test = new Test();
test.methodC();
}
}
Which of the following can be the body of methodC?
Correct
Option B is incorrect as exception types in a multi-catch block mustn’t be in the same inheritance hierarchy.
Option C is incorrect as the caught exception, which can be a checked exception, is re-thrown without being handled.
Option D is incorrect as methodB specifies IOException in its declaration. This exception type must be handled somewhere up the call stack. The provided code only catches FileNotFoundException, an IOException subtype.
Incorrect
Option B is incorrect as exception types in a multi-catch block mustn’t be in the same inheritance hierarchy.
Option C is incorrect as the caught exception, which can be a checked exception, is re-thrown without being handled.
Option D is incorrect as methodB specifies IOException in its declaration. This exception type must be handled somewhere up the call stack. The provided code only catches FileNotFoundException, an IOException subtype.
Unattempted
Option B is incorrect as exception types in a multi-catch block mustn’t be in the same inheritance hierarchy.
Option C is incorrect as the caught exception, which can be a checked exception, is re-thrown without being handled.
Option D is incorrect as methodB specifies IOException in its declaration. This exception type must be handled somewhere up the call stack. The provided code only catches FileNotFoundException, an IOException subtype.
Question 37 of 65
37. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.loop(1);
}
void loop(int number) {
do {
System.out.println(number–);
} while (number < 0);
}
}
What is the program's output?
Correct
Unlike the while construct, the body of a do/while construct always gets executed at least once, before the condition expression is evaluated.
In the first iteration, the input value 1 is printed to the console. Then the condition expression returns false. At this point, the do/while construct exits, and no more iterations are run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Incorrect
Unlike the while construct, the body of a do/while construct always gets executed at least once, before the condition expression is evaluated.
In the first iteration, the input value 1 is printed to the console. Then the condition expression returns false. At this point, the do/while construct exits, and no more iterations are run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Unattempted
Unlike the while construct, the body of a do/while construct always gets executed at least once, before the condition expression is evaluated.
In the first iteration, the input value 1 is printed to the console. Then the condition expression returns false. At this point, the do/while construct exits, and no more iterations are run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Question 38 of 65
38. Question
Given:
public class Person {
String name;
int age;
public String toString() {
return name + “: ” + age;
}
}
And:
public class Test {
static public void main(String[] args) {
Person person = new Person();
person.name = “John”;
person.age = 30;
String string = String.valueOf(person);
person.name = “Jane”;
person.age = 20;
System.out.println(string);
}
}
What is the output of the given program?
Correct
The String#valueOf method returns the string representation of the object argument. In the given code, this argument is an instance of the Person class, which provides an implementation for the toString method.
Notice String is an immutable class – once a String instance is created, it will never be changed. Therefore, the output reflects the original string representation of the Person object.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#valueOf(java.lang.Object)
Incorrect
The String#valueOf method returns the string representation of the object argument. In the given code, this argument is an instance of the Person class, which provides an implementation for the toString method.
Notice String is an immutable class – once a String instance is created, it will never be changed. Therefore, the output reflects the original string representation of the Person object.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#valueOf(java.lang.Object)
Unattempted
The String#valueOf method returns the string representation of the object argument. In the given code, this argument is an instance of the Person class, which provides an implementation for the toString method.
Notice String is an immutable class – once a String instance is created, it will never be changed. Therefore, the output reflects the original string representation of the Person object.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#valueOf(java.lang.Object)
Question 39 of 65
39. Question
Given:
public class Test {
Test(String arg1, String arg2) {
System.out.println(“Two parameters”);
this(arg1 + ” ” + arg2);
}
Test(String arg) {
System.out.println(“One parameter”);
System.out.println(arg);
}
public static void main(String[] args) {
new Test(“Foo”, “Bar”);
}
}
What is the program’s output?
Correct
A call to this() inside a constructor, if any, must be the first statement. This isn’t the case over here, hence a compile-time error occurs in the two-parameter constructor.
Incorrect
A call to this() inside a constructor, if any, must be the first statement. This isn’t the case over here, hence a compile-time error occurs in the two-parameter constructor.
Unattempted
A call to this() inside a constructor, if any, must be the first statement. This isn’t the case over here, hence a compile-time error occurs in the two-parameter constructor.
Question 40 of 65
40. Question
Which option specify the location of input source files when compiling modules with the javac command?
Given:
List original = new ArrayList<>();
original.add(“A”);
List copy = List.copyOf(original);
copy.set(1, “B”);
System.out.println(original);
What is the output of the given code?
Given:
Object[][] strings = new String[2][2]; // Line 1
strings[1][1] = “test”;
strings[0] = new String[1]; // Line 2
strings[1] = new String[3]; // Line 3
System.out.println(strings[1][1]);
What is the output of the given code fragment?
Correct
There’s nothing wrong on line 1 as the element type String on the left-hand side of the assignment is a subtype of the Object class.
On lines 2 and 3, elements of the two-dimensional strings array are set to new one-dimensional arrays. All elements of the new arrays are initialized to the default value of the String data type, which is null. This is the value that gets printed.
Incorrect
There’s nothing wrong on line 1 as the element type String on the left-hand side of the assignment is a subtype of the Object class.
On lines 2 and 3, elements of the two-dimensional strings array are set to new one-dimensional arrays. All elements of the new arrays are initialized to the default value of the String data type, which is null. This is the value that gets printed.
Unattempted
There’s nothing wrong on line 1 as the element type String on the left-hand side of the assignment is a subtype of the Object class.
On lines 2 and 3, elements of the two-dimensional strings array are set to new one-dimensional arrays. All elements of the new arrays are initialized to the default value of the String data type, which is null. This is the value that gets printed.
Question 43 of 65
43. Question
Given:
public class Test {
static int number;
static public void main(String[] args) {
int number = 1; // Line 1
Test test = new Test();
if (test != null) {
int number = 2; // Line 2
}
System.out.println(number);
}
}
What is the program’s output?
Correct
When a variable is declared in a method or a block, it’s visible in all statements within the same method or block that follow the variable declaration.
In the given code, the number variable declared on line 1 is visible to the if construct. The variable declaration on line 2 is therefore a re-declaration, leading to a compile-time error.
Notice on line 1, the number local variable just shadows the class field of the same name, thus no compilation error occurs.
Incorrect
When a variable is declared in a method or a block, it’s visible in all statements within the same method or block that follow the variable declaration.
In the given code, the number variable declared on line 1 is visible to the if construct. The variable declaration on line 2 is therefore a re-declaration, leading to a compile-time error.
Notice on line 1, the number local variable just shadows the class field of the same name, thus no compilation error occurs.
Unattempted
When a variable is declared in a method or a block, it’s visible in all statements within the same method or block that follow the variable declaration.
In the given code, the number variable declared on line 1 is visible to the if construct. The variable declaration on line 2 is therefore a re-declaration, leading to a compile-time error.
Notice on line 1, the number local variable just shadows the class field of the same name, thus no compilation error occurs.
Question 44 of 65
44. Question
Given:
class Data { }
class Test {
Data createData() {
Data a = new Data(); // Line 0
Data b = new Data();
Data c = a; // Line 1
b = c; // Line 2
a = null; // Line 3
c = null; // Line 4
return b; // Line 5
}
}
After which line the object created on line 0 is eligible for garbage collection?
Correct
When the mentioned object is created, it’s referenced by only variable a. After that, on lines 2 and 3, variables c and b are set to this object as well. Variable b is never set again, and its referenced object is returned to the caller of the createData method. As a result, the object created on line 0 isn’t ready to be collected even after the method returns.
Incorrect
When the mentioned object is created, it’s referenced by only variable a. After that, on lines 2 and 3, variables c and b are set to this object as well. Variable b is never set again, and its referenced object is returned to the caller of the createData method. As a result, the object created on line 0 isn’t ready to be collected even after the method returns.
Unattempted
When the mentioned object is created, it’s referenced by only variable a. After that, on lines 2 and 3, variables c and b are set to this object as well. Variable b is never set again, and its referenced object is returned to the caller of the createData method. As a result, the object created on line 0 isn’t ready to be collected even after the method returns.
Question 45 of 65
45. Question
Given:
for (int i = 0; i < 6; i++) {
if (i % 3 != 0) {
continue;
}
System.out.println(i);
}
What is the output of the given code?
Correct
Each time the i variable reaches a value that isn’t divisible by 3, the for construct jumps to the next iteration. This means only values divisible by 3 are printed.
When variable i goes to 5, which isn’t divisible by 3, the loop’s body is skipped, and i gets increased to 6. Since the termination expression 6 < 6 evaluates to false, number 6 doesn't have a chance to be printed.
Reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Incorrect
Each time the i variable reaches a value that isn’t divisible by 3, the for construct jumps to the next iteration. This means only values divisible by 3 are printed.
When variable i goes to 5, which isn’t divisible by 3, the loop’s body is skipped, and i gets increased to 6. Since the termination expression 6 < 6 evaluates to false, number 6 doesn't have a chance to be printed.
Reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Unattempted
Each time the i variable reaches a value that isn’t divisible by 3, the for construct jumps to the next iteration. This means only values divisible by 3 are printed.
When variable i goes to 5, which isn’t divisible by 3, the loop’s body is skipped, and i gets increased to 6. Since the termination expression 6 < 6 evaluates to false, number 6 doesn't have a chance to be printed.
Reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Question 46 of 65
46. Question
Which kinds of multiple inheritance does Java support?
Correct
Here are some excerpts from the referenced link:
One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes.
Multiple inheritance of implementation is the ability to inherit method definitions from multiple classes. Problems arise with this type of multiple inheritance, such as name conflicts and ambiguity. When compilers of programming languages that support this type of multiple inheritance encounter superclasses that contain methods with the same name, they sometimes cannot determine which member or method to access or invoke.
The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
Incorrect
Here are some excerpts from the referenced link:
One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes.
Multiple inheritance of implementation is the ability to inherit method definitions from multiple classes. Problems arise with this type of multiple inheritance, such as name conflicts and ambiguity. When compilers of programming languages that support this type of multiple inheritance encounter superclasses that contain methods with the same name, they sometimes cannot determine which member or method to access or invoke.
The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
Unattempted
Here are some excerpts from the referenced link:
One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes.
Multiple inheritance of implementation is the ability to inherit method definitions from multiple classes. Problems arise with this type of multiple inheritance, such as name conflicts and ambiguity. When compilers of programming languages that support this type of multiple inheritance encounter superclasses that contain methods with the same name, they sometimes cannot determine which member or method to access or invoke.
The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
Question 47 of 65
47. Question
Given:
package foo;
public class MyFoo {
// Insert here
}
And:
package bar;
import foo.MyFoo;
public class MyBar extends MyFoo {
void printText() {
System.out.println(super.text);
}
}
Which two field declarations allow the given code to compile?
Correct
To be accessible in subclasses in different packages, a field in a superclass must be have the public or protected scope. A field no explicit access modifier is visible within the same package, hence options A and B are invalid.
Notice the super keyword is often used to access an instance member declared in the parent class. However, the compiler doesn’t complain if it’s used for a static class field or method.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/super.html
Incorrect
To be accessible in subclasses in different packages, a field in a superclass must be have the public or protected scope. A field no explicit access modifier is visible within the same package, hence options A and B are invalid.
Notice the super keyword is often used to access an instance member declared in the parent class. However, the compiler doesn’t complain if it’s used for a static class field or method.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/super.html
Unattempted
To be accessible in subclasses in different packages, a field in a superclass must be have the public or protected scope. A field no explicit access modifier is visible within the same package, hence options A and B are invalid.
Notice the super keyword is often used to access an instance member declared in the parent class. However, the compiler doesn’t complain if it’s used for a static class field or method.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/super.html
Question 48 of 65
48. Question
Given:
class Data {
String input;
Data(String input) {
this.input = input;
}
}
public class Test {
Data echo(boolean nullified, Data data) {
return nullified ? null : data;
}
public static void main(String[] args) {
Test test = new Test();
String input = “hello”;
String output = null;
try {
output = test.echo(true, new Data(input = “bye”)).input;
} catch (Exception e) { }
System.out.println(input + ” ” + output);
}
}
What is the program’s output?
Correct
The first argument to the echo method is null, meaning the return value is null as well. When the input field is accessed on this null value, a NullPointerException is thrown. Due to this exception, the output variable isn’t set inside the try-catch statement, and its original value null is never changed.
Notice that the assignment input = “bye” is executed before that exception is thrown. This means the final value of the input variable is “bye”.
Incorrect
The first argument to the echo method is null, meaning the return value is null as well. When the input field is accessed on this null value, a NullPointerException is thrown. Due to this exception, the output variable isn’t set inside the try-catch statement, and its original value null is never changed.
Notice that the assignment input = “bye” is executed before that exception is thrown. This means the final value of the input variable is “bye”.
Unattempted
The first argument to the echo method is null, meaning the return value is null as well. When the input field is accessed on this null value, a NullPointerException is thrown. Due to this exception, the output variable isn’t set inside the try-catch statement, and its original value null is never changed.
Notice that the assignment input = “bye” is executed before that exception is thrown. This means the final value of the input variable is “bye”.
Question 49 of 65
49. Question
Given:
public class Test {
static public void main(String[] args) {
int i = (i = 1) + (i = 2) – ++i + i– * 3;
System.out.println(i);
}
}
What is the program’s output?
Correct
There’s nothing wrong with the given code, hence no compile-time errors.
The i variable is initialized to 1 in the first pair of parentheses, then set to 2 in the second.
Notice value of an assignment is that of the expression on the right-hand side, meaning the expression i = 1 evaluates to 1 and i = 2 does to 2.
With that in mind, we can rewrite the computation statement as:
int i = 2;
i = 3 – ++i + i– * 3;
A pre-increment operation results in the increased value of a variable being used in the surrounding expression, allowing the computation to be written as:
int i = 3;
i = 3 – 3 + i– * 3;
With a post-decrement operator, the original value of the variable rather than the decreased one is used in the computation. At this point, it’s clear that the final value of i is the result of the expression 3 – 3 + 3 * 3, which is 9.
Notice after the expression on the right-hand side is completes, the i variable is set to 2 as the result of the post-decrement operation. This value is overridden right after that when the expression value is assigned to the variable.
Incorrect
There’s nothing wrong with the given code, hence no compile-time errors.
The i variable is initialized to 1 in the first pair of parentheses, then set to 2 in the second.
Notice value of an assignment is that of the expression on the right-hand side, meaning the expression i = 1 evaluates to 1 and i = 2 does to 2.
With that in mind, we can rewrite the computation statement as:
int i = 2;
i = 3 – ++i + i– * 3;
A pre-increment operation results in the increased value of a variable being used in the surrounding expression, allowing the computation to be written as:
int i = 3;
i = 3 – 3 + i– * 3;
With a post-decrement operator, the original value of the variable rather than the decreased one is used in the computation. At this point, it’s clear that the final value of i is the result of the expression 3 – 3 + 3 * 3, which is 9.
Notice after the expression on the right-hand side is completes, the i variable is set to 2 as the result of the post-decrement operation. This value is overridden right after that when the expression value is assigned to the variable.
Unattempted
There’s nothing wrong with the given code, hence no compile-time errors.
The i variable is initialized to 1 in the first pair of parentheses, then set to 2 in the second.
Notice value of an assignment is that of the expression on the right-hand side, meaning the expression i = 1 evaluates to 1 and i = 2 does to 2.
With that in mind, we can rewrite the computation statement as:
int i = 2;
i = 3 – ++i + i– * 3;
A pre-increment operation results in the increased value of a variable being used in the surrounding expression, allowing the computation to be written as:
int i = 3;
i = 3 – 3 + i– * 3;
With a post-decrement operator, the original value of the variable rather than the decreased one is used in the computation. At this point, it’s clear that the final value of i is the result of the expression 3 – 3 + 3 * 3, which is 9.
Notice after the expression on the right-hand side is completes, the i variable is set to 2 as the result of the post-decrement operation. This value is overridden right after that when the expression value is assigned to the variable.
Question 50 of 65
50. Question
Given the source directory structure of a module:
my.foo
moduleinfo.java
foo
Test.java
Which command compiles the given module when executed in the parent folder of my.foo?
Correct
When compiling a module, the module name, module source path and output directory must all be specified.
Incorrect
When compiling a module, the module name, module source path and output directory must all be specified.
Unattempted
When compiling a module, the module name, module source path and output directory must all be specified.
Question 51 of 65
51. Question
Given:
Integer[] array = {3, 2, 1};
Arrays.sort(array, /* Insert here */);
System.out.println(Arrays.toString(array));
Which of the following expressions when inserted into the given code doesn’t product the output [1, 2, 3]?
Correct
Option C is invalid as the parameter types of the lambda expression doesn’t match element type of the array.
Option D is valid as the var keyword is used to infer the types of both parameters.
Options A and B showcase method references, a special form of lambda expressions. They are valid as well.
Incorrect
Option C is invalid as the parameter types of the lambda expression doesn’t match element type of the array.
Option D is valid as the var keyword is used to infer the types of both parameters.
Options A and B showcase method references, a special form of lambda expressions. They are valid as well.
Unattempted
Option C is invalid as the parameter types of the lambda expression doesn’t match element type of the array.
Option D is valid as the var keyword is used to infer the types of both parameters.
Options A and B showcase method references, a special form of lambda expressions. They are valid as well.
Question 52 of 65
52. Question
Given:
for (int i = 0; i < 5; i++, System.out.print(i + " ")) {
i++;
}
What is the output of the given code?
Correct
There’s nothing wrong with the given code. The System.out.print statement is part of the increment expression, which gets executed at the end of each iteration.
Since the variable i is increased in the body of the for construct, then is raised again in the increment expression, the printed value is 2 units larger than the input number at the beginning of an iteration.
Incorrect
There’s nothing wrong with the given code. The System.out.print statement is part of the increment expression, which gets executed at the end of each iteration.
Since the variable i is increased in the body of the for construct, then is raised again in the increment expression, the printed value is 2 units larger than the input number at the beginning of an iteration.
Unattempted
There’s nothing wrong with the given code. The System.out.print statement is part of the increment expression, which gets executed at the end of each iteration.
Since the variable i is increased in the body of the for construct, then is raised again in the increment expression, the printed value is 2 units larger than the input number at the beginning of an iteration.
Question 53 of 65
53. Question
Given a class that is compiled and packaged in a JAR file called foo.jar:
package foo;
public class StringFactory {
public static String createString() {
return “Hello World!”;
}
}
And a source file:
package test;
import foo.StringFactory;
public class Test {
public static void main(String[] args) {
String output = StringFactory.createString();
System.out.println(output);
}
}
The JAR file is put in the working directory, while the source file is located inside the test folder:
foo.jar
test
Test.java
Which statement is correct about the following command when it’s executed:
java -cp . test/Test.java
Correct
There’s nothing wrong with the classpath. Also, if a program contains only a single source file, we can run it with the java command in the source mode. Notice the source mode is turned on by default if the source file’s name ends with .java.
All the solutions mentioned in options A, B, C and D work. However, these options are wrong because the given command doesn’t fail.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Incorrect
There’s nothing wrong with the classpath. Also, if a program contains only a single source file, we can run it with the java command in the source mode. Notice the source mode is turned on by default if the source file’s name ends with .java.
All the solutions mentioned in options A, B, C and D work. However, these options are wrong because the given command doesn’t fail.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Unattempted
There’s nothing wrong with the classpath. Also, if a program contains only a single source file, we can run it with the java command in the source mode. Notice the source mode is turned on by default if the source file’s name ends with .java.
All the solutions mentioned in options A, B, C and D work. However, these options are wrong because the given command doesn’t fail.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Question 54 of 65
54. Question
Given:
String string1 = new String(“Hello”).concat(” “).concat(“World!”);
String string2 = ” Hello World!”.stripLeading(); // 2 leading white-spaces
String string3 = new StringBuilder(“World!”)
.append(“Hello”, 0, 5).append(” “).toString();
String string4 = new StringBuilder(” “)
.insert(0, “Hello”).append(“World!”).toString();
Which variable doesn’t reference a “Hello World!” string?
Correct
The StringBuilder#append method with a CharSequence and two int parameters appends a subsequence of the specified CharSequence to the current sequence. Characters of the first argument, starting at the index specified by the second argument, are appended, in order, to the contents of this sequence up to the (exclusive) the index specified by the last argument.
In the third statement, the first append method takes the first five characters in the “Hello” string, which is the whole string itself, and appends them to the “World!” string. The second append method adds a while-space. As a result, the string3 variable references the “World!Hello ” string.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuilder.html#append(java.lang.CharSequence,int,int)
Incorrect
The StringBuilder#append method with a CharSequence and two int parameters appends a subsequence of the specified CharSequence to the current sequence. Characters of the first argument, starting at the index specified by the second argument, are appended, in order, to the contents of this sequence up to the (exclusive) the index specified by the last argument.
In the third statement, the first append method takes the first five characters in the “Hello” string, which is the whole string itself, and appends them to the “World!” string. The second append method adds a while-space. As a result, the string3 variable references the “World!Hello ” string.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuilder.html#append(java.lang.CharSequence,int,int)
Unattempted
The StringBuilder#append method with a CharSequence and two int parameters appends a subsequence of the specified CharSequence to the current sequence. Characters of the first argument, starting at the index specified by the second argument, are appended, in order, to the contents of this sequence up to the (exclusive) the index specified by the last argument.
In the third statement, the first append method takes the first five characters in the “Hello” string, which is the whole string itself, and appends them to the “World!” string. The second append method adds a while-space. As a result, the string3 variable references the “World!Hello ” string.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuilder.html#append(java.lang.CharSequence,int,int)
Question 55 of 65
55. Question
Given:
String[] strings = {“b”, “c”, “a”};
Arrays.sort(strings, 1, 3);
System.out.println(Arrays.toString(strings));
What is the given code fragment’s output?
Correct
As per the JDK API Specification, the Arrays#sort method sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements. The range to be sorted extends from the first index argument, inclusive, to the second index argument, exclusive.
In the given code, the first array element is left untouched while the remaining are sorted. The string “a” comes before “c” in the natural ordering of the String class, implying the order of the last two elements are reversed.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D,int,int)
Incorrect
As per the JDK API Specification, the Arrays#sort method sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements. The range to be sorted extends from the first index argument, inclusive, to the second index argument, exclusive.
In the given code, the first array element is left untouched while the remaining are sorted. The string “a” comes before “c” in the natural ordering of the String class, implying the order of the last two elements are reversed.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D,int,int)
Unattempted
As per the JDK API Specification, the Arrays#sort method sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements. The range to be sorted extends from the first index argument, inclusive, to the second index argument, exclusive.
In the given code, the first array element is left untouched while the remaining are sorted. The string “a” comes before “c” in the natural ordering of the String class, implying the order of the last two elements are reversed.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D,int,int)
Question 56 of 65
56. Question
Given:
class Foo {
int number = 1;
int getNumber() {
return number;
}
}
public class Bar extends Foo {
int number = 2;
int getNumber() {
return number;
}
public static void main(String[] args) {
Foo foo = new Bar();
System.out.print(foo.number + ” ” + foo.getNumber() + ” “);
Bar bar = (Bar) foo;
System.out.print(bar.number + ” ” + bar.getNumber());
}
}
What is the program’s output?
Correct
The value of a field is determined by the reference type of the variable it’s accessed through. The number field in the first print statement comes from the Foo class, while the field of the same name in the second print statement is declared in the Bar class. This means the first output number is 1 and the third is 2.
When method overriding happens, the method that gets executed is determined by the type of the object it’s invoked on at runtime. In the given code, the getNumber methods in both print statements are called on a Bar instance, hence the method defined in the Bar class is called in both cases. This method returns the value of the number field in the same class. This value is 2, resulting in the second and forth output numbers being 2.
Incorrect
The value of a field is determined by the reference type of the variable it’s accessed through. The number field in the first print statement comes from the Foo class, while the field of the same name in the second print statement is declared in the Bar class. This means the first output number is 1 and the third is 2.
When method overriding happens, the method that gets executed is determined by the type of the object it’s invoked on at runtime. In the given code, the getNumber methods in both print statements are called on a Bar instance, hence the method defined in the Bar class is called in both cases. This method returns the value of the number field in the same class. This value is 2, resulting in the second and forth output numbers being 2.
Unattempted
The value of a field is determined by the reference type of the variable it’s accessed through. The number field in the first print statement comes from the Foo class, while the field of the same name in the second print statement is declared in the Bar class. This means the first output number is 1 and the third is 2.
When method overriding happens, the method that gets executed is determined by the type of the object it’s invoked on at runtime. In the given code, the getNumber methods in both print statements are called on a Bar instance, hence the method defined in the Bar class is called in both cases. This method returns the value of the number field in the same class. This value is 2, resulting in the second and forth output numbers being 2.
Question 57 of 65
57. Question
Given:
public class Foo {
static int number;
String text;
void methodA() {
System.out.println(this.number); // Line 1
System.out.println(this.text); // Line 2
}
static void methodB() {
System.out.println(this.number); // Line 3
System.out.println(this.text); // Line 4
}
}
Which lines cause a compile-time error?
Correct
A static context, such as the body of a static method, cannot reference a non-static field method. Notice that the this keyword always refers to the current object from within an instance method or a constructor – it cannot be used in a static context. This means lines 3 and 4 are invalid.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Incorrect
A static context, such as the body of a static method, cannot reference a non-static field method. Notice that the this keyword always refers to the current object from within an instance method or a constructor – it cannot be used in a static context. This means lines 3 and 4 are invalid.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Unattempted
A static context, such as the body of a static method, cannot reference a non-static field method. Notice that the this keyword always refers to the current object from within an instance method or a constructor – it cannot be used in a static context. This means lines 3 and 4 are invalid.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
public class Test {
static void methodA() throws MyException {
throw new MyException(“A custom exception”);
}
static int methodB(int argument) throws MyException {
int result = 1 / argument;
methodA();
return result;
}
public static void main(String[] args) {
try {
String output = “The result is ” + methodB(0);
System.out.println(output);
} catch (MyException e) {
System.out.println(e);
}
}
}
What can be the program’s output?
Correct
When a number is divided by 0, an ArithmeticException is thrown. This is an unchecked exception; thus, we don’t need to catch or specify it in the throws clause of the containing method.
That exception isn’t handled anywhere in the call stack. Consequently, the default exception handle kicks in and prints the stack trace to the console.
Incorrect
When a number is divided by 0, an ArithmeticException is thrown. This is an unchecked exception; thus, we don’t need to catch or specify it in the throws clause of the containing method.
That exception isn’t handled anywhere in the call stack. Consequently, the default exception handle kicks in and prints the stack trace to the console.
Unattempted
When a number is divided by 0, an ArithmeticException is thrown. This is an unchecked exception; thus, we don’t need to catch or specify it in the throws clause of the containing method.
That exception isn’t handled anywhere in the call stack. Consequently, the default exception handle kicks in and prints the stack trace to the console.
Question 59 of 65
59. Question
Given:
int sum = 0;
myLabel:
do {
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) continue;
sum += i;
}
} while (sum < 15);
System.out.println(sum);
What is the output of the given code?
Correct
The continue statement is unlabeled, hence it skips an iteration of the for loop each time variable i is even. This means only numbers 1 and 3 are added up to the sum value in each iteration. This process is repeated four times until the do/while condition expression sum < 15 evaluates to false. At this point, the value of sum is 16.
Incorrect
The continue statement is unlabeled, hence it skips an iteration of the for loop each time variable i is even. This means only numbers 1 and 3 are added up to the sum value in each iteration. This process is repeated four times until the do/while condition expression sum < 15 evaluates to false. At this point, the value of sum is 16.
Unattempted
The continue statement is unlabeled, hence it skips an iteration of the for loop each time variable i is even. This means only numbers 1 and 3 are added up to the sum value in each iteration. This process is repeated four times until the do/while condition expression sum < 15 evaluates to false. At this point, the value of sum is 16.
Question 60 of 65
60. Question
Given:
boolean b1 = new StringBuilder(“hello”).equals(“hello”);
boolean b2 = new StringBuilder(“he”).append(“llo”)
.equals(new StringBuilder(“hello”));
boolean b3 = new String(” hello “).strip().equalsIgnoreCase(“hello”);
boolean b4 = (“he” + “llo”).toUpperCase().equals(“HELLO”);
boolean b5 = “heLLO”.equalsIgnoreCase(“HEllo”);
Which two variables are set to false after the given code fragment is executed?
Correct
The b1 variable is false because the comparison is between objects of different types.
The b2 variable is false as well because the StringBuilder class doesn’t override the equals method defined in the root class Object. When the equals method is called on an instance of such a class, it returns true if and only if this instance and the argument object are the same.
To make it clearer, this is how we can rewrite the second statement:
boolean b2 = new StringBuilder(“he”).append(“llo”) == new StringBuilder(“hello”);
Obviously, the expression on the right-hand side of the assignment evaluates to false.
Incorrect
The b1 variable is false because the comparison is between objects of different types.
The b2 variable is false as well because the StringBuilder class doesn’t override the equals method defined in the root class Object. When the equals method is called on an instance of such a class, it returns true if and only if this instance and the argument object are the same.
To make it clearer, this is how we can rewrite the second statement:
boolean b2 = new StringBuilder(“he”).append(“llo”) == new StringBuilder(“hello”);
Obviously, the expression on the right-hand side of the assignment evaluates to false.
Unattempted
The b1 variable is false because the comparison is between objects of different types.
The b2 variable is false as well because the StringBuilder class doesn’t override the equals method defined in the root class Object. When the equals method is called on an instance of such a class, it returns true if and only if this instance and the argument object are the same.
To make it clearer, this is how we can rewrite the second statement:
boolean b2 = new StringBuilder(“he”).append(“llo”) == new StringBuilder(“hello”);
Obviously, the expression on the right-hand side of the assignment evaluates to false.
Question 61 of 65
61. Question
Given two source files:
package foo;
public class MyFoo {
// a valid body
}
And:
package foo.bar;
public class MyBar {
// a valid body
}
These files are put is this directory hierarchy:
foo
MyFoo.java
bar
MyBar.java
What is the correct way to compile both source files?
Correct
When the source file value foo/* is passed to the javac command, all members of the foo directory are supposed to be compiled. The bar directory is one of those members, but it isn’t a source file or a class file, hence the command fails.
Option C is incorrect as the source file separator is incorrect. It should have been one or more spaces instead of a semi-colon (;)
Incorrect
When the source file value foo/* is passed to the javac command, all members of the foo directory are supposed to be compiled. The bar directory is one of those members, but it isn’t a source file or a class file, hence the command fails.
Option C is incorrect as the source file separator is incorrect. It should have been one or more spaces instead of a semi-colon (;)
Unattempted
When the source file value foo/* is passed to the javac command, all members of the foo directory are supposed to be compiled. The bar directory is one of those members, but it isn’t a source file or a class file, hence the command fails.
Option C is incorrect as the source file separator is incorrect. It should have been one or more spaces instead of a semi-colon (;)
Question 62 of 65
62. Question
Which two of the following are correct about the Java Platform Module System (JPMS)?
Correct
Option A is incorrect as we can mix code from the classpath and module path. This allows us to gradually migrate an application to modules.
Option D is incorrect because exported types are declared in the module descriptor. Whether a type is an interface or class has nothing to do with its scope.
Option E is incorrect as we can only export a whole package rather than individual types.
The statements in options B and C are described in the referenced link.
Reference: https://blogs.oracle.com/java/modular-development
Incorrect
Option A is incorrect as we can mix code from the classpath and module path. This allows us to gradually migrate an application to modules.
Option D is incorrect because exported types are declared in the module descriptor. Whether a type is an interface or class has nothing to do with its scope.
Option E is incorrect as we can only export a whole package rather than individual types.
The statements in options B and C are described in the referenced link.
Reference: https://blogs.oracle.com/java/modular-development
Unattempted
Option A is incorrect as we can mix code from the classpath and module path. This allows us to gradually migrate an application to modules.
Option D is incorrect because exported types are declared in the module descriptor. Whether a type is an interface or class has nothing to do with its scope.
Option E is incorrect as we can only export a whole package rather than individual types.
The statements in options B and C are described in the referenced link.
Reference: https://blogs.oracle.com/java/modular-development
Question 63 of 65
63. Question
Given:
abstract class Foo {
protected static int x;
private String y;
abstract void methodA();
final void methodB() { }
}
class Bar extends Foo { // Line 1
int y; // Line 2
static String x; // Line 3
@Override // Line 4
public void methodA(String s) { }
public void methodB() {} // Line 5
}
Which three lines fail to compile?
Correct
Line 1 is invalid since class Bar extends an abstract class, but it isn’t declared as abstract or provides an implementation for the abstract method in the superclass.
Option D is incorrect as methodA in the Bar class doesn’t override methodA in the Foo class. These methods have different parameters, meaning they are overloaded.
Option E is correct as methodB in the Foo class is declared as final, hence cannot be overridden.
Notice fields in a subclass always hide fields of the same name in a superclass regardless of its type and whether they are static or not. Therefore, there’s nothing wrong on lines 2 and 3.
Incorrect
Line 1 is invalid since class Bar extends an abstract class, but it isn’t declared as abstract or provides an implementation for the abstract method in the superclass.
Option D is incorrect as methodA in the Bar class doesn’t override methodA in the Foo class. These methods have different parameters, meaning they are overloaded.
Option E is correct as methodB in the Foo class is declared as final, hence cannot be overridden.
Notice fields in a subclass always hide fields of the same name in a superclass regardless of its type and whether they are static or not. Therefore, there’s nothing wrong on lines 2 and 3.
Unattempted
Line 1 is invalid since class Bar extends an abstract class, but it isn’t declared as abstract or provides an implementation for the abstract method in the superclass.
Option D is incorrect as methodA in the Bar class doesn’t override methodA in the Foo class. These methods have different parameters, meaning they are overloaded.
Option E is correct as methodB in the Foo class is declared as final, hence cannot be overridden.
Notice fields in a subclass always hide fields of the same name in a superclass regardless of its type and whether they are static or not. Therefore, there’s nothing wrong on lines 2 and 3.
Question 64 of 65
64. Question
Given:
String[] array1 = {“1”, “2”, “3”};
String[] array2 = {};
String[] array3 = null;
Object o1 = Arrays.compare(array1, array2);
Object o2 = Arrays.compare(array2, array3);
Object o3 = Arrays.compare(array3, array1);
System.out.println(o1 + ” ” + o2 + ” ” + o3);
What is the output of the given code fragment?
Correct
The compare method returns an int value. This value can be auto-boxed to an Integer object, whose class is a subtype of the Object class. Therefore, the declarations of variables o1, o2 and o3 are valid.
When two arrays don’t share a prefix, the comparison is the result of comparing the two array lengths. The second array doesn’t have any element, meaning its length is 0. Meanwhile, the first array has three elements, resulting in o1 being 3.
A null array reference is considered less than a non-null array reference. This means variable o2 is set to 1 and o3 is to -1.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#compare(T%5B%5D,T%5B%5D)
Incorrect
The compare method returns an int value. This value can be auto-boxed to an Integer object, whose class is a subtype of the Object class. Therefore, the declarations of variables o1, o2 and o3 are valid.
When two arrays don’t share a prefix, the comparison is the result of comparing the two array lengths. The second array doesn’t have any element, meaning its length is 0. Meanwhile, the first array has three elements, resulting in o1 being 3.
A null array reference is considered less than a non-null array reference. This means variable o2 is set to 1 and o3 is to -1.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#compare(T%5B%5D,T%5B%5D)
Unattempted
The compare method returns an int value. This value can be auto-boxed to an Integer object, whose class is a subtype of the Object class. Therefore, the declarations of variables o1, o2 and o3 are valid.
When two arrays don’t share a prefix, the comparison is the result of comparing the two array lengths. The second array doesn’t have any element, meaning its length is 0. Meanwhile, the first array has three elements, resulting in o1 being 3.
A null array reference is considered less than a non-null array reference. This means variable o2 is set to 1 and o3 is to -1.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#compare(T%5B%5D,T%5B%5D)
Question 65 of 65
65. Question
Given:
public class Test {
static public void main(String[] args) {
Test test = new Test();
test.checkBoolean(true);
}
void checkBoolean(boolean value) {
switch (value) {
default: System.out.println(“false”);
case Boolean.TRUE: System.out.println(“true”);
}
}
}
What is the program’s output?
Correct
A switch statement works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
In the given code, the switch expression is of the boolean type, hence a compile-time error occurs.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Incorrect
A switch statement works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
In the given code, the switch expression is of the boolean type, hence a compile-time error occurs.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Unattempted
A switch statement works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
In the given code, the switch expression is of the boolean type, hence a compile-time error occurs.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
X
Use Page numbers below to navigate to other practice tests