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 9 "
0 of 65 questions answered correctly
Your time:
Time has elapsed
Your Final Score is : 0
You have attempted : 0
Number of Correct Questions : 0 and scored 0
Number of Incorrect Questions : 0 and Negative marks 0
Average score
Your score
OCP Java SE 11 Programmer I 1Z0-815
You have attempted: 0
Number of Correct Questions: 0 and scored 0
Number of Incorrect Questions: 0 and Negative marks 0
You can review your answers by clicking view questions. Important Note : Open Reference Documentation Links in New Tab (Right Click and Open in New Tab).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Answered
Review
Question 1 of 65
1. Question
Given:
public class Test {
void switchNumber(double number) {
switch (number) { // Line 1
case 1:
System.out.println(“Integer”);
case 1.0:
System.out.println(“Floating point”);
}
}
public static void main(String[] args) {
Test test = new Test();
test.switchNumber(1); // Line 2
}
}
What is the output of the program?
Correct
As per the Oracle Java Tutorial, a switch statement can only work 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 type double, hence it fails to compile on line 1. On line 2, an int value is automatically converted to the double type, thus there’s nothing wrong over there.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Incorrect
As per the Oracle Java Tutorial, a switch statement can only work 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 type double, hence it fails to compile on line 1. On line 2, an int value is automatically converted to the double type, thus there’s nothing wrong over there.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Unattempted
As per the Oracle Java Tutorial, a switch statement can only work 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 type double, hence it fails to compile on line 1. On line 2, an int value is automatically converted to the double type, thus there’s nothing wrong over there.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Question 2 of 65
2. Question
Given:
int[][] matrix1 = {{1, 2}, {3}};
int[][] matrix2;
matrix2 = {{1, 2}, {3, 4}};
int[][] matrix3 = new int[][]{{1, 2}, {3, 4}};
int[][] matrix4 = {new int[2], new int[2]};
Which array initialization is invalid?
Correct
The initialization of matrix2 is invalid because an array initializer must be used at the declaration time. It would have been valid if the declaration and initialization were:
int[][] matrix2 = {{1, 2}, {3, 4}};
Incorrect
The initialization of matrix2 is invalid because an array initializer must be used at the declaration time. It would have been valid if the declaration and initialization were:
int[][] matrix2 = {{1, 2}, {3, 4}};
Unattempted
The initialization of matrix2 is invalid because an array initializer must be used at the declaration time. It would have been valid if the declaration and initialization were:
int[][] matrix2 = {{1, 2}, {3, 4}};
Question 3 of 65
3. Question
Given:
List list = new ArrayList<>();
list.add(“A”);
list.addAll(1, List.of(“A”));
list.clear();
System.out.println(list);
What is the output of the given code fragment?
Correct
The add statement appends “A” to the list, then addAll appends a collection of strings – which happens to contain only a single string with the same value – to that list as well.
At this point, the list variable references a list with two elements: “A” and “A”. However, the clear method wipes out all the elements, leaving the list empty.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Incorrect
The add statement appends “A” to the list, then addAll appends a collection of strings – which happens to contain only a single string with the same value – to that list as well.
At this point, the list variable references a list with two elements: “A” and “A”. However, the clear method wipes out all the elements, leaving the list empty.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Unattempted
The add statement appends “A” to the list, then addAll appends a collection of strings – which happens to contain only a single string with the same value – to that list as well.
At this point, the list variable references a list with two elements: “A” and “A”. However, the clear method wipes out all the elements, leaving the list empty.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Question 4 of 65
4. Question
Given:
String string = “Hey”;
StringBuilder builder = new StringBuilder(string);
System.out.println(string.equals(builder)); // Line 1
System.out.println(string.contentEquals(builder)); // Line 2
What’s the program’s output?
When a class is loaded, all static variables are initialized, and static initialization blocks are executed. Therefore, after the class loading, the number field is set to 3.
The body of each instance initialization block is copied to all the constructors during compilation. This copied code is placed right before the existing code in those constructors. After the compilation, the Test class looks like this:
public class Test {
When a class is loaded, all static variables are initialized, and static initialization blocks are executed. Therefore, after the class loading, the number field is set to 3.
The body of each instance initialization block is copied to all the constructors during compilation. This copied code is placed right before the existing code in those constructors. After the compilation, the Test class looks like this:
public class Test {
When a class is loaded, all static variables are initialized, and static initialization blocks are executed. Therefore, after the class loading, the number field is set to 3.
The body of each instance initialization block is copied to all the constructors during compilation. This copied code is placed right before the existing code in those constructors. After the compilation, the Test class looks like this:
public class Test {
If a constructor doesn’t call another constructor in the same class or in the parent class, a call to the no-argument constructor of the parent class is added automatically.
In the given code, the only constructor of the Bar class invokes the no-argument constructor in the Foo class. However, the Foo constructor has no access modifier, meaning that it’s package private. This scope prevents any access from outside of the f package, resulting in a compile-time error.
Had the constructor in the Foo class been removed, the story would have been different. In such a case, the compiler inserts a no-argument constructor, but this constructor has the same access modifier as its containing class. As a result, the compilation succeeds.
Incorrect
If a constructor doesn’t call another constructor in the same class or in the parent class, a call to the no-argument constructor of the parent class is added automatically.
In the given code, the only constructor of the Bar class invokes the no-argument constructor in the Foo class. However, the Foo constructor has no access modifier, meaning that it’s package private. This scope prevents any access from outside of the f package, resulting in a compile-time error.
Had the constructor in the Foo class been removed, the story would have been different. In such a case, the compiler inserts a no-argument constructor, but this constructor has the same access modifier as its containing class. As a result, the compilation succeeds.
Unattempted
If a constructor doesn’t call another constructor in the same class or in the parent class, a call to the no-argument constructor of the parent class is added automatically.
In the given code, the only constructor of the Bar class invokes the no-argument constructor in the Foo class. However, the Foo constructor has no access modifier, meaning that it’s package private. This scope prevents any access from outside of the f package, resulting in a compile-time error.
Had the constructor in the Foo class been removed, the story would have been different. In such a case, the compiler inserts a no-argument constructor, but this constructor has the same access modifier as its containing class. As a result, the compilation succeeds.
Question 7 of 65
7. Question
Given:
int i;
int j;
for (i = 1, j = 3; i <= j; i = i + 2, j++) {
i++;
}
System.out.println(i + " " + j);
What is the output of the program?
Correct
There’s nothing wrong with the given code, hence no error occurs.
Let’s go over iterations of the for construct:
Iteration 1:
i starts with the value of 1, j with the value of 3
Since 1 <= 3, the body of the for loop is executed, increasing i to 2
In the increment step, i goes from 2 to 4, j from 3 to 4
Iteration 2:
Both i and j starts with the value of 4
Since 4 <= 4, the body of the for loop is executed, increasing i to 6
In the increment step, i goes from 6 to 7, j from 4 to 5
Iteration 3:
i starts with the value of 7, j with the value of 5
The condition expression evaluates to false as 7 isn't less than or equal to 5 - at this point, the for loop exits
The final values of variables i and j are therefore 7 and 5, respectively.
Incorrect
There’s nothing wrong with the given code, hence no error occurs.
Let’s go over iterations of the for construct:
Iteration 1:
i starts with the value of 1, j with the value of 3
Since 1 <= 3, the body of the for loop is executed, increasing i to 2
In the increment step, i goes from 2 to 4, j from 3 to 4
Iteration 2:
Both i and j starts with the value of 4
Since 4 <= 4, the body of the for loop is executed, increasing i to 6
In the increment step, i goes from 6 to 7, j from 4 to 5
Iteration 3:
i starts with the value of 7, j with the value of 5
The condition expression evaluates to false as 7 isn't less than or equal to 5 - at this point, the for loop exits
The final values of variables i and j are therefore 7 and 5, respectively.
Unattempted
There’s nothing wrong with the given code, hence no error occurs.
Let’s go over iterations of the for construct:
Iteration 1:
i starts with the value of 1, j with the value of 3
Since 1 <= 3, the body of the for loop is executed, increasing i to 2
In the increment step, i goes from 2 to 4, j from 3 to 4
Iteration 2:
Both i and j starts with the value of 4
Since 4 <= 4, the body of the for loop is executed, increasing i to 6
In the increment step, i goes from 6 to 7, j from 4 to 5
Iteration 3:
i starts with the value of 7, j with the value of 5
The condition expression evaluates to false as 7 isn't less than or equal to 5 - at this point, the for loop exits
The final values of variables i and j are therefore 7 and 5, respectively.
Question 8 of 65
8. Question
Which types of exceptions/errors must be caught or specified with a throws clause in the method’s declaration?
Given:
List strings = new ArrayList<>(List.of(“A”, “B”));
Iterator iterator = strings.listIterator(1);
strings.set(1, “C”);
if (iterator.hasNext()) {
System.out.println(iterator.next());
}
What is the output of the given code fragment?
Correct
The listIterator with an int parameter returns an iterator over elements of the list, starting at the specified position. This means, in the given code fragment, the iterator starts at index 1. The value at index 1 after the invocation of the set method is “C”, hence option C is the correct answer.
Incorrect
The listIterator with an int parameter returns an iterator over elements of the list, starting at the specified position. This means, in the given code fragment, the iterator starts at index 1. The value at index 1 after the invocation of the set method is “C”, hence option C is the correct answer.
Unattempted
The listIterator with an int parameter returns an iterator over elements of the list, starting at the specified position. This means, in the given code fragment, the iterator starts at index 1. The value at index 1 after the invocation of the set method is “C”, hence option C is the correct answer.
Question 11 of 65
11. Question
It’s known that the foo and bar modules require the my.module module. Which of the following declarations makes the foo and bar packages visible in those requiring modules?
Correct
The exports directive cannot specify more than one package, thus all the options except for option A are invalid.
Incorrect
The exports directive cannot specify more than one package, thus all the options except for option A are invalid.
Unattempted
The exports directive cannot specify more than one package, thus all the options except for option A are invalid.
Question 12 of 65
12. Question
Given:
class Foo {
protected Number getValue(Number number) {
return number;
}
}
class Bar extends Foo {
@Override
/* Position 1 */
}
Which method when inserted at position 1 allows the Bar class to compile?
Correct
When a subtype overrides a method in a supertype, the overriding method must have the exact same signature as the overridden method and its return type must be the same or a subtype of the overridden method’s return type (there are other restrictions, but they are irrelevant to this question). None of the given methods satisfy those requirements, hence option E is the correct answer.
Incorrect
When a subtype overrides a method in a supertype, the overriding method must have the exact same signature as the overridden method and its return type must be the same or a subtype of the overridden method’s return type (there are other restrictions, but they are irrelevant to this question). None of the given methods satisfy those requirements, hence option E is the correct answer.
Unattempted
When a subtype overrides a method in a supertype, the overriding method must have the exact same signature as the overridden method and its return type must be the same or a subtype of the overridden method’s return type (there are other restrictions, but they are irrelevant to this question). None of the given methods satisfy those requirements, hence option E is the correct answer.
Question 13 of 65
13. Question
Given:
int a = 4, b = 2;
System.out.println(a + b + “=a+b=” + a + b);
What is the given code’s output?
Correct
When an expression contains only additive operators, the calculation is performed from left to right. Notice that if either of the operands is a string, the other operand is converted to string as well.
In the given code, the first addition, 4 + 2, is computed as an arithmetic operation. The result is 6.
The second addition, however, is different as the second operand is a string. The result after this computation is the string “6=a+b=”.
At this point, we have the expression “6=a+b=” + 4 + 2. Since the computation is still from left to right, 4 is converted to a string and added to the concatenation, then 2 is. The final result is then “6=a+b=42”.
Incorrect
When an expression contains only additive operators, the calculation is performed from left to right. Notice that if either of the operands is a string, the other operand is converted to string as well.
In the given code, the first addition, 4 + 2, is computed as an arithmetic operation. The result is 6.
The second addition, however, is different as the second operand is a string. The result after this computation is the string “6=a+b=”.
At this point, we have the expression “6=a+b=” + 4 + 2. Since the computation is still from left to right, 4 is converted to a string and added to the concatenation, then 2 is. The final result is then “6=a+b=42”.
Unattempted
When an expression contains only additive operators, the calculation is performed from left to right. Notice that if either of the operands is a string, the other operand is converted to string as well.
In the given code, the first addition, 4 + 2, is computed as an arithmetic operation. The result is 6.
The second addition, however, is different as the second operand is a string. The result after this computation is the string “6=a+b=”.
At this point, we have the expression “6=a+b=” + 4 + 2. Since the computation is still from left to right, 4 is converted to a string and added to the concatenation, then 2 is. The final result is then “6=a+b=42”.
Question 14 of 65
14. Question
Given:
public class Test {
static String text = “foo”;
public static void main(String[] args) {
String text = “bar”;
if (text.equals(“foo”)) {
String text = “fuz”;
} else {
String text = “baz”;
}
System.out.println(text);
}
}
What is the program’s output?
Correct
In the given code, the text local variable shadows the text static field. This means the value of text after the first statement inside the main method is “bar”.
However, since a variable is visible in all the following code blocks that are at the same level as its declaration, the two declarations within the if-else statement are, in fact, re-declarations. As a result, we get compile-time errors.
Incorrect
In the given code, the text local variable shadows the text static field. This means the value of text after the first statement inside the main method is “bar”.
However, since a variable is visible in all the following code blocks that are at the same level as its declaration, the two declarations within the if-else statement are, in fact, re-declarations. As a result, we get compile-time errors.
Unattempted
In the given code, the text local variable shadows the text static field. This means the value of text after the first statement inside the main method is “bar”.
However, since a variable is visible in all the following code blocks that are at the same level as its declaration, the two declarations within the if-else statement are, in fact, re-declarations. As a result, we get compile-time errors.
Question 15 of 65
15. Question
Given:
int[] array1 = {1, 2, 3};
int[] array2 = Arrays.copyOf(array1, 4);
System.out.println(array2[3]);
What is the output when executing the given code?
Correct
As per the JDK API Specification, the Arrays#copyOf method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain 0. Such indices will exist if and only if the specified length is greater than that of the original array.
In the given code, the original array has three elements while the target has four. Therefore, the target will be fill in with the default value of the int data type, which is 0.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(int%5B%5D,int)
Incorrect
As per the JDK API Specification, the Arrays#copyOf method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain 0. Such indices will exist if and only if the specified length is greater than that of the original array.
In the given code, the original array has three elements while the target has four. Therefore, the target will be fill in with the default value of the int data type, which is 0.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(int%5B%5D,int)
Unattempted
As per the JDK API Specification, the Arrays#copyOf method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain 0. Such indices will exist if and only if the specified length is greater than that of the original array.
In the given code, the original array has three elements while the target has four. Therefore, the target will be fill in with the default value of the int data type, which is 0.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(int%5B%5D,int)
Question 16 of 65
16. Question
Which types of exception shouldn’t be caught and handled?
Correct
As per the JDK API Specification, an Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.
Checked exceptions must be caught at one point or another in the call stack, while checked exceptions may or may not be caught, depending on business requirements.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Error.html
Incorrect
As per the JDK API Specification, an Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.
Checked exceptions must be caught at one point or another in the call stack, while checked exceptions may or may not be caught, depending on business requirements.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Error.html
Unattempted
As per the JDK API Specification, an Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.
Checked exceptions must be caught at one point or another in the call stack, while checked exceptions may or may not be caught, depending on business requirements.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Error.html
Question 17 of 65
17. Question
Given:
public class Test {
public static void main(String[] args) {
int sum = 0;
for (String arg : args) {
sum += Integer.valueOf(arg);
}
System.out.println(sum);
}
}
What is the output if we execute the given program with the following command?
java Test “1” “2” 3
Correct
When passing arguments to the java command, single (‘) or double (“) quotes can be used to enclose arguments that contain whitespace characters. All content between the open quote and the first matching close quote are preserved by simply removing the pair of quotes.
In the given program, the input arguments are strings “1”, “2” and “3”. These strings are converted to integers and added up. The result is thus 6, the sum of corresponding numbers.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Incorrect
When passing arguments to the java command, single (‘) or double (“) quotes can be used to enclose arguments that contain whitespace characters. All content between the open quote and the first matching close quote are preserved by simply removing the pair of quotes.
In the given program, the input arguments are strings “1”, “2” and “3”. These strings are converted to integers and added up. The result is thus 6, the sum of corresponding numbers.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Unattempted
When passing arguments to the java command, single (‘) or double (“) quotes can be used to enclose arguments that contain whitespace characters. All content between the open quote and the first matching close quote are preserved by simply removing the pair of quotes.
In the given program, the input arguments are strings “1”, “2” and “3”. These strings are converted to integers and added up. The result is thus 6, the sum of corresponding numbers.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Question 18 of 65
18. Question
Given:
List list = new ArrayList<>(List.of(“A”, “B”));
String[] array1 = {“C”};
String[] array2 = list.toArray(array1);
array1[0] = “D”;
System.out.println(Arrays.toString(array2));
What is the output of the given code fragment?
Correct
The toArray method with an array parameter allocates a new array if the argument isn’t large enough. The length of this new array is equal to that of the original list.
In the given code, the array passed to the toArray method has one element, but the original list has two. As a result, a new array is created to store both elements of the list. These elements are then printed to the console.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#toArray(T%5B%5D)
Incorrect
The toArray method with an array parameter allocates a new array if the argument isn’t large enough. The length of this new array is equal to that of the original list.
In the given code, the array passed to the toArray method has one element, but the original list has two. As a result, a new array is created to store both elements of the list. These elements are then printed to the console.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#toArray(T%5B%5D)
Unattempted
The toArray method with an array parameter allocates a new array if the argument isn’t large enough. The length of this new array is equal to that of the original list.
In the given code, the array passed to the toArray method has one element, but the original list has two. As a result, a new array is created to store both elements of the list. These elements are then printed to the console.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#toArray(T%5B%5D)
Question 19 of 65
19. Question
Given a method:
String getValue(int value) {
return String.valueOf(value);
}
Which of the following is not an overloaded method of the given one?
Correct
As per the Oracle Java Tutorials, the Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists.
In options A and B, the parameter is different from that of the given method, hence they are both overloaded methods of the method in question. The method in option C, nevertheless, has the exact same signature with the given method (notice the method’s return type doesn’t matter). This means the method in option C and the one in the question cannot be declared in the same class, hence they aren’t overloaded.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Incorrect
As per the Oracle Java Tutorials, the Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists.
In options A and B, the parameter is different from that of the given method, hence they are both overloaded methods of the method in question. The method in option C, nevertheless, has the exact same signature with the given method (notice the method’s return type doesn’t matter). This means the method in option C and the one in the question cannot be declared in the same class, hence they aren’t overloaded.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Unattempted
As per the Oracle Java Tutorials, the Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists.
In options A and B, the parameter is different from that of the given method, hence they are both overloaded methods of the method in question. The method in option C, nevertheless, has the exact same signature with the given method (notice the method’s return type doesn’t matter). This means the method in option C and the one in the question cannot be declared in the same class, hence they aren’t overloaded.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Question 20 of 65
20. Question
Given:
LocalTime now = LocalTime.of(10, 10, 10);
LocalTime start = LocalTime.of(8, 30).withMinute(now.getMinute());
LocalTime end = LocalTime.of(12, 30).withMinute(now.getMinute());
long timePassed = now.until(start, ChronoUnit.HOURS);
long timeToGo = now.until(end, ChronoUnit.HOURS);
System.out.println(timePassed + ” ” + timeToGo);
Assumes local time of the machine on which the given code fragment runs is 10:10:10 AM. What is the output?
Correct
The getMinute method returns minute of hour without information about second, thus the start variable is set to 8:10:00 and end to 12:10:00.
Notice the until method calculates the amount of time until another time, exclusively. In the given code, the interval between now and start is two hours and ten seconds, rounded down to two hours. The interval between now and end is ten seconds short of two hours, rounded down to one hour.
Incorrect
The getMinute method returns minute of hour without information about second, thus the start variable is set to 8:10:00 and end to 12:10:00.
Notice the until method calculates the amount of time until another time, exclusively. In the given code, the interval between now and start is two hours and ten seconds, rounded down to two hours. The interval between now and end is ten seconds short of two hours, rounded down to one hour.
Unattempted
The getMinute method returns minute of hour without information about second, thus the start variable is set to 8:10:00 and end to 12:10:00.
Notice the until method calculates the amount of time until another time, exclusively. In the given code, the interval between now and start is two hours and ten seconds, rounded down to two hours. The interval between now and end is ten seconds short of two hours, rounded down to one hour.
Question 21 of 65
21. Question
Given:
class Foo {
void myMethod(Integer number) {
// a valid body
}
}
public class Bar extends Foo {
/* Method 1 */
int myMethod(Integer integer) {
// a valid body
}
/* Method 2 */
static void myMethod(Integer integer) {
// a valid body
}
/* Method 3 */
String myMethod(long number) {
// a valid body
}
/* Method 4 */
void myMethod(int number) {
// a valid body
}
/* Method 5 */
void myMethod(Integer number1, Integer number2) {
// a valid body
}
}
Which two methods in the Bar class fail to compile?
Correct
Method 1 has the exact same signature as the method in the superclass, thereby overriding it. However, their return types are incompatible. Specifically, the return type of the overriding method must be the same or a subtype of the overridden method’s return type. This means method 1 is invalid.
Method 2 also has the same signature as the superclass’s method. Nonetheless, the subclass’s method is static but the one in the superclass isn’t. A static method cannot override or hide a non-static method, hence a compilation error.
Notice the parameter names of both method 1 and method 2 are different from that of the superclass’s method, but parameter names aren’t part of the method’s signature. Thus, this difference doesn’t matter.
Methods 3, 4 and 5 have a different signature from the superclass’s method – they overload that method.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Incorrect
Method 1 has the exact same signature as the method in the superclass, thereby overriding it. However, their return types are incompatible. Specifically, the return type of the overriding method must be the same or a subtype of the overridden method’s return type. This means method 1 is invalid.
Method 2 also has the same signature as the superclass’s method. Nonetheless, the subclass’s method is static but the one in the superclass isn’t. A static method cannot override or hide a non-static method, hence a compilation error.
Notice the parameter names of both method 1 and method 2 are different from that of the superclass’s method, but parameter names aren’t part of the method’s signature. Thus, this difference doesn’t matter.
Methods 3, 4 and 5 have a different signature from the superclass’s method – they overload that method.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Unattempted
Method 1 has the exact same signature as the method in the superclass, thereby overriding it. However, their return types are incompatible. Specifically, the return type of the overriding method must be the same or a subtype of the overridden method’s return type. This means method 1 is invalid.
Method 2 also has the same signature as the superclass’s method. Nonetheless, the subclass’s method is static but the one in the superclass isn’t. A static method cannot override or hide a non-static method, hence a compilation error.
Notice the parameter names of both method 1 and method 2 are different from that of the superclass’s method, but parameter names aren’t part of the method’s signature. Thus, this difference doesn’t matter.
Methods 3, 4 and 5 have a different signature from the superclass’s method – they overload that method.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Question 22 of 65
22. Question
Given:
package foo;
public class MyFoo {
protected void say() {
System.out.println(“Hello!”);
}
}
Which statement is correct about the say method?
Given:
String text = “hiheyhello”;
int index = text.lastIndexOf(“h”, 4);
System.out.println(index);
What is the output of the given code?
Correct
As per the JDK API Specification, the String#lastIndexOf(String, int) method returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
In the given code, the search starts at index 4, implying the covered substring is “hihey”. There are two characters “h” in this substring, and the last one is at index 2.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#lastIndexOf(java.lang.String,int)
Incorrect
As per the JDK API Specification, the String#lastIndexOf(String, int) method returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
In the given code, the search starts at index 4, implying the covered substring is “hihey”. There are two characters “h” in this substring, and the last one is at index 2.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#lastIndexOf(java.lang.String,int)
Unattempted
As per the JDK API Specification, the String#lastIndexOf(String, int) method returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
In the given code, the search starts at index 4, implying the covered substring is “hihey”. There are two characters “h” in this substring, and the last one is at index 2.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#lastIndexOf(java.lang.String,int)
Question 24 of 65
24. Question
Which command prints the module descriptor?
Correct
Here’s a description of the –check option of the jdeps command:
Analyzes the dependencies of the specified modules. It prints the module descriptor, the resulting module dependencies after analysis, and the graph after transition reduction. It also identifies any unused qualified exports.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Incorrect
Here’s a description of the –check option of the jdeps command:
Analyzes the dependencies of the specified modules. It prints the module descriptor, the resulting module dependencies after analysis, and the graph after transition reduction. It also identifies any unused qualified exports.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Unattempted
Here’s a description of the –check option of the jdeps command:
Analyzes the dependencies of the specified modules. It prints the module descriptor, the resulting module dependencies after analysis, and the graph after transition reduction. It also identifies any unused qualified exports.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Question 25 of 65
25. Question
Which of the following are checked exceptions?
Correct
Checked exceptions are exceptions that don’t extend the RuntimeException class. Among all the given options, only IOException isn’t an unchecked exception.
Incorrect
Checked exceptions are exceptions that don’t extend the RuntimeException class. Among all the given options, only IOException isn’t an unchecked exception.
Unattempted
Checked exceptions are exceptions that don’t extend the RuntimeException class. Among all the given options, only IOException isn’t an unchecked exception.
Question 26 of 65
26. Question
Given:
List original = new ArrayList<>();
original.add(null); // Line 1
List copy = List.copyOf(original); // Line 2
System.out.println(copy.get(0)); // Line 3
Which line will throw an exception when the given code is run?
Correct
The List#copyOf method returns an unmodifiable list containing elements of the original one. As per the JDK API Specification, such a list disallows null elements. Attempts to create them with null elements result in NullPointerException.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Incorrect
The List#copyOf method returns an unmodifiable list containing elements of the original one. As per the JDK API Specification, such a list disallows null elements. Attempts to create them with null elements result in NullPointerException.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Unattempted
The List#copyOf method returns an unmodifiable list containing elements of the original one. As per the JDK API Specification, such a list disallows null elements. Attempts to create them with null elements result in NullPointerException.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Question 27 of 65
27. Question
Given:
Integer[] array1 = new Integer[1];
int[] array2 = new int[1];
System.out.println(array1[0] + ” ” + array2[0]);
What is the output of the given code fragment?
Correct
When creating an array with the new operator, all elements of the array is initialized to the default value of their type. In the given code, the default value of elements in the first array is null because they are of an object reference type. Meanwhile, the default value of elements in the second array is 0 as their type is int.
Incorrect
When creating an array with the new operator, all elements of the array is initialized to the default value of their type. In the given code, the default value of elements in the first array is null because they are of an object reference type. Meanwhile, the default value of elements in the second array is 0 as their type is int.
Unattempted
When creating an array with the new operator, all elements of the array is initialized to the default value of their type. In the given code, the default value of elements in the first array is null because they are of an object reference type. Meanwhile, the default value of elements in the second array is 0 as their type is int.
Question 28 of 65
28. Question
Given:
int x = 1, y = 2, z = 3;
x += y *= z -= x;
System.out.println(x + ” ” + y + ” ” + z);
What is the output of the given code?
Correct
Unlike all other operators in Java, assignment operators are evaluated from right to left. Therefore, the given assignments can be rewritten as:
z = z – x;
y = y * z;
x = x + y;
Incorrect
Unlike all other operators in Java, assignment operators are evaluated from right to left. Therefore, the given assignments can be rewritten as:
z = z – x;
y = y * z;
x = x + y;
Unattempted
Unlike all other operators in Java, assignment operators are evaluated from right to left. Therefore, the given assignments can be rewritten as:
z = z – x;
y = y * z;
x = x + y;
Question 29 of 65
29. Question
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.*; // 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. Both the import statements are valid, but the compiler fails on line 2 as it cannot know which Greeting class is referenced. This ambiguity leads to a compile-time error.
Incorrect
In the given code, the Greeting class is declared in two packages, foo and bar. Both the import statements are valid, but the compiler fails on line 2 as it cannot know which Greeting class is referenced. This ambiguity leads to a compile-time error.
Unattempted
In the given code, the Greeting class is declared in two packages, foo and bar. Both the import statements are valid, but the compiler fails on line 2 as it cannot know which Greeting class is referenced. This ambiguity leads to a compile-time error.
class Bar extends Foo {
String getName() {
return “Bar”;
}
}
public class Baz extends Foo, Bar {
String getName() {
return “Baz”;
}
public static void main(String[] args) {
Baz baz = new Baz();
String name = baz.getName();
System.out.println(name);
}
}
What is the program’s output?
Correct
The given program is invalid as the Baz class extends more than one class. Such a declaration is prohibited despite the inherited classes are in the same inheritance chain.
Incorrect
The given program is invalid as the Baz class extends more than one class. Such a declaration is prohibited despite the inherited classes are in the same inheritance chain.
Unattempted
The given program is invalid as the Baz class extends more than one class. Such a declaration is prohibited despite the inherited classes are in the same inheritance chain.
Question 31 of 65
31. Question
Given:
class Foo {
Foo() {
System.out.println(“Foo”);
}
}
public class Bar extends Foo {
Bar() {
System.out.println(“Bar”);
super();
}
public static void main(String[] args) {
new Bar();
}
}
What is the program’s output?
Correct
Inside a constructor, the call to another constructor in the same class or the parent class must be the first statement, otherwise a compile-time error occurs.
If the call to super() were moved to the top of the constructor, option B would have been the correct answer.
Incorrect
Inside a constructor, the call to another constructor in the same class or the parent class must be the first statement, otherwise a compile-time error occurs.
If the call to super() were moved to the top of the constructor, option B would have been the correct answer.
Unattempted
Inside a constructor, the call to another constructor in the same class or the parent class must be the first statement, otherwise a compile-time error occurs.
If the call to super() were moved to the top of the constructor, option B would have been the correct answer.
Question 32 of 65
32. Question
Given:
float addend1 = 4L / 2; // Line 1
long addend2 = (long) 1.8; // Line 2
var sum = addend1 + addend2; // Line 3
System.out.println(sum);
What is the output of the given code?
Correct
On line 1, the quotient on the right-hand side is of type long. The casting from long to float is widening, thus we don’t need a casting operator. The division result is 2, which is then cast to the float type, meaning the value of variable addend1 is 2.0.
One line 2, the double value 1.8 is cast to the long type. During this operation, the fractional part of the original value is lost, resulting addend2 being 1.
The computation on line 3 is also valid – it’s just the addition of a float and a long number. The result of this computation is of type float, hence it’s printed as 3.0.
Incorrect
On line 1, the quotient on the right-hand side is of type long. The casting from long to float is widening, thus we don’t need a casting operator. The division result is 2, which is then cast to the float type, meaning the value of variable addend1 is 2.0.
One line 2, the double value 1.8 is cast to the long type. During this operation, the fractional part of the original value is lost, resulting addend2 being 1.
The computation on line 3 is also valid – it’s just the addition of a float and a long number. The result of this computation is of type float, hence it’s printed as 3.0.
Unattempted
On line 1, the quotient on the right-hand side is of type long. The casting from long to float is widening, thus we don’t need a casting operator. The division result is 2, which is then cast to the float type, meaning the value of variable addend1 is 2.0.
One line 2, the double value 1.8 is cast to the long type. During this operation, the fractional part of the original value is lost, resulting addend2 being 1.
The computation on line 3 is also valid – it’s just the addition of a float and a long number. The result of this computation is of type float, hence it’s printed as 3.0.
Question 33 of 65
33. Question
Given:
try {
throw new FileNotFoundException();
} catch (Exception | IOException e) {
if (e instanceof FileNotFoundException) {
System.out.println(“FileNotFoundException”);
} else if (e instanceof IOException) {
System.out.println(“IOException”);
} else if (e instanceof Exception) {
System.out.println(“Exception”);
}
}
What is the output of the given code?
Correct
When a catch block specifies multiple exception types, these types must be disjoint. In other words, they must not be in the same inheritance chain.
In the given code, Exception is the parent of IOException, meaning they aren’t allowed to be in the same catch block. This violation leads to a compile-time error.
Incorrect
When a catch block specifies multiple exception types, these types must be disjoint. In other words, they must not be in the same inheritance chain.
In the given code, Exception is the parent of IOException, meaning they aren’t allowed to be in the same catch block. This violation leads to a compile-time error.
Unattempted
When a catch block specifies multiple exception types, these types must be disjoint. In other words, they must not be in the same inheritance chain.
In the given code, Exception is the parent of IOException, meaning they aren’t allowed to be in the same catch block. This violation leads to a compile-time error.
Question 34 of 65
34. Question
Which of the following isn’t a command that can be used to create and build application?
Correct
The commands that can be used to create and build applications can be found via the referenced link.
jshell is a JDK tools, but it’s used to interactively evaluate declarations, statements, and expressions of the Java programming language in a read-eval-print loop (REPL).
Reference: https://docs.oracle.com/en/java/javase/11/tools/main-tools-create-and-build-applications.html
Incorrect
The commands that can be used to create and build applications can be found via the referenced link.
jshell is a JDK tools, but it’s used to interactively evaluate declarations, statements, and expressions of the Java programming language in a read-eval-print loop (REPL).
Reference: https://docs.oracle.com/en/java/javase/11/tools/main-tools-create-and-build-applications.html
Unattempted
The commands that can be used to create and build applications can be found via the referenced link.
jshell is a JDK tools, but it’s used to interactively evaluate declarations, statements, and expressions of the Java programming language in a read-eval-print loop (REPL).
Reference: https://docs.oracle.com/en/java/javase/11/tools/main-tools-create-and-build-applications.html
Question 35 of 65
35. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
String text1 = test.convert(‘a’);
String text2 = test.convert(‘b’);
System.out.println(text1 + text2);
}
String convert(char character) {
String text;
switch (character) { // Line 1
case ‘a’:
text = “A”;
case ‘b’:
text = “B”;
break;
case ‘c’:
text = “C”;
}
return text; // Line 2
}
}
What is the output of the program?
Correct
The switch statement doesn’t have a default label, meaning it doesn’t cover all the allowable values of the character variable. As a result, the text variable might not be initialized before the convert method returns (when character isn’t a, b or c). This possible un-initialization state leads to a compile-time error.
Incorrect
The switch statement doesn’t have a default label, meaning it doesn’t cover all the allowable values of the character variable. As a result, the text variable might not be initialized before the convert method returns (when character isn’t a, b or c). This possible un-initialization state leads to a compile-time error.
Unattempted
The switch statement doesn’t have a default label, meaning it doesn’t cover all the allowable values of the character variable. As a result, the text variable might not be initialized before the convert method returns (when character isn’t a, b or c). This possible un-initialization state leads to a compile-time error.
Question 36 of 65
36. Question
Given:
class Foo {
void myMethod() {
System.out.println(“Foo”);
}
}
public class Bar extends Foo {
void myMethod() {
System.out.println(“Bar”);
}
public static void main(String[] args) {
Foo foo = new Foo();
Bar bar = (Bar) foo;
bar.myMethod();
}
}
What is the program’s output?
Correct
Notice the casting of an object reference doesn’t touch the object it refers to. Instead, casting is just a way to label an object in another way, possibly exposing more fields and methods of that object.
In the given program, the foo variable references an object of the Foo class. This object cannot be assigned to the Bar reference type at runtime since Bar isn’t a supertype of Foo. This mismatch leads to a ClassCastException.
Had the first statement in the main method been:
Foo foo = new Foo();
Option B would have been the correct answer as variable foo referenced a Bar object in the first place. A Bar object is, of course, assignable to the reference type Bar after the casting.
Incorrect
Notice the casting of an object reference doesn’t touch the object it refers to. Instead, casting is just a way to label an object in another way, possibly exposing more fields and methods of that object.
In the given program, the foo variable references an object of the Foo class. This object cannot be assigned to the Bar reference type at runtime since Bar isn’t a supertype of Foo. This mismatch leads to a ClassCastException.
Had the first statement in the main method been:
Foo foo = new Foo();
Option B would have been the correct answer as variable foo referenced a Bar object in the first place. A Bar object is, of course, assignable to the reference type Bar after the casting.
Unattempted
Notice the casting of an object reference doesn’t touch the object it refers to. Instead, casting is just a way to label an object in another way, possibly exposing more fields and methods of that object.
In the given program, the foo variable references an object of the Foo class. This object cannot be assigned to the Bar reference type at runtime since Bar isn’t a supertype of Foo. This mismatch leads to a ClassCastException.
Had the first statement in the main method been:
Foo foo = new Foo();
Option B would have been the correct answer as variable foo referenced a Bar object in the first place. A Bar object is, of course, assignable to the reference type Bar after the casting.
Question 37 of 65
37. Question
Given:
public class Test {
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = null;
Test test3 = new Test();
Test test4 = null;
test1 = test2; // Line 1
test2 = test3; // Line 2
test3 = test4; // Line 3
test2 = test4; // Line 4
test4 = test1; // Line 5
}
}
After which line all objects created in the main method are eligible for garbage collection?
Correct
The object created in the first statement is eligible for garbage collection right after line 1 as it becomes unreachable when variable test1 is set to null.
After line 2, variables test2 and test3 refer to the second object, which was created in the third statement of the program. These variables are then set to null on line 3 and 4. This is the point where the second object is ready to be garbage collected.
Incorrect
The object created in the first statement is eligible for garbage collection right after line 1 as it becomes unreachable when variable test1 is set to null.
After line 2, variables test2 and test3 refer to the second object, which was created in the third statement of the program. These variables are then set to null on line 3 and 4. This is the point where the second object is ready to be garbage collected.
Unattempted
The object created in the first statement is eligible for garbage collection right after line 1 as it becomes unreachable when variable test1 is set to null.
After line 2, variables test2 and test3 refer to the second object, which was created in the third statement of the program. These variables are then set to null on line 3 and 4. This is the point where the second object is ready to be garbage collected.
Question 38 of 65
38. Question
Given:
public class Test {
static public void main(String[] args) {
var result = 0;
int i1 = 1;
int i2 = 2;
float i3 = i1++ + ++i2; // Line 1
result = (i1 + i2) / i3; // Line 2
System.out.println(result);
}
}
What is the output of the given program?
Correct
The local variable result is declared with var and initialized to a value of type int. As a result, the type of this variable is inferred to be int.
Variable i3 is of type float, implying the expression type on the right-hand side of the assignment on line 2 is float as well. This expression result is then assigned to a variable of type int. This type mismatch leads to a compile-time error.
Incorrect
The local variable result is declared with var and initialized to a value of type int. As a result, the type of this variable is inferred to be int.
Variable i3 is of type float, implying the expression type on the right-hand side of the assignment on line 2 is float as well. This expression result is then assigned to a variable of type int. This type mismatch leads to a compile-time error.
Unattempted
The local variable result is declared with var and initialized to a value of type int. As a result, the type of this variable is inferred to be int.
Variable i3 is of type float, implying the expression type on the right-hand side of the assignment on line 2 is float as well. This expression result is then assigned to a variable of type int. This type mismatch leads to a compile-time error.
Question 39 of 65
39. Question
Which of the following is not correct about a module descriptor?
Correct
A module may be required transitively by another module, which is, in turn, required by the current module. In such a case, the transitive dependency module doesn’t need to be specified in the module descriptor.
Incorrect
A module may be required transitively by another module, which is, in turn, required by the current module. In such a case, the transitive dependency module doesn’t need to be specified in the module descriptor.
Unattempted
A module may be required transitively by another module, which is, in turn, required by the current module. In such a case, the transitive dependency module doesn’t need to be specified in the module descriptor.
Question 40 of 65
40. Question
Which of the following code fragments prints “true” to the console?
Correct
As per the JDK API Specification, the Arrays#equals method returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
Options A and C are incorrect because the equals method is provided with an incorrect number of arguments. Option B is incorrect as elements in the two arrays aren’t in the same order.
Option D is correct as the two arrays have the same elements in the same order over the specified ranges.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#equals(java.lang.Object%5B%5D,int,int,java.lang.Object%5B%5D,int,int)
Incorrect
As per the JDK API Specification, the Arrays#equals method returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
Options A and C are incorrect because the equals method is provided with an incorrect number of arguments. Option B is incorrect as elements in the two arrays aren’t in the same order.
Option D is correct as the two arrays have the same elements in the same order over the specified ranges.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#equals(java.lang.Object%5B%5D,int,int,java.lang.Object%5B%5D,int,int)
Unattempted
As per the JDK API Specification, the Arrays#equals method returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
Options A and C are incorrect because the equals method is provided with an incorrect number of arguments. Option B is incorrect as elements in the two arrays aren’t in the same order.
Option D is correct as the two arrays have the same elements in the same order over the specified ranges.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#equals(java.lang.Object%5B%5D,int,int,java.lang.Object%5B%5D,int,int)
Question 41 of 65
41. Question
Given:
List list = new ArrayList();
list.add(1); // Line 1
Object object = list.get(list.size()); // Line 2
System.out.println(object);
What is the output of the given code fragment?
Correct
There’s nothing wrong with the given code as the int value is auto-boxed to an object when it’s added to the given list. After adding this element, the list contains only a single element, which is at index 0. However, the expression on line 2 attempts to get the element at index 1. This access is out of bounds, thereby resulting in an ArrayIndexOutOfBoundsException.
Incorrect
There’s nothing wrong with the given code as the int value is auto-boxed to an object when it’s added to the given list. After adding this element, the list contains only a single element, which is at index 0. However, the expression on line 2 attempts to get the element at index 1. This access is out of bounds, thereby resulting in an ArrayIndexOutOfBoundsException.
Unattempted
There’s nothing wrong with the given code as the int value is auto-boxed to an object when it’s added to the given list. After adding this element, the list contains only a single element, which is at index 0. However, the expression on line 2 attempts to get the element at index 1. This access is out of bounds, thereby resulting in an ArrayIndexOutOfBoundsException.
Question 42 of 65
42. Question
Given:
public class Foo {
static int number;
String text;
void methodA() {
System.out.println(number); // Line 1
System.out.println(text); // Line 2
}
static void methodB() {
System.out.println(number); // Line 3
System.out.println(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. However, it’s allowable to access class’s members the other way around – a non-static context can access a static field or call a static method. This means only line 4 is invalid.
Incorrect
A static context, such as the body of a static method, cannot reference a non-static field method. However, it’s allowable to access class’s members the other way around – a non-static context can access a static field or call a static method. This means only line 4 is invalid.
Unattempted
A static context, such as the body of a static method, cannot reference a non-static field method. However, it’s allowable to access class’s members the other way around – a non-static context can access a static field or call a static method. This means only line 4 is invalid.
Question 43 of 65
43. Question
Given:
String text = “JAVA”;
while (text.equalsIgnoreCase(“JAVA”)) {
text = text.toLowerCase();
}
System.out.println(text);
What is the output of the given code?
Correct
The value of variable text before the while statement is “JAVA”, making the condition expression evaluate to true. Inside the body of the while statement, this variable is set to the lowercase version of its original value: from “JAVA” to “java”.
At this point, the condition expression is evaluated again, and it’s still true. The while body doesn’t change the value of text anymore because it’s already in lowercase. This process happens over and over again as the condition expression keeps returning true. As a result, we’ll end up with an infinite loop.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Incorrect
The value of variable text before the while statement is “JAVA”, making the condition expression evaluate to true. Inside the body of the while statement, this variable is set to the lowercase version of its original value: from “JAVA” to “java”.
At this point, the condition expression is evaluated again, and it’s still true. The while body doesn’t change the value of text anymore because it’s already in lowercase. This process happens over and over again as the condition expression keeps returning true. As a result, we’ll end up with an infinite loop.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Unattempted
The value of variable text before the while statement is “JAVA”, making the condition expression evaluate to true. Inside the body of the while statement, this variable is set to the lowercase version of its original value: from “JAVA” to “java”.
At this point, the condition expression is evaluated again, and it’s still true. The while body doesn’t change the value of text anymore because it’s already in lowercase. This process happens over and over again as the condition expression keeps returning true. As a result, we’ll end up with an infinite loop.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Question 44 of 65
44. Question
Given two source files:
package test;
public class Foo { }
And:
package test;
public class Bar {
Foo foo;
}
These files are placed in a test folder:
test
Foo.java
Bar.java
Which statement is correct about compiling these files using the javac command?
Correct
Options A and B are incorrect as we can run the javac command from any directory, provided the path from that working directory to the source files are valid.
Options C and D are incorrect as the order of source files doesn’t matter to the javac command.
Incorrect
Options A and B are incorrect as we can run the javac command from any directory, provided the path from that working directory to the source files are valid.
Options C and D are incorrect as the order of source files doesn’t matter to the javac command.
Unattempted
Options A and B are incorrect as we can run the javac command from any directory, provided the path from that working directory to the source files are valid.
Options C and D are incorrect as the order of source files doesn’t matter to the javac command.
The second statement in the given code fragment assigns the value of input2 to input1, then assigns this value to output1 as well. This means after the initialization of output1, the values of input1, input2 and output1 are all false.
Likewise, in the next statement, input2 and output2 are set to the value of input1. At this point, all the variables that have been declared are false.
In the fourth statement, variables input1 and input2 are compared. Since they are both false, the comparison result is true, meaning the value of output3 is true.
Incorrect
The second statement in the given code fragment assigns the value of input2 to input1, then assigns this value to output1 as well. This means after the initialization of output1, the values of input1, input2 and output1 are all false.
Likewise, in the next statement, input2 and output2 are set to the value of input1. At this point, all the variables that have been declared are false.
In the fourth statement, variables input1 and input2 are compared. Since they are both false, the comparison result is true, meaning the value of output3 is true.
Unattempted
The second statement in the given code fragment assigns the value of input2 to input1, then assigns this value to output1 as well. This means after the initialization of output1, the values of input1, input2 and output1 are all false.
Likewise, in the next statement, input2 and output2 are set to the value of input1. At this point, all the variables that have been declared are false.
In the fourth statement, variables input1 and input2 are compared. Since they are both false, the comparison result is true, meaning the value of output3 is true.
Question 46 of 65
46. Question
Given:
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
test.isNegative(-1);
System.out.println(“try”);
} catch (Exception e) {
System.out.println(“catch”);
} finally {
System.out.println(“finally”);
}
}
void isNegative(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 isNegative method.
In the given program, no exception is thrown. This means the catch block is ignored and the finally block gets executed after the try block completes.
Incorrect
RuntimeException is an unchecked exception, thus we don’t need a throws clause on the declaration of the isNegative method.
In the given program, no exception is thrown. This means the catch block is ignored and the finally block gets executed after the try block completes.
Unattempted
RuntimeException is an unchecked exception, thus we don’t need a throws clause on the declaration of the isNegative method.
In the given program, no exception is thrown. This means the catch block is ignored and the finally block gets executed after the try block completes.
Question 47 of 65
47. Question
Given:
class Foo {
String name = “Foo”;
void print() {
System.out.println(this.name); // Line 1
}
}
class Bar extends Foo {
String name = “Bar”;
void print() {
super.print(); // Line 2
}
}
public class Test {
public static void main(String[] args) {
new Bar().print();
}
}
What is the program’s output?
double getAverage() {
if (numbers.isEmpty()) {
return 0;
}
double sum = 0;
for (int i : numbers) {
sum += i;
}
return sum / numbers.size();
}
}
Which two changes enable the given class to be encapsulated?
Correct
The numbers field must be private, so other classes cannot modify the referenced list.
In the existing code, the List object passed to the constructor is referenced from the caller. This list is assigned directly to the numbers field; hence, the caller can manipulate it. The change in option E separates the passed-in object and the object referenced from the numbers field, preventing the caller from accessing that field.
Incorrect
The numbers field must be private, so other classes cannot modify the referenced list.
In the existing code, the List object passed to the constructor is referenced from the caller. This list is assigned directly to the numbers field; hence, the caller can manipulate it. The change in option E separates the passed-in object and the object referenced from the numbers field, preventing the caller from accessing that field.
Unattempted
The numbers field must be private, so other classes cannot modify the referenced list.
In the existing code, the List object passed to the constructor is referenced from the caller. This list is assigned directly to the numbers field; hence, the caller can manipulate it. The change in option E separates the passed-in object and the object referenced from the numbers field, preventing the caller from accessing that field.
Question 49 of 65
49. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.loop(0);
}
void loop(int number) {
while (number < 5) {
number++;
continue;
System.out.print(number + " ");
}
}
}
What is the program's output?
Correct
The continue statement skips the current iteration of a while, hence the System.out.print is never reached regardless of what happened before. This unreachable statement causes a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Incorrect
The continue statement skips the current iteration of a while, hence the System.out.print is never reached regardless of what happened before. This unreachable statement causes a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Unattempted
The continue statement skips the current iteration of a while, hence the System.out.print is never reached regardless of what happened before. This unreachable statement causes a compile-time error.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Question 50 of 65
50. Question
Which of the following helps Java achieve high performance?
Correct
When a program is running, the JIT compiler compiles byte-code written in class files into native code. During this compilation, compiler uses various mechanism to improve the performance at runtime, including reordering statements (this is implemented only if the result won’t be affected by the reordering).
Option B is incorrect as the JVM doesn’t execute code in parallel automatically. We must use the Java API or a supporting library to instruct the JVM to do so.
Option C is incorrect as that compilation has nothing to do with runtime performance.
Option D is incorrect as the garbage collector, in fact, reduces performance because it consumes resources. As a result, garbage collection only happens when the JVM isn’t very busy.
Incorrect
When a program is running, the JIT compiler compiles byte-code written in class files into native code. During this compilation, compiler uses various mechanism to improve the performance at runtime, including reordering statements (this is implemented only if the result won’t be affected by the reordering).
Option B is incorrect as the JVM doesn’t execute code in parallel automatically. We must use the Java API or a supporting library to instruct the JVM to do so.
Option C is incorrect as that compilation has nothing to do with runtime performance.
Option D is incorrect as the garbage collector, in fact, reduces performance because it consumes resources. As a result, garbage collection only happens when the JVM isn’t very busy.
Unattempted
When a program is running, the JIT compiler compiles byte-code written in class files into native code. During this compilation, compiler uses various mechanism to improve the performance at runtime, including reordering statements (this is implemented only if the result won’t be affected by the reordering).
Option B is incorrect as the JVM doesn’t execute code in parallel automatically. We must use the Java API or a supporting library to instruct the JVM to do so.
Option C is incorrect as that compilation has nothing to do with runtime performance.
Option D is incorrect as the garbage collector, in fact, reduces performance because it consumes resources. As a result, garbage collection only happens when the JVM isn’t very busy.
Question 51 of 65
51. Question
Given:
public class Test {
int decrease(int number) {
return –number – number–;
}
public static void main(String[] args) {
Test test = new Test();
int number = test.decrease(10);
number -= number– – –number;
System.out.println(number);
}
}
What is the program’s output?
Correct
The expression –number – number– in the decrease method always evaluates to 0, regardless of the number value. The reason is that after the pre-decrement operation is performed, the value of number is subtracted by itself. The final value of number after the whole expression is computed is reduced once again by the post-decrement operator. However, this value is just ignored.
Now, let’s rewrite the second and third statements in the main method:
int number = 0;
number -= number– – –number;
Notice the pre-decrement operator decreases a variable before it’s used, while the post-decrement operator reduces a variable after all the other operations are done. As a result, we can re-write the two statements we just mentioned as:
int number = 0;
number = number – (number – (number – 1));
number = number – 1;
At this point, it should be clear that the final value of the number variable is -2.
Incorrect
The expression –number – number– in the decrease method always evaluates to 0, regardless of the number value. The reason is that after the pre-decrement operation is performed, the value of number is subtracted by itself. The final value of number after the whole expression is computed is reduced once again by the post-decrement operator. However, this value is just ignored.
Now, let’s rewrite the second and third statements in the main method:
int number = 0;
number -= number– – –number;
Notice the pre-decrement operator decreases a variable before it’s used, while the post-decrement operator reduces a variable after all the other operations are done. As a result, we can re-write the two statements we just mentioned as:
int number = 0;
number = number – (number – (number – 1));
number = number – 1;
At this point, it should be clear that the final value of the number variable is -2.
Unattempted
The expression –number – number– in the decrease method always evaluates to 0, regardless of the number value. The reason is that after the pre-decrement operation is performed, the value of number is subtracted by itself. The final value of number after the whole expression is computed is reduced once again by the post-decrement operator. However, this value is just ignored.
Now, let’s rewrite the second and third statements in the main method:
int number = 0;
number -= number– – –number;
Notice the pre-decrement operator decreases a variable before it’s used, while the post-decrement operator reduces a variable after all the other operations are done. As a result, we can re-write the two statements we just mentioned as:
int number = 0;
number = number – (number – (number – 1));
number = number – 1;
At this point, it should be clear that the final value of the number variable is -2.
Question 52 of 65
52. Question
Which command lists all observable modules on the system?
Given:
public class Test {
void methodA() throws ArithmeticException { // Line 1
throw new RuntimeException(); // Line 2
}
void methodB() throws IOException { // Line 3
methodA(); // Line 4
}
public static void main(String[] args) {
Test test = new Test();
try {
test.methodA(); // Line 5
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
Which line of code causes a compile-time error?
Correct
ArithmeticException and RuntimeException are unchecked exceptions, thus we don’t need to catch or specify them. Nonetheless, doing so is legitimate.
methodB never throws an IOException but still has this exception type in the throws clause of its declaration. Again, this clause is unnecessary but still valid.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
Incorrect
ArithmeticException and RuntimeException are unchecked exceptions, thus we don’t need to catch or specify them. Nonetheless, doing so is legitimate.
methodB never throws an IOException but still has this exception type in the throws clause of its declaration. Again, this clause is unnecessary but still valid.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
Unattempted
ArithmeticException and RuntimeException are unchecked exceptions, thus we don’t need to catch or specify them. Nonetheless, doing so is legitimate.
methodB never throws an IOException but still has this exception type in the throws clause of its declaration. Again, this clause is unnecessary but still valid.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
public class MyBar extends MyFoo {
private String text = “Bar”; // Line 1
public static void main(String[] args) {
MyBar myBar = new MyBar();
myBar.printText(); // Line 2
System.out.println(myBar.text); // Line 3
}
}
What is the program’s output?
Correct
Unlike methods, fields in a subclass hide those of the same name in the superclass. Therefore, the fields in the subclass don’t need to have equal-or-less restrictive access modifier than the hidden fields. This means there’s nothing wrong on line 1.
The text field in the MyFoo class is inaccessible to the MyBar class. However, when calling the printText method, that field is accessed from within the printText method itself. This method belongs to the MyFoo class. As a result, the access is valid, and the output is the value of the text field in the MyFoo class.
The statement on line 3 is simple – it just prints out the text field in the MyBar class.
Incorrect
Unlike methods, fields in a subclass hide those of the same name in the superclass. Therefore, the fields in the subclass don’t need to have equal-or-less restrictive access modifier than the hidden fields. This means there’s nothing wrong on line 1.
The text field in the MyFoo class is inaccessible to the MyBar class. However, when calling the printText method, that field is accessed from within the printText method itself. This method belongs to the MyFoo class. As a result, the access is valid, and the output is the value of the text field in the MyFoo class.
The statement on line 3 is simple – it just prints out the text field in the MyBar class.
Unattempted
Unlike methods, fields in a subclass hide those of the same name in the superclass. Therefore, the fields in the subclass don’t need to have equal-or-less restrictive access modifier than the hidden fields. This means there’s nothing wrong on line 1.
The text field in the MyFoo class is inaccessible to the MyBar class. However, when calling the printText method, that field is accessed from within the printText method itself. This method belongs to the MyFoo class. As a result, the access is valid, and the output is the value of the text field in the MyFoo class.
The statement on line 3 is simple – it just prints out the text field in the MyBar class.
Question 55 of 65
55. Question
Given:
class Data {
int number;
Data(int number) {
this.number = number;
}
}
public class Test {
Data data1 = new Data(1);
Data data2 = new Data(2);
Data[] getData() {
return new Data[]{data1, data2};
}
public static void main(String[] args) {
Test test = new Test();
–test.getData()[1].number;
Data[] data = test.getData();
int number1 = (data[0]).number;
int number2 = (data[1]).number;
System.out.println(number1 + ” and ” + number2);
}
}
What is the program’s output?
Correct
In the expression –test.getData()[1].number, both the object member access and array access operators has higher precedence than the unary pre-decrement operator. As a result, the decrement operator takes action on the number field of the Data object at the array index 1. This object is also referenced by the data2 field of the Test object.
Due to the change in the expression mentioned above, the number value in the data2 field is decreased from 2 to 1, resulting in the string “1 and 2” being printed.
Incorrect
In the expression –test.getData()[1].number, both the object member access and array access operators has higher precedence than the unary pre-decrement operator. As a result, the decrement operator takes action on the number field of the Data object at the array index 1. This object is also referenced by the data2 field of the Test object.
Due to the change in the expression mentioned above, the number value in the data2 field is decreased from 2 to 1, resulting in the string “1 and 2” being printed.
Unattempted
In the expression –test.getData()[1].number, both the object member access and array access operators has higher precedence than the unary pre-decrement operator. As a result, the decrement operator takes action on the number field of the Data object at the array index 1. This object is also referenced by the data2 field of the Test object.
Due to the change in the expression mentioned above, the number value in the data2 field is decreased from 2 to 1, resulting in the string “1 and 2” being printed.
public class Test {
public static void main(String[] args) {
Integer integer = new Integer(1); // Line 2
System.out.println(integer.equals(1)); // Line 3
}
}
What is the given program’s output?
Correct
There’s nothing wrong when declaring a class with the same name as a class in another package. These classes don’t conflict as they can be distinguished by the containing packages. This means line 1 is valid.
However, there’s a problem on line 2. The Integer type over here is the class defined in the same package, not the java.lang.Integer class we’re familiar with. This custom Integer class doesn’t have a constructor with an int parameter; hence, the compiler fails.
Line 3 is valid because the custom Integer class extends the Object class, implying it has an equals method inherited from that superclass.
Incorrect
There’s nothing wrong when declaring a class with the same name as a class in another package. These classes don’t conflict as they can be distinguished by the containing packages. This means line 1 is valid.
However, there’s a problem on line 2. The Integer type over here is the class defined in the same package, not the java.lang.Integer class we’re familiar with. This custom Integer class doesn’t have a constructor with an int parameter; hence, the compiler fails.
Line 3 is valid because the custom Integer class extends the Object class, implying it has an equals method inherited from that superclass.
Unattempted
There’s nothing wrong when declaring a class with the same name as a class in another package. These classes don’t conflict as they can be distinguished by the containing packages. This means line 1 is valid.
However, there’s a problem on line 2. The Integer type over here is the class defined in the same package, not the java.lang.Integer class we’re familiar with. This custom Integer class doesn’t have a constructor with an int parameter; hence, the compiler fails.
Line 3 is valid because the custom Integer class extends the Object class, implying it has an equals method inherited from that superclass.
Question 57 of 65
57. Question
Given:
Double d = 1.5;
++d;
System.out.println(d);
What happens when compiling and executing the given code fragment?
Correct
There’s nothing wrong with the given code. The pre-increment operator works on a floating-point value just like it does on an integral number.
In fact, the d variable refers to an object, but this object is auto-unboxed, allowing the pre-increment operator to take action.
Incorrect
There’s nothing wrong with the given code. The pre-increment operator works on a floating-point value just like it does on an integral number.
In fact, the d variable refers to an object, but this object is auto-unboxed, allowing the pre-increment operator to take action.
Unattempted
There’s nothing wrong with the given code. The pre-increment operator works on a floating-point value just like it does on an integral number.
In fact, the d variable refers to an object, but this object is auto-unboxed, allowing the pre-increment operator to take action.
Question 58 of 65
58. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.loop(0);
}
void loop(int number) {
do {
if (number % 2 != 0) break; // Line 1
} while (number++ > 0); // Line 2
System.out.println(number);
}
}
What is the program’s output?
Correct
There’s nothing wrong with the given code.
In the first do/while iteration, the if condition expression evaluates to false, so the break statement is ignored. The number variable is then increased to 1 within the while condition expression.
In the second do/while iteration, the if expression evaluates to true, the break statement is executed, and the do/while construct exits. At this point, the value of number is 1.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Incorrect
There’s nothing wrong with the given code.
In the first do/while iteration, the if condition expression evaluates to false, so the break statement is ignored. The number variable is then increased to 1 within the while condition expression.
In the second do/while iteration, the if expression evaluates to true, the break statement is executed, and the do/while construct exits. At this point, the value of number is 1.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Unattempted
There’s nothing wrong with the given code.
In the first do/while iteration, the if condition expression evaluates to false, so the break statement is ignored. The number variable is then increased to 1 within the while condition expression.
In the second do/while iteration, the if expression evaluates to true, the break statement is executed, and the do/while construct exits. At this point, the value of number is 1.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Question 59 of 65
59. Question
Given:
public class Test {
static void methodA() {
methodB(); // Line 1
}
void methodB() {
methodC(); // Line 2
}
static void methodC() {
System.out.println(“Hello”);
}
}
Which of the following changes must be made to allow the given code to compile?
Correct
There’s nothing wrong on line 2 as an instance method can call a static one in the same class without any class or object reference.
On line 1, an instance method is called from a static context. Such an invocation leads to a compile-time error. To fix this problem, we must call the instance method via an object reference.
Notice option A is incorrect because the this keyword references the current object, hence can only be used in a non-static content.
Incorrect
There’s nothing wrong on line 2 as an instance method can call a static one in the same class without any class or object reference.
On line 1, an instance method is called from a static context. Such an invocation leads to a compile-time error. To fix this problem, we must call the instance method via an object reference.
Notice option A is incorrect because the this keyword references the current object, hence can only be used in a non-static content.
Unattempted
There’s nothing wrong on line 2 as an instance method can call a static one in the same class without any class or object reference.
On line 1, an instance method is called from a static context. Such an invocation leads to a compile-time error. To fix this problem, we must call the instance method via an object reference.
Notice option A is incorrect because the this keyword references the current object, hence can only be used in a non-static content.
Question 60 of 65
60. Question
Given:
class MyException extends Exception /* Position 1 */ {
/* Position 2 */
}
public class Test {
static void methodA() throws MyException /* Position 3 */ {
throw new MyException();
}
static void methodB() /* Position 4 */ {
methodA();
}
public static void main(String[] args) /* Position 5 */ {
try {
methodB();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Which two changes enable when made independently enable the given program to compile?
Correct
The given program fails because methodA throws a checked exception, but this exception isn’t caught or specified in methodB.
The solution in option A converts the exception to unchecked, hence it doesn’t need to be handled anymore. The solution in option D specifies the exception in the declaration of methodB. Both solutions are correct ways to solve the compile-time error.
Incorrect
The given program fails because methodA throws a checked exception, but this exception isn’t caught or specified in methodB.
The solution in option A converts the exception to unchecked, hence it doesn’t need to be handled anymore. The solution in option D specifies the exception in the declaration of methodB. Both solutions are correct ways to solve the compile-time error.
Unattempted
The given program fails because methodA throws a checked exception, but this exception isn’t caught or specified in methodB.
The solution in option A converts the exception to unchecked, hence it doesn’t need to be handled anymore. The solution in option D specifies the exception in the declaration of methodB. Both solutions are correct ways to solve the compile-time error.
Question 61 of 65
61. Question
Given:
interface I { /* a valid body */ }
class C1 implements I { /* a valid body */ }
class C2 extends C1 { /* a valid body */ }
class Foo {
protected C1 get() { /* a valid body */ }
}
abstract class Bar extends Foo {
// Insert here
}
Which of the following method can be inserted into the Bar class?
Correct
In method overriding, the return type of the overriding method must be the same or a subtype of the overridden method’s return type. The get method in the Foo class returns a C1 object, implying its overriding method must return a C1 or C2 object. Options C and D are clearly incorrect, then.
A static method cannot override an instance one; thus, option E is incorrect.
An overriding method must be declared with the same or less restrictive scope than the overridden method. In option F, the get method is defined without an access modifier, which is package-private by default. This scope is more restrictive than protected, hence the option is incorrect.
Option A is incorrect as the given method doesn’t have a body but isn’t declared with the abstract keyword.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Incorrect
In method overriding, the return type of the overriding method must be the same or a subtype of the overridden method’s return type. The get method in the Foo class returns a C1 object, implying its overriding method must return a C1 or C2 object. Options C and D are clearly incorrect, then.
A static method cannot override an instance one; thus, option E is incorrect.
An overriding method must be declared with the same or less restrictive scope than the overridden method. In option F, the get method is defined without an access modifier, which is package-private by default. This scope is more restrictive than protected, hence the option is incorrect.
Option A is incorrect as the given method doesn’t have a body but isn’t declared with the abstract keyword.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Unattempted
In method overriding, the return type of the overriding method must be the same or a subtype of the overridden method’s return type. The get method in the Foo class returns a C1 object, implying its overriding method must return a C1 or C2 object. Options C and D are clearly incorrect, then.
A static method cannot override an instance one; thus, option E is incorrect.
An overriding method must be declared with the same or less restrictive scope than the overridden method. In option F, the get method is defined without an access modifier, which is package-private by default. This scope is more restrictive than protected, hence the option is incorrect.
Option A is incorrect as the given method doesn’t have a body but isn’t declared with the abstract keyword.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Question 62 of 65
62. Question
Given:
public class Person {
final String name;
void setName() {
name = “John”;
}
public static void main(String[] args) {
Person person = new Person();
person.setName();
System.out.println(person.name);
}
}
What’s the program’s output?
Correct
When an instance field is declared as final, it must be set before an object is fully constructed. This can be done by initializing it at the declaration point:
final String name = “John”;
Using a constructor:
Person() {
name = “John”;
}
Or relying on an initialization block:
{
name = “John”;
}
In the given program, the name field is final but initialized when the Person object is created, hence a compile-time error.
Incorrect
When an instance field is declared as final, it must be set before an object is fully constructed. This can be done by initializing it at the declaration point:
final String name = “John”;
Using a constructor:
Person() {
name = “John”;
}
Or relying on an initialization block:
{
name = “John”;
}
In the given program, the name field is final but initialized when the Person object is created, hence a compile-time error.
Unattempted
When an instance field is declared as final, it must be set before an object is fully constructed. This can be done by initializing it at the declaration point:
final String name = “John”;
Using a constructor:
Person() {
name = “John”;
}
Or relying on an initialization block:
{
name = “John”;
}
In the given program, the name field is final but initialized when the Person object is created, hence a compile-time error.
Question 63 of 65
63. Question
Given:
float f1 = 1.0;
float f2 = 1e0;
float f3 = 1;
float f4 = 1.0f;
float f5 = 0x1F;
float f6 = 1L;
var f7 = 1.1;
Which two declarations are invalid?
Correct
The numeric literals assigned to variables f1 and f2 don’t have the f or F suffix, hence they are double values. The conversion from double to float is narrowing and requires a cast operator. Such an operator is missing, meaning the declarations of those variables are invalid.
The literals assigned to variables f4 and f5 ends with f and F, respectively. These suffixes denote float numbers, meaning options D and E are incorrect.
The literal assigned to f3 is an int value, while that assigned to f4 is a long. The conversion from int or long to float is widening, thus no cast operator is needed. Option C and F are incorrect, then.
The type of the value assigned to f7 is double. This variable is declared using var, hence it’s inferred to be of type double. There’s nothing wrong here, and option G is invalid.
Incorrect
The numeric literals assigned to variables f1 and f2 don’t have the f or F suffix, hence they are double values. The conversion from double to float is narrowing and requires a cast operator. Such an operator is missing, meaning the declarations of those variables are invalid.
The literals assigned to variables f4 and f5 ends with f and F, respectively. These suffixes denote float numbers, meaning options D and E are incorrect.
The literal assigned to f3 is an int value, while that assigned to f4 is a long. The conversion from int or long to float is widening, thus no cast operator is needed. Option C and F are incorrect, then.
The type of the value assigned to f7 is double. This variable is declared using var, hence it’s inferred to be of type double. There’s nothing wrong here, and option G is invalid.
Unattempted
The numeric literals assigned to variables f1 and f2 don’t have the f or F suffix, hence they are double values. The conversion from double to float is narrowing and requires a cast operator. Such an operator is missing, meaning the declarations of those variables are invalid.
The literals assigned to variables f4 and f5 ends with f and F, respectively. These suffixes denote float numbers, meaning options D and E are incorrect.
The literal assigned to f3 is an int value, while that assigned to f4 is a long. The conversion from int or long to float is widening, thus no cast operator is needed. Option C and F are incorrect, then.
The type of the value assigned to f7 is double. This variable is declared using var, hence it’s inferred to be of type double. There’s nothing wrong here, and option G is invalid.
Question 64 of 65
64. Question
Given:
String s = “Hello” + ” ” + “World!”;
How many objects are created when the given statement is executed?
Correct
Normally, the compiler doesn’t make any calculation. However, when it comes to a constant expression, the compiler calculates the expression value at compile time.
The given expression is, in fact, compiled into:
String s = “Hello World!”;
Clearly, there’s only one object created at runtime.
Incorrect
Normally, the compiler doesn’t make any calculation. However, when it comes to a constant expression, the compiler calculates the expression value at compile time.
The given expression is, in fact, compiled into:
String s = “Hello World!”;
Clearly, there’s only one object created at runtime.
Unattempted
Normally, the compiler doesn’t make any calculation. However, when it comes to a constant expression, the compiler calculates the expression value at compile time.
The given expression is, in fact, compiled into:
String s = “Hello World!”;
Clearly, there’s only one object created at runtime.
Question 65 of 65
65. Question
Given:
int i, j;
for (i = j = 0; ; ++i, j–) {
if (i – j > 10) {
break;
}
}
System.out.println(i + ” ” + j);
What is the output of the given code?
Correct
There’s nothing wrong with the given code. The body of the for construct keeps running until i – j > 10. This happens when variables i and j reach 6 and -6, respectively. At this point, the break statement is executed and the for construct exits.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Incorrect
There’s nothing wrong with the given code. The body of the for construct keeps running until i – j > 10. This happens when variables i and j reach 6 and -6, respectively. At this point, the break statement is executed and the for construct exits.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Unattempted
There’s nothing wrong with the given code. The body of the for construct keeps running until i – j > 10. This happens when variables i and j reach 6 and -6, respectively. At this point, the break statement is executed and the for construct exits.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
X
Use Page numbers below to navigate to other practice tests