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 13 "
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:
package test;
class Data {
/* Insert here */ String s;
}
Which access modifiers when added to the s field enable it to be visible outside of the test package?
Correct
Notice the Data class is declared with no access modifier, meaning it’s package-private. Since this class is invisible outside of the containing package, its members are invisible too.
Incorrect
Notice the Data class is declared with no access modifier, meaning it’s package-private. Since this class is invisible outside of the containing package, its members are invisible too.
Unattempted
Notice the Data class is declared with no access modifier, meaning it’s package-private. Since this class is invisible outside of the containing package, its members are invisible too.
Question 2 of 65
2. Question
Given:
var list = new ArrayList<>(); // Line 1
var i1 = 1, i2 = 2; // Line 2
var string; // Line 3
var object = null; // Line 4
var array = {1, 2}; // Line 5
Which line of code successfully compiles?
Correct
Notice var can only be used if the type of the declared variable can be inferred from its initial value.
Line 2 is invalid as var isn’t allowed in a compound declaration.
Line 3 is invalid as var must go with a variable initializer.
Line 4 is invalid as the variable declared with var mustn’t be initialized to null.
Line 5 is invalid as an array initializer needs an explicit target-type.
Reference: https://openjdk.java.net/projects/amber/LVTIFAQ.html
Incorrect
Notice var can only be used if the type of the declared variable can be inferred from its initial value.
Line 2 is invalid as var isn’t allowed in a compound declaration.
Line 3 is invalid as var must go with a variable initializer.
Line 4 is invalid as the variable declared with var mustn’t be initialized to null.
Line 5 is invalid as an array initializer needs an explicit target-type.
Reference: https://openjdk.java.net/projects/amber/LVTIFAQ.html
Unattempted
Notice var can only be used if the type of the declared variable can be inferred from its initial value.
Line 2 is invalid as var isn’t allowed in a compound declaration.
Line 3 is invalid as var must go with a variable initializer.
Line 4 is invalid as the variable declared with var mustn’t be initialized to null.
Line 5 is invalid as an array initializer needs an explicit target-type.
Reference: https://openjdk.java.net/projects/amber/LVTIFAQ.html
Question 3 of 65
3. Question
Given:
List list1 = new ArrayList<>(List.of(1, 2, 3, 4, 5));
List list2 = new ArrayList<>(List.of(1, 2, 3));
list1.removeIf(e -> e % 2 == 0);
list1.retainAll(list2);
System.out.println(list1);
What is the output of the given code fragment?
Which two options specify the module to compile when using the javac command?
Correct
Here’s a description of the -m and –module options of the javac command:
Compiles only the specified module and checks time stamps.
All the other options aren’t recognized by this command.
Reference: https://docs.oracle.com/en/java/javase/11/tools/javac.html
Incorrect
Here’s a description of the -m and –module options of the javac command:
Compiles only the specified module and checks time stamps.
All the other options aren’t recognized by this command.
Reference: https://docs.oracle.com/en/java/javase/11/tools/javac.html
Unattempted
Here’s a description of the -m and –module options of the javac command:
Compiles only the specified module and checks time stamps.
All the other options aren’t recognized by this command.
Reference: https://docs.oracle.com/en/java/javase/11/tools/javac.html
Question 5 of 65
5. Question
Given:
interface Foo {
abstract void m(); // Line 1
}
class Bar implements Foo {
@Override // Line 2
void m() { } // Line 3
}
What is correct about the given code?
Correct
An interface method is public by default, implying the m method in interface Foo is public-scoped. The Bar class overrides this method, but the overriding method is package-private, which is more restrictive than public. Such an overriding is forbidden. To make the code compile, we must add the public access modifier to the method in the Bar class.
An interface method is also abstract by default. Normally, we don’t need the abstract modifier on a method. However, adding this keyword doesn’t do any harm.
Incorrect
An interface method is public by default, implying the m method in interface Foo is public-scoped. The Bar class overrides this method, but the overriding method is package-private, which is more restrictive than public. Such an overriding is forbidden. To make the code compile, we must add the public access modifier to the method in the Bar class.
An interface method is also abstract by default. Normally, we don’t need the abstract modifier on a method. However, adding this keyword doesn’t do any harm.
Unattempted
An interface method is public by default, implying the m method in interface Foo is public-scoped. The Bar class overrides this method, but the overriding method is package-private, which is more restrictive than public. Such an overriding is forbidden. To make the code compile, we must add the public access modifier to the method in the Bar class.
An interface method is also abstract by default. Normally, we don’t need the abstract modifier on a method. However, adding this keyword doesn’t do any harm.
Question 6 of 65
6. Question
Given:
public class Test {
public static void main(String[] args) {
int[] array = {0, 2, 4};
int index;
int element = array[index = 1]++;
System.out.println(index + “: ” + array[index] + ” -> ” + element);
}
}
What is the program’s output?
Correct
When the array access is executed, the index variable is set to 1 before any other operation. We can then re-write the second and third statements as:
int index = 1;
int element = array[1]++;
Notice an array access has higher precedence than a unary post-increment operator, hence the third statement can be re-written again:
int element = array[1];
array[1] = array[1] + 1;
The element variable is set to the number at index 1 in the array; this number is then incremented by 1. At this point, it’s clear option E is the correct answer.
Incorrect
When the array access is executed, the index variable is set to 1 before any other operation. We can then re-write the second and third statements as:
int index = 1;
int element = array[1]++;
Notice an array access has higher precedence than a unary post-increment operator, hence the third statement can be re-written again:
int element = array[1];
array[1] = array[1] + 1;
The element variable is set to the number at index 1 in the array; this number is then incremented by 1. At this point, it’s clear option E is the correct answer.
Unattempted
When the array access is executed, the index variable is set to 1 before any other operation. We can then re-write the second and third statements as:
int index = 1;
int element = array[1]++;
Notice an array access has higher precedence than a unary post-increment operator, hence the third statement can be re-written again:
int element = array[1];
array[1] = array[1] + 1;
The element variable is set to the number at index 1 in the array; this number is then incremented by 1. At this point, it’s clear option E is the correct answer.
Question 7 of 65
7. Question
Given:
String select(int number) {
String output;
switch (number) {
case 0:
default:
case 1:
output = “positive”;
}
return output;
}
Which statement is correct about the given method?
Correct
There’s no break statement in any label, implying the last statement always runs regardless of the value of the number variable. This means the output variable is set to “positive” no matter which value is passed in.
Notice the default label doesn’t need to be the last one in a switch construct. Its associated statements are always executed if no matching cases are found.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Incorrect
There’s no break statement in any label, implying the last statement always runs regardless of the value of the number variable. This means the output variable is set to “positive” no matter which value is passed in.
Notice the default label doesn’t need to be the last one in a switch construct. Its associated statements are always executed if no matching cases are found.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Unattempted
There’s no break statement in any label, implying the last statement always runs regardless of the value of the number variable. This means the output variable is set to “positive” no matter which value is passed in.
Notice the default label doesn’t need to be the last one in a switch construct. Its associated statements are always executed if no matching cases are found.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Question 8 of 65
8. Question
Given:
package foo;
public class MyFoo {
// a valid body
}
And:
package foo.bar;
public class MyBar {
// a valid body
}
And:
package test;
// Insert here
public class Test {
public static void main(String[] args) {
new MyFoo();
new MyBar();
}
}
Which statement when inserted into the Test class allows it to compile?
Correct
Importing a package doesn’t mean its sub-packages or super-packages are imported automatically. If we want to use a type by its simple name, we must import either that particular type or the whole containing package, such as:
import foo.*;
import foo.bar.*;
Or:
import foo.MyFoo;
import foo.bar.MyBar;
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Incorrect
Importing a package doesn’t mean its sub-packages or super-packages are imported automatically. If we want to use a type by its simple name, we must import either that particular type or the whole containing package, such as:
import foo.*;
import foo.bar.*;
Or:
import foo.MyFoo;
import foo.bar.MyBar;
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Unattempted
Importing a package doesn’t mean its sub-packages or super-packages are imported automatically. If we want to use a type by its simple name, we must import either that particular type or the whole containing package, such as:
import foo.*;
import foo.bar.*;
Or:
import foo.MyFoo;
import foo.bar.MyBar;
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
public class Test {
static void methodA() throws MyException {
throw new MyException(“A custom exception”);
}
static void methodB() {
methodA();
}
public static void main(String[] args) {
try {
methodB();
} catch (Exception e) {
System.out.println(e);
}
}
}
What can be the program’s output?
Correct
When an exception object is passed to the println method, its toString method is called. This method is inherited from the Throwable class, returning a short description of the throwable object. The result is the concatenation of:
the name of the class of the exception object
“: ” (a colon and a space)
the result of invoking the exception object’s getLocalizedMessage method
Had the statement inside the catch block been replaced by e.printStackTrace(); option D would have been the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#toString()
Incorrect
When an exception object is passed to the println method, its toString method is called. This method is inherited from the Throwable class, returning a short description of the throwable object. The result is the concatenation of:
the name of the class of the exception object
“: ” (a colon and a space)
the result of invoking the exception object’s getLocalizedMessage method
Had the statement inside the catch block been replaced by e.printStackTrace(); option D would have been the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#toString()
Unattempted
When an exception object is passed to the println method, its toString method is called. This method is inherited from the Throwable class, returning a short description of the throwable object. The result is the concatenation of:
the name of the class of the exception object
“: ” (a colon and a space)
the result of invoking the exception object’s getLocalizedMessage method
Had the statement inside the catch block been replaced by e.printStackTrace(); option D would have been the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#toString()
Question 10 of 65
10. Question
Given:
public class Test {
static public void main(String[] args) {
String string1 = “hello”;
var chars = string1.toCharArray(); // Line 1
StringBuilder builder = new StringBuilder();
for (var c : chars) { // Line 2
builder.append(c);
}
String string2 = builder.toString();
System.out.println(string1 == string2);
System.out.println(string1.equals(string2));
}
}
What is the program’s output?
Correct
The use of var in the given program is valid, hence no compile-time errors occur.
The StringBuilder#toString method creates a new String object rather than taking one from the string constant pool. Consequently, the first comparison result is false. The second result is true as the contents of the two compared strings are the same.
Incorrect
The use of var in the given program is valid, hence no compile-time errors occur.
The StringBuilder#toString method creates a new String object rather than taking one from the string constant pool. Consequently, the first comparison result is false. The second result is true as the contents of the two compared strings are the same.
Unattempted
The use of var in the given program is valid, hence no compile-time errors occur.
The StringBuilder#toString method creates a new String object rather than taking one from the string constant pool. Consequently, the first comparison result is false. The second result is true as the contents of the two compared strings are the same.
Question 11 of 65
11. Question
Given:
public class Test {
void Test(String input) { // Line 1
System.out.println(input);
}
static public void main(String[] args) {
new Test(); // Line 2
new Test(“hello”); // Line 3
}
}
On which line the program fails to compile?
Correct
Notice the declaration on line 1 isn’t a constructor but rather a method. The reason is that it has a return type.
Since the Test class doesn’t have an explicit constructor, the compiler adds a no-argument constructor by default. The statement on line 2 calls that constructor, hence no error occurs over here. The statement on line 3 is different – it calls a non-existent constructor, resulting in a compile-time error.
Incorrect
Notice the declaration on line 1 isn’t a constructor but rather a method. The reason is that it has a return type.
Since the Test class doesn’t have an explicit constructor, the compiler adds a no-argument constructor by default. The statement on line 2 calls that constructor, hence no error occurs over here. The statement on line 3 is different – it calls a non-existent constructor, resulting in a compile-time error.
Unattempted
Notice the declaration on line 1 isn’t a constructor but rather a method. The reason is that it has a return type.
Since the Test class doesn’t have an explicit constructor, the compiler adds a no-argument constructor by default. The statement on line 2 calls that constructor, hence no error occurs over here. The statement on line 3 is different – it calls a non-existent constructor, resulting in a compile-time error.
Question 12 of 65
12. Question
Given:
List original = List.of(“A”);
List derived = new ArrayList<>(original);
original.add(1, “B”);
System.out.println(derived);
What is the output of the given code?
Given:
for (int i = 0; false; i++) {
System.out.println(“Inside”);
}
System.out.println(“Outside”);
What happens when compiling and executing the given code fragment?
Correct
The condition expression of the for statement is a constant, implying its value is taken into account during compilation. The false value means that the contained statement isn’t executed even once. The unreachability of this statement makes the given code unable to compiled.
This excerpt from section 14.21 of the Java Language Specification should make things clears:
A basic for statement can complete normally if and only if at least one of the following is true:
The for statement is reachable, there is a condition expression, and the condition expression is not a constant expression with value true.
There is a reachable break statement that exits the for statement.
The contained statement is reachable if and only if the for statement is reachable and the condition expression is not a constant expression whose value is false.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Incorrect
The condition expression of the for statement is a constant, implying its value is taken into account during compilation. The false value means that the contained statement isn’t executed even once. The unreachability of this statement makes the given code unable to compiled.
This excerpt from section 14.21 of the Java Language Specification should make things clears:
A basic for statement can complete normally if and only if at least one of the following is true:
The for statement is reachable, there is a condition expression, and the condition expression is not a constant expression with value true.
There is a reachable break statement that exits the for statement.
The contained statement is reachable if and only if the for statement is reachable and the condition expression is not a constant expression whose value is false.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Unattempted
The condition expression of the for statement is a constant, implying its value is taken into account during compilation. The false value means that the contained statement isn’t executed even once. The unreachability of this statement makes the given code unable to compiled.
This excerpt from section 14.21 of the Java Language Specification should make things clears:
A basic for statement can complete normally if and only if at least one of the following is true:
The for statement is reachable, there is a condition expression, and the condition expression is not a constant expression with value true.
There is a reachable break statement that exits the for statement.
The contained statement is reachable if and only if the for statement is reachable and the condition expression is not a constant expression whose value is false.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.21
Question 14 of 65
14. Question
Given:
public class Person {
String name = “John”;
static int age = 25;
static String getName() {
return new Person().name;
}
int getAge() {
return age;
}
public static void main(String[] args) {
Person person = new Person();
// Line 1
System.out.println(nameAndAge);
}
}
Which statement when inserted at line 1 allows the program to print “John 25” to the console?
Correct
The age field and getName method are static, hence they can be accessed by the class itself or one of its instances. The name field and getAge method, on the other hand, are non-static. These members can only be accessed by class instances.
In option C, the instance field name is accessed by the Person class. In option E, both instance members are also access by the class. Therefore, these options are incorrect.
Incorrect
The age field and getName method are static, hence they can be accessed by the class itself or one of its instances. The name field and getAge method, on the other hand, are non-static. These members can only be accessed by class instances.
In option C, the instance field name is accessed by the Person class. In option E, both instance members are also access by the class. Therefore, these options are incorrect.
Unattempted
The age field and getName method are static, hence they can be accessed by the class itself or one of its instances. The name field and getAge method, on the other hand, are non-static. These members can only be accessed by class instances.
In option C, the instance field name is accessed by the Person class. In option E, both instance members are also access by the class. Therefore, these options are incorrect.
Question 15 of 65
15. Question
Given:
public class Test {
public static void main(String[] args) {
CharSequence sequence = “test”; // Line 1
String string = (String) sequence.toUpperCase(); // Line 2
System.out.println(string);
}
}
What is the program’s output?
Correct
Notice object member access has the highest precedence in Java. This operation is performed before the casting, implying the toUpperCase method is called on an object of the CharSequence type. This type doesn’t have such a method, resulting in a compile-time error.
Option B would have been the correct answer had line 2 been changed to:
String string = ((String) sequence).toUpperCase();
Incorrect
Notice object member access has the highest precedence in Java. This operation is performed before the casting, implying the toUpperCase method is called on an object of the CharSequence type. This type doesn’t have such a method, resulting in a compile-time error.
Option B would have been the correct answer had line 2 been changed to:
String string = ((String) sequence).toUpperCase();
Unattempted
Notice object member access has the highest precedence in Java. This operation is performed before the casting, implying the toUpperCase method is called on an object of the CharSequence type. This type doesn’t have such a method, resulting in a compile-time error.
Option B would have been the correct answer had line 2 been changed to:
String string = ((String) sequence).toUpperCase();
Question 16 of 65
16. Question
Which of the following is correct about module path of the java command?
Correct
Option A is incorrect as we can specify the module path with the -m option as well
Option C is incorrect as module path has no default value.
Here’s a description of the –module-path and -p option:
A semicolon (;) separated list of directories in which each directory is a directory of modules.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Incorrect
Option A is incorrect as we can specify the module path with the -m option as well
Option C is incorrect as module path has no default value.
Here’s a description of the –module-path and -p option:
A semicolon (;) separated list of directories in which each directory is a directory of modules.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Unattempted
Option A is incorrect as we can specify the module path with the -m option as well
Option C is incorrect as module path has no default value.
Here’s a description of the –module-path and -p option:
A semicolon (;) separated list of directories in which each directory is a directory of modules.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Question 17 of 65
17. Question
Given a source file named Foo.java:
package test;
class Foo {
int f;
Foo(int f) {
this.f = f;
}
}
// Insert here
Which of the following class declarations can be inserted into the given file?
Correct
A source file doesn’t need to contain a public type. However, when it does, the name of the file must correspond to the name of the public type. The given source file has name Foo.java, hence it cannot contain any public type not named Foo. Option D is incorrect, then.
The declaration in option A doesn’t have a constructor. For this reason, the compiler would insert a default constructor with no parameter:
class Bar extends Foo {
Bar() {
super();
}
}
This constructor would call the no-parameter constructor of the Foo class. However, this superclass has an explicit constructor with one parameter; thus, the compiler backs off, not inserting the default constructor. Since a no-parameter constructor doesn’t exist, the invocation super() fails to compile.
In option B, the Bar class has a no-parameter constructor. Notice the compiler automatically inserts a call to super() as the first statement in any constructor if it doesn’t call another constructor in the same class or a constructor in the superclass. Therefore, the class declaration in this case is exactly the same as the one in option A.
In option C, the Bar class doesn’t explicitly extend any class, meaning Bar is a direct subtype of the Object class. This Object class has a no-parameter constructor, hence the invocation super() is valid.
Incorrect
A source file doesn’t need to contain a public type. However, when it does, the name of the file must correspond to the name of the public type. The given source file has name Foo.java, hence it cannot contain any public type not named Foo. Option D is incorrect, then.
The declaration in option A doesn’t have a constructor. For this reason, the compiler would insert a default constructor with no parameter:
class Bar extends Foo {
Bar() {
super();
}
}
This constructor would call the no-parameter constructor of the Foo class. However, this superclass has an explicit constructor with one parameter; thus, the compiler backs off, not inserting the default constructor. Since a no-parameter constructor doesn’t exist, the invocation super() fails to compile.
In option B, the Bar class has a no-parameter constructor. Notice the compiler automatically inserts a call to super() as the first statement in any constructor if it doesn’t call another constructor in the same class or a constructor in the superclass. Therefore, the class declaration in this case is exactly the same as the one in option A.
In option C, the Bar class doesn’t explicitly extend any class, meaning Bar is a direct subtype of the Object class. This Object class has a no-parameter constructor, hence the invocation super() is valid.
Unattempted
A source file doesn’t need to contain a public type. However, when it does, the name of the file must correspond to the name of the public type. The given source file has name Foo.java, hence it cannot contain any public type not named Foo. Option D is incorrect, then.
The declaration in option A doesn’t have a constructor. For this reason, the compiler would insert a default constructor with no parameter:
class Bar extends Foo {
Bar() {
super();
}
}
This constructor would call the no-parameter constructor of the Foo class. However, this superclass has an explicit constructor with one parameter; thus, the compiler backs off, not inserting the default constructor. Since a no-parameter constructor doesn’t exist, the invocation super() fails to compile.
In option B, the Bar class has a no-parameter constructor. Notice the compiler automatically inserts a call to super() as the first statement in any constructor if it doesn’t call another constructor in the same class or a constructor in the superclass. Therefore, the class declaration in this case is exactly the same as the one in option A.
In option C, the Bar class doesn’t explicitly extend any class, meaning Bar is a direct subtype of the Object class. This Object class has a no-parameter constructor, hence the invocation super() is valid.
Question 18 of 65
18. Question
Which two of the following lambda expressions are valid?
Correct
Option B is incorrect because if a lambda expression has two or more parameters, they must be wrapped within parentheses.
Option C is incorrect as we cannot specify a type for a parameter while ignoring it on another parameter. We must indicate types for all parameters or leaving them off altogether.
Option D is incorrect as we cannot mix the var keyword with an explicit parameter type.
Options A and E may look weird, but they’re valid. The body of these expressions is declared in its complete form, enclosed within a pair of curly brackets.
Incorrect
Option B is incorrect because if a lambda expression has two or more parameters, they must be wrapped within parentheses.
Option C is incorrect as we cannot specify a type for a parameter while ignoring it on another parameter. We must indicate types for all parameters or leaving them off altogether.
Option D is incorrect as we cannot mix the var keyword with an explicit parameter type.
Options A and E may look weird, but they’re valid. The body of these expressions is declared in its complete form, enclosed within a pair of curly brackets.
Unattempted
Option B is incorrect because if a lambda expression has two or more parameters, they must be wrapped within parentheses.
Option C is incorrect as we cannot specify a type for a parameter while ignoring it on another parameter. We must indicate types for all parameters or leaving them off altogether.
Option D is incorrect as we cannot mix the var keyword with an explicit parameter type.
Options A and E may look weird, but they’re valid. The body of these expressions is declared in its complete form, enclosed within a pair of curly brackets.
Question 19 of 65
19. Question
Given:
int[][] array1 = {{1}, {2, 3}, {4, 5, 6}};
int[] array2 = array1[1];
System.out.println(array2[2][3]);
What is the output of the given code fragment?
Correct
The array2 variable references an element of a two-dimensional array. This element is a one-dimensional array. However, the array access expression in the println method treats array2 as if it were a two-dimensional array. Consequently, a compile-time error occurs.
Incorrect
The array2 variable references an element of a two-dimensional array. This element is a one-dimensional array. However, the array access expression in the println method treats array2 as if it were a two-dimensional array. Consequently, a compile-time error occurs.
Unattempted
The array2 variable references an element of a two-dimensional array. This element is a one-dimensional array. However, the array access expression in the println method treats array2 as if it were a two-dimensional array. Consequently, a compile-time error occurs.
Question 20 of 65
20. Question
Given:
String string1 = new String(“ja”) + new String(“va”);
String string2 = “ja” + “va”;
String string3 = “java”;
boolean b1 = string1 == string2;
boolean b2 = string2 == string3;
System.out.println(b1 + ” ” + b2);
What is the given code fragment’s output?
Correct
When a string literal is referenced, it’s added to the string constant pool. Likewise, when a string-valued constant expression is computed, the result is added to the pool as well. This means both variables string2 and string3 reference the string “java” from the constant pool.
There’s nothing wrong with the first statement. The two strings on the right-hand side of the assignment are concatenated and a new String object with the content “java” is constructed. The String#intern method isn’t called on this resulting object, implying it isn’t added to the string constant pool.
The string1 variable references an object outside of the constant pool, while the two others refer to an object in the pool. These references lead to the output shown in option C.
Incorrect
When a string literal is referenced, it’s added to the string constant pool. Likewise, when a string-valued constant expression is computed, the result is added to the pool as well. This means both variables string2 and string3 reference the string “java” from the constant pool.
There’s nothing wrong with the first statement. The two strings on the right-hand side of the assignment are concatenated and a new String object with the content “java” is constructed. The String#intern method isn’t called on this resulting object, implying it isn’t added to the string constant pool.
The string1 variable references an object outside of the constant pool, while the two others refer to an object in the pool. These references lead to the output shown in option C.
Unattempted
When a string literal is referenced, it’s added to the string constant pool. Likewise, when a string-valued constant expression is computed, the result is added to the pool as well. This means both variables string2 and string3 reference the string “java” from the constant pool.
There’s nothing wrong with the first statement. The two strings on the right-hand side of the assignment are concatenated and a new String object with the content “java” is constructed. The String#intern method isn’t called on this resulting object, implying it isn’t added to the string constant pool.
The string1 variable references an object outside of the constant pool, while the two others refer to an object in the pool. These references lead to the output shown in option C.
Question 21 of 65
21. Question
Given:
package test;
public class Test {
public static void main(String[] args) {
System.out.println(“Hello”);
}
}
The compiled class file Test.class is stored in a folder called test. How can we execute the given program using the command line?
Correct
The given class belongs to the test package, hence its qualified name is test.Test. This qualified name must be passed to the java command when executed in the parent of the test folder.
Incorrect
The given class belongs to the test package, hence its qualified name is test.Test. This qualified name must be passed to the java command when executed in the parent of the test folder.
Unattempted
The given class belongs to the test package, hence its qualified name is test.Test. This qualified name must be passed to the java command when executed in the parent of the test folder.
Question 22 of 65
22. Question
Given:
String s = “2”;
switch (s) {
case 1:
System.out.println(1);
case 2:
System.out.println(2);
}
What happens when compiling and executing the given code fragment?
Correct
The switch expression is of type String, while the label expressions are of type int. This type mismatch makes the given code unable to compile.
Incorrect
The switch expression is of type String, while the label expressions are of type int. This type mismatch makes the given code unable to compile.
Unattempted
The switch expression is of type String, while the label expressions are of type int. This type mismatch makes the given code unable to compile.
Question 23 of 65
23. Question
Given:
public class Test {
public static void main(String[] args) {
String x = “hello”;
try {
throw new IOException(x = “good bye”);
} catch (Exception e) {
System.out.println(x);
}
System.out.println(x);
}
}
What is the program’s output?
Correct
The x variable is initialized to “hello” in its declaration. In the try block, this variable is set to “good bye”, which is then used as a message wrapped in the thrown exception. Notice despite the expression passed to the IOException constructor looking weird, it’s just an expression evaluating to a string.
Since the x variable is changed to “good bye”, both the println statement prints this string to the console.
Incorrect
The x variable is initialized to “hello” in its declaration. In the try block, this variable is set to “good bye”, which is then used as a message wrapped in the thrown exception. Notice despite the expression passed to the IOException constructor looking weird, it’s just an expression evaluating to a string.
Since the x variable is changed to “good bye”, both the println statement prints this string to the console.
Unattempted
The x variable is initialized to “hello” in its declaration. In the try block, this variable is set to “good bye”, which is then used as a message wrapped in the thrown exception. Notice despite the expression passed to the IOException constructor looking weird, it’s just an expression evaluating to a string.
Since the x variable is changed to “good bye”, both the println statement prints this string to the console.
Question 24 of 65
24. Question
Given:
public class Test {
void aMethod(long… argument) {
System.out.println(“Method A”);
}
public static void main(String[] args) {
Test test = new Test();
int number = ‘a’; // Line 1
test.aMethod(number); // Line 2
}
}
What is the program’s output?
Correct
There’s nothing wrong with the given code. When assigning a literal to a variable of a primitive type, the compiler just checks if the input value is within the range of the declared primitive type. In the main method, the number variable is set to the Unicode code point of character ‘a’.
The three methods named aMethod are overloaded. When calling these methods with a given argument, the compiler determines the applicable method by following these three phases – which is documented in the section 15.12.2 of the Java Language Specification:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
All the overloaded methods match the invocation with an argument of type int. Among them the first method matches in phase 3, the second matches in phase 1 and the third matches in phase 2. This means the second method is given the priority.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Incorrect
There’s nothing wrong with the given code. When assigning a literal to a variable of a primitive type, the compiler just checks if the input value is within the range of the declared primitive type. In the main method, the number variable is set to the Unicode code point of character ‘a’.
The three methods named aMethod are overloaded. When calling these methods with a given argument, the compiler determines the applicable method by following these three phases – which is documented in the section 15.12.2 of the Java Language Specification:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
All the overloaded methods match the invocation with an argument of type int. Among them the first method matches in phase 3, the second matches in phase 1 and the third matches in phase 2. This means the second method is given the priority.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Unattempted
There’s nothing wrong with the given code. When assigning a literal to a variable of a primitive type, the compiler just checks if the input value is within the range of the declared primitive type. In the main method, the number variable is set to the Unicode code point of character ‘a’.
The three methods named aMethod are overloaded. When calling these methods with a given argument, the compiler determines the applicable method by following these three phases – which is documented in the section 15.12.2 of the Java Language Specification:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
All the overloaded methods match the invocation with an argument of type int. Among them the first method matches in phase 3, the second matches in phase 1 and the third matches in phase 2. This means the second method is given the priority.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Question 25 of 65
25. Question
Given:
String s1 = “java”;
String s2 = s1.replace(‘A’, ‘a’);
String s3 = s1.replace(“A”, “a”);
String s4 = s1.replaceAll(“A”, “a”);
System.out.print((s1 == s2) + ” “);
System.out.print((s1 == s3) + ” “);
System.out.print(s1 == s4);
What is the output of the given code fragment
Correct
All the replace and replaceAll methods always return the String object on which those methods are called if the target character/string/regex isn’t included in that string.
Incorrect
All the replace and replaceAll methods always return the String object on which those methods are called if the target character/string/regex isn’t included in that string.
Unattempted
All the replace and replaceAll methods always return the String object on which those methods are called if the target character/string/regex isn’t included in that string.
public class Test {
public static void main(String[] args) {
MyInterface func1 = (i1, i2) -> i1 > i2;
MyInterface func2 = (i1, i2) -> i1 < i2;
System.out.println(func1.m(1, 2));
System.out.println(func2.m(2, 1));
}
}
What is the given program's output?
Correct
A lambda expression can only be used in places where a functional interface is expected. Such an interface has only a single abstract method. MyInterface in the given program contains two abstract methods, hence cannot be represented by a lambda expression. The incorrect use of lambda expressions leads to a compile-time error.
Incorrect
A lambda expression can only be used in places where a functional interface is expected. Such an interface has only a single abstract method. MyInterface in the given program contains two abstract methods, hence cannot be represented by a lambda expression. The incorrect use of lambda expressions leads to a compile-time error.
Unattempted
A lambda expression can only be used in places where a functional interface is expected. Such an interface has only a single abstract method. MyInterface in the given program contains two abstract methods, hence cannot be represented by a lambda expression. The incorrect use of lambda expressions leads to a compile-time error.
Question 27 of 65
27. Question
Given:
public class Test {
int getNumber() {
return 0;
}
float getNumber() {
return 1;
}
public static void main(String[] args) {
Test test = new Test();
long l = test.getNumber();
double d = test.getNumber();
System.out.println(l + d);
}
}
What is the given program’s output?
Correct
Notice the return type of a method isn’t part of its signature. In the given code, the Test class has two methods with the exact same signature. Such a declaration is invalid, resulting in a compile-time error.
Incorrect
Notice the return type of a method isn’t part of its signature. In the given code, the Test class has two methods with the exact same signature. Such a declaration is invalid, resulting in a compile-time error.
Unattempted
Notice the return type of a method isn’t part of its signature. In the given code, the Test class has two methods with the exact same signature. Such a declaration is invalid, resulting in a compile-time error.
Question 28 of 65
28. Question
Given:
public class Test {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
for (int element : array) {
if (element % 2 == 0)
continue;
else
break;
element *= 2;
}
System.out.println(Arrays.toString(array));
}
}
What is the given program’s output?
Correct
Inside the for-each statement, the if-then construct either skips the current iteration or breaks it, depending on the element value. This means the statement following that construct is unreachable, resulting in a compile-time error.
Incorrect
Inside the for-each statement, the if-then construct either skips the current iteration or breaks it, depending on the element value. This means the statement following that construct is unreachable, resulting in a compile-time error.
Unattempted
Inside the for-each statement, the if-then construct either skips the current iteration or breaks it, depending on the element value. This means the statement following that construct is unreachable, resulting in a compile-time error.
Question 29 of 65
29. Question
Given:
var a1[] = new int[]{1, 2};
var a2[] = {1, 2};
var a3 = {1, 2};
Which variable declarations are valid?
Correct
An array initializer requires an explicit type because the compiler cannot infer the type of its elements. This means var cannot be used in the last declaration.
The first two statements are also invalid because the syntax is incorrect – a pair of brackets cannot be appended to a variable name.
Incorrect
An array initializer requires an explicit type because the compiler cannot infer the type of its elements. This means var cannot be used in the last declaration.
The first two statements are also invalid because the syntax is incorrect – a pair of brackets cannot be appended to a variable name.
Unattempted
An array initializer requires an explicit type because the compiler cannot infer the type of its elements. This means var cannot be used in the last declaration.
The first two statements are also invalid because the syntax is incorrect – a pair of brackets cannot be appended to a variable name.
Question 30 of 65
30. Question
Given:
interface Foo {
// declaration of the m method
}
class Bar implements Foo {
void m() throws IOException { }
}
Which of the following is correct about the m abstract method in the Foo interface?
Correct
When method overriding occurs, the overriding method cannot specify a checked exception that isn’t specified by the overridden one.
In the given code, the subclass method specifies a checked exception. This means the superclass method must specify an exception that’s assignable from IOException.
Incorrect
When method overriding occurs, the overriding method cannot specify a checked exception that isn’t specified by the overridden one.
In the given code, the subclass method specifies a checked exception. This means the superclass method must specify an exception that’s assignable from IOException.
Unattempted
When method overriding occurs, the overriding method cannot specify a checked exception that isn’t specified by the overridden one.
In the given code, the subclass method specifies a checked exception. This means the superclass method must specify an exception that’s assignable from IOException.
Question 31 of 65
31. Question
Given the class directory structure of a module:
my.foo
moduleinfo.class
foo
Test.class
Which command starts the Test program when executed in the parent folder of my.foo?
Correct
When start a program with the java command, the module path, module name and the main class must be specified.
Incorrect
When start a program with the java command, the module path, module name and the main class must be specified.
Unattempted
When start a program with the java command, the module path, module name and the main class must be specified.
Question 32 of 65
32. Question
Given:
public class Test {
public static void main(String[] args) {
var var = new ArrayList<>(); // Line 1
Data input = new Data(“My data”);
var.add(input); // Line 2
Data output = var.get(0); // Line 3
System.out.println(output.content);
}
}
What happens when compiling and executing the given program?
Correct
Notice var isn’t a keyword. Instead, it’s a local variable type inference, and we’re free to use this word as an identifier. Therefore, the declaration on line 1 is valid.
Note that the ArrayList class on the right-hand side of the assignment on line 1 is specified without a type argument. This means elements of the created list are considered to be of type Object.
When adding an object of type Data to the provided list, it’s cast to type Object automatically, meaning the statement on line 2 is valid.
On the other hand, when getting an element from the list, this element is of type Object. As a result, it must be assigned to a variable of type Object as well or be cast to a more specific type. The statement on line 3 doesn’t satisfy this requirement, leading to a compile-time error.
Incorrect
Notice var isn’t a keyword. Instead, it’s a local variable type inference, and we’re free to use this word as an identifier. Therefore, the declaration on line 1 is valid.
Note that the ArrayList class on the right-hand side of the assignment on line 1 is specified without a type argument. This means elements of the created list are considered to be of type Object.
When adding an object of type Data to the provided list, it’s cast to type Object automatically, meaning the statement on line 2 is valid.
On the other hand, when getting an element from the list, this element is of type Object. As a result, it must be assigned to a variable of type Object as well or be cast to a more specific type. The statement on line 3 doesn’t satisfy this requirement, leading to a compile-time error.
Unattempted
Notice var isn’t a keyword. Instead, it’s a local variable type inference, and we’re free to use this word as an identifier. Therefore, the declaration on line 1 is valid.
Note that the ArrayList class on the right-hand side of the assignment on line 1 is specified without a type argument. This means elements of the created list are considered to be of type Object.
When adding an object of type Data to the provided list, it’s cast to type Object automatically, meaning the statement on line 2 is valid.
On the other hand, when getting an element from the list, this element is of type Object. As a result, it must be assigned to a variable of type Object as well or be cast to a more specific type. The statement on line 3 doesn’t satisfy this requirement, leading to a compile-time error.
Question 33 of 65
33. Question
Given:
public class Test {
static int m() throws RuntimeException {
throw new ArithmeticException();
}
public static void main(String[] args) {
int[] arr = null;
int i = arr[m()];
}
}
What happens when compiling and executing the given program?
Correct
To access an element in the arr array, the m method is called first to calculate the index. This calling throws an ArithmeticException, and the program terminates abruptly.
Had the m method returned an int value instead of throwing an exception, option B would have been the correct answer.
Incorrect
To access an element in the arr array, the m method is called first to calculate the index. This calling throws an ArithmeticException, and the program terminates abruptly.
Had the m method returned an int value instead of throwing an exception, option B would have been the correct answer.
Unattempted
To access an element in the arr array, the m method is called first to calculate the index. This calling throws an ArithmeticException, and the program terminates abruptly.
Had the m method returned an int value instead of throwing an exception, option B would have been the correct answer.
Question 34 of 65
34. Question
Given:
do {
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
++i;
} while (i < 10);
What happens when compiling and executing the given code fragment?
Correct
The i variable is declared inside the do block, implying it’s invisible to any statements that aren’t specified in that block. Nonetheless, the condition expression of outer loop still refers to i, leading to a compile-time error.
Incorrect
The i variable is declared inside the do block, implying it’s invisible to any statements that aren’t specified in that block. Nonetheless, the condition expression of outer loop still refers to i, leading to a compile-time error.
Unattempted
The i variable is declared inside the do block, implying it’s invisible to any statements that aren’t specified in that block. Nonetheless, the condition expression of outer loop still refers to i, leading to a compile-time error.
Question 35 of 65
35. Question
Given:
interface Foo {
int number = 0; // Line 1
void modify(int arg); // Line 2
}
class Bar implements Foo {
int number = 10; // Line 3
public void modify(int arg) { // Line 4
number += arg;
}
}
Which of the following is incorrect about the given code?
Correct
An interface method is public by default. However, the Foo interface is declared without an access modifier, implying it’s package-private. This interface is invisible outside of the containing package; hence, its members are invisible too. This is why option B is the correct answer.
A field in an interface is public, static, and final by default. Since the variable declared on line 1 is final, its value cannot be changed.
If line 3 is commented out, the number variable inside the modify method of the Bar class refers to the number field defined in the Foo interface. This field is final, and modifying a final field results in a compile-time error.
The modify method in the Bar class overrides the method of the same name in the Foo interface. Notice an interface method is public, and its overriding methods mustn’t have a more restrictive access modifier. Removing the public modifier on line 4 makes the class method package-private, leading to a compile-time error.
Incorrect
An interface method is public by default. However, the Foo interface is declared without an access modifier, implying it’s package-private. This interface is invisible outside of the containing package; hence, its members are invisible too. This is why option B is the correct answer.
A field in an interface is public, static, and final by default. Since the variable declared on line 1 is final, its value cannot be changed.
If line 3 is commented out, the number variable inside the modify method of the Bar class refers to the number field defined in the Foo interface. This field is final, and modifying a final field results in a compile-time error.
The modify method in the Bar class overrides the method of the same name in the Foo interface. Notice an interface method is public, and its overriding methods mustn’t have a more restrictive access modifier. Removing the public modifier on line 4 makes the class method package-private, leading to a compile-time error.
Unattempted
An interface method is public by default. However, the Foo interface is declared without an access modifier, implying it’s package-private. This interface is invisible outside of the containing package; hence, its members are invisible too. This is why option B is the correct answer.
A field in an interface is public, static, and final by default. Since the variable declared on line 1 is final, its value cannot be changed.
If line 3 is commented out, the number variable inside the modify method of the Bar class refers to the number field defined in the Foo interface. This field is final, and modifying a final field results in a compile-time error.
The modify method in the Bar class overrides the method of the same name in the Foo interface. Notice an interface method is public, and its overriding methods mustn’t have a more restrictive access modifier. Removing the public modifier on line 4 makes the class method package-private, leading to a compile-time error.
Question 36 of 65
36. Question
Given:
interface Foo {
int count = 0;
void increase();
}
public class Bar implements Foo {
@Override // Line 1
public void increase() {
count++; // Line 2
}
public static void main(String[] args) {
Foo foo = new Bar(); // Line 3
foo.increase(); // Line 4
System.out.println(foo.count); // Line 5
}
}
On which line the given program fails to compile?
As per section 8.4.8.2 of the Java Language Specification, it is a compile-time error if a static method hides an instance method.
In the given code, myMethod is an instance method in the class Foo, but is a static method in class Bar, hence the compilation fails.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.8.2
Incorrect
As per section 8.4.8.2 of the Java Language Specification, it is a compile-time error if a static method hides an instance method.
In the given code, myMethod is an instance method in the class Foo, but is a static method in class Bar, hence the compilation fails.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.8.2
Unattempted
As per section 8.4.8.2 of the Java Language Specification, it is a compile-time error if a static method hides an instance method.
In the given code, myMethod is an instance method in the class Foo, but is a static method in class Bar, hence the compilation fails.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.8.2
Question 38 of 65
38. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.compare(1, 2, 3);
}
private void compare(int x, int y, int z) {
var in = x > y – z && (x > z – y && x < y + z);
var out = x < y - z && (x < z - y || x < y + z);
System.out.println(in);
System.out.println(out);
}
}
What is the program's output?
Correct
The key point about this kind of question is the operator precedence. An additive operator (+ -) has higher precedence than a logical one. Among all the logical operators, NOT (!) has the highest precedence, then AND (&&), and OR (||) has the least. All these operators are evaluated from left to right.
In this question, parentheses are used to override operator precedence. In both the computation statements, the parentheses instruct the JVM to evaluate the second operator before the first one. If we removed these parentheses, option C would be the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Incorrect
The key point about this kind of question is the operator precedence. An additive operator (+ -) has higher precedence than a logical one. Among all the logical operators, NOT (!) has the highest precedence, then AND (&&), and OR (||) has the least. All these operators are evaluated from left to right.
In this question, parentheses are used to override operator precedence. In both the computation statements, the parentheses instruct the JVM to evaluate the second operator before the first one. If we removed these parentheses, option C would be the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Unattempted
The key point about this kind of question is the operator precedence. An additive operator (+ -) has higher precedence than a logical one. Among all the logical operators, NOT (!) has the highest precedence, then AND (&&), and OR (||) has the least. All these operators are evaluated from left to right.
In this question, parentheses are used to override operator precedence. In both the computation statements, the parentheses instruct the JVM to evaluate the second operator before the first one. If we removed these parentheses, option C would be the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Question 39 of 65
39. Question
Given a module declaration:
module my.foo {
requires java.logging;
requires java.xml;
exports my.bar;
}
Which module graph correctly describes the my.foo module:
Correct
my.bar is an exported package, hence has nothing to do with the module graph. This means options A and B are incorrect.
All modules depend on the base module, so there must be a direct dependency between the my.foo module and java.base module. Option D doesn’t have such a dependency.
Notice option D shows references from the java.logging and java.xml modules to the base module. This is correct but has nothing to do with the my.foo module.
Incorrect
my.bar is an exported package, hence has nothing to do with the module graph. This means options A and B are incorrect.
All modules depend on the base module, so there must be a direct dependency between the my.foo module and java.base module. Option D doesn’t have such a dependency.
Notice option D shows references from the java.logging and java.xml modules to the base module. This is correct but has nothing to do with the my.foo module.
Unattempted
my.bar is an exported package, hence has nothing to do with the module graph. This means options A and B are incorrect.
All modules depend on the base module, so there must be a direct dependency between the my.foo module and java.base module. Option D doesn’t have such a dependency.
Notice option D shows references from the java.logging and java.xml modules to the base module. This is correct but has nothing to do with the my.foo module.
Question 40 of 65
40. Question
Given:
String string1 = new String(“Java11”);
String string2 = “Java11”;
String string3 = string1.intern();
System.out.println(string1 == string2);
System.out.println(string2 == string3);
What is the output when executing the code fragment?
Correct
The String constructor with a single string argument always creates a new string which is a copy of the argument. On the other hand, a string literal or the intern method returns a string from a constant pool. If the referenced string hasn’t existed, a new string with that value is added to the pool and a reference to it is returned.
Therefore, the string2 and string3 variables reference the same object in the string constant pool, while the string1 variable doesn’t.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10.5
Incorrect
The String constructor with a single string argument always creates a new string which is a copy of the argument. On the other hand, a string literal or the intern method returns a string from a constant pool. If the referenced string hasn’t existed, a new string with that value is added to the pool and a reference to it is returned.
Therefore, the string2 and string3 variables reference the same object in the string constant pool, while the string1 variable doesn’t.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10.5
Unattempted
The String constructor with a single string argument always creates a new string which is a copy of the argument. On the other hand, a string literal or the intern method returns a string from a constant pool. If the referenced string hasn’t existed, a new string with that value is added to the pool and a reference to it is returned.
Therefore, the string2 and string3 variables reference the same object in the string constant pool, while the string1 variable doesn’t.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10.5
Question 41 of 65
41. Question
Given:
try {
throw new FileNotFoundException();
} catch (IOException e) {
throw new RuntimeException(e); // Line 1
} catch (Exception e) { // Line 2
System.out.println(“Test”);
}
What is the output of the given code?
Correct
When a FileNotFoundException is thrown, it’s caught in the first catch block. This block then wraps the original exception in a RuntimeException and throws the new exception up the call stack. This is the final exception that the given code fragment throws.
Notice the second catch block just handles exceptions thrown from within the try block. It doesn’t process exceptions thrown by earlier catch blocks in the exception handling handler.
Incorrect
When a FileNotFoundException is thrown, it’s caught in the first catch block. This block then wraps the original exception in a RuntimeException and throws the new exception up the call stack. This is the final exception that the given code fragment throws.
Notice the second catch block just handles exceptions thrown from within the try block. It doesn’t process exceptions thrown by earlier catch blocks in the exception handling handler.
Unattempted
When a FileNotFoundException is thrown, it’s caught in the first catch block. This block then wraps the original exception in a RuntimeException and throws the new exception up the call stack. This is the final exception that the given code fragment throws.
Notice the second catch block just handles exceptions thrown from within the try block. It doesn’t process exceptions thrown by earlier catch blocks in the exception handling handler.
Question 42 of 65
42. Question
Given:
class Foo {
void methodA() {
// a valid body
}
}
abstract class Bar extends Foo {
abstract void methodB();
}
public class Baz extends Bar {
void methodC() {
// a valid body
}
}
Which three of the following changes when made independently allows the given code to compile?
Correct
The given program fails to compile since the Baz class extends Bar – an abstract class – without overriding its abstract method. Any modification must handle this issue.
Option A turns the Baz class into abstract, hence it no longer needs to override the abstract method in its superclass.
Option C provides the Baz class with a concrete method to override the abstract method in the Bar class.
Option E transforms the abstract method in the Bar class into a concrete one. The fact that Bar is still an abstract class doesn’t matter as long as all of its abstract methods are overridden in concrete subclasses.
Incorrect
The given program fails to compile since the Baz class extends Bar – an abstract class – without overriding its abstract method. Any modification must handle this issue.
Option A turns the Baz class into abstract, hence it no longer needs to override the abstract method in its superclass.
Option C provides the Baz class with a concrete method to override the abstract method in the Bar class.
Option E transforms the abstract method in the Bar class into a concrete one. The fact that Bar is still an abstract class doesn’t matter as long as all of its abstract methods are overridden in concrete subclasses.
Unattempted
The given program fails to compile since the Baz class extends Bar – an abstract class – without overriding its abstract method. Any modification must handle this issue.
Option A turns the Baz class into abstract, hence it no longer needs to override the abstract method in its superclass.
Option C provides the Baz class with a concrete method to override the abstract method in the Bar class.
Option E transforms the abstract method in the Bar class into a concrete one. The fact that Bar is still an abstract class doesn’t matter as long as all of its abstract methods are overridden in concrete subclasses.
public class Bar implements Foo {
String text = “Bar”;
public static void main(String[] args) {
Foo foo = new Bar();
foo.print();
System.out.println(foo.text);
}
}
What is the program’s output?
Correct
Notice a static method of an interface can only be called on the interface itself – it cannot be invoked on any object. This means the statement foo.print() is invalid, leading to a compile-time error.
Had that statement been Foo.print(), option A would have been the correct answer.
Incorrect
Notice a static method of an interface can only be called on the interface itself – it cannot be invoked on any object. This means the statement foo.print() is invalid, leading to a compile-time error.
Had that statement been Foo.print(), option A would have been the correct answer.
Unattempted
Notice a static method of an interface can only be called on the interface itself – it cannot be invoked on any object. This means the statement foo.print() is invalid, leading to a compile-time error.
Had that statement been Foo.print(), option A would have been the correct answer.
Question 44 of 65
44. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.compare(‘A’);
test.compare(‘b’);
}
void compare(char character) {
if (character = ‘A’) { // Line 1
System.out.println(“character is in uppercase”);
} else if (character > ‘a’) { // Line 2
System.out.println(“character is in lowercase”);
} else {
System.out.println(“not sure”);
}
}
}
What is the program’s output?
Correct
The expression character = ‘A’ on line 1 sets the character variable to ‘A’ and returns the character itself. This is a char value while the if expression expects a boolean, resulting in a compile-time error.
Have the if expression on line 1 been character == ‘A’, option A would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Incorrect
The expression character = ‘A’ on line 1 sets the character variable to ‘A’ and returns the character itself. This is a char value while the if expression expects a boolean, resulting in a compile-time error.
Have the if expression on line 1 been character == ‘A’, option A would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Unattempted
The expression character = ‘A’ on line 1 sets the character variable to ‘A’ and returns the character itself. This is a char value while the if expression expects a boolean, resulting in a compile-time error.
Have the if expression on line 1 been character == ‘A’, option A would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Question 45 of 65
45. Question
Given:
String text1 = “Hello”;
String text2 = “Hello World”;
String text3 = “hello world”;
int text1VsText2 = text1.compareTo(text2);
int text2VsText3 = text2.compareTo(text3);
System.out.println(text1VsText2 + ” ” + text2VsText3);
What is the program’s output?
Correct
Unlike the compareTo method in most other classes, which returns either 0, -1 or 1, the compareTo method in the String class returns the difference between the two characters at the first position where they are different. In case one string is a prefix of the other string, their difference in length is returned.
In the given code, the string referenced by text1 is a prefix of that referenced by text2, hence the compareTo method returns their length difference. “Hello” has 5 characters, while “Hello World” has 11, so the comparison result is 5 – 11, which is -6.
The strings referenced by text2 and text3 are different right at the first position. This means the difference between letters “H” and “h” is returned. The Unicode value of an uppercase letter is 32 less than that of its corresponding lowercase letter. As a result, the value of text2VsText3 is -32.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#compareTo(java.lang.String)
Incorrect
Unlike the compareTo method in most other classes, which returns either 0, -1 or 1, the compareTo method in the String class returns the difference between the two characters at the first position where they are different. In case one string is a prefix of the other string, their difference in length is returned.
In the given code, the string referenced by text1 is a prefix of that referenced by text2, hence the compareTo method returns their length difference. “Hello” has 5 characters, while “Hello World” has 11, so the comparison result is 5 – 11, which is -6.
The strings referenced by text2 and text3 are different right at the first position. This means the difference between letters “H” and “h” is returned. The Unicode value of an uppercase letter is 32 less than that of its corresponding lowercase letter. As a result, the value of text2VsText3 is -32.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#compareTo(java.lang.String)
Unattempted
Unlike the compareTo method in most other classes, which returns either 0, -1 or 1, the compareTo method in the String class returns the difference between the two characters at the first position where they are different. In case one string is a prefix of the other string, their difference in length is returned.
In the given code, the string referenced by text1 is a prefix of that referenced by text2, hence the compareTo method returns their length difference. “Hello” has 5 characters, while “Hello World” has 11, so the comparison result is 5 – 11, which is -6.
The strings referenced by text2 and text3 are different right at the first position. This means the difference between letters “H” and “h” is returned. The Unicode value of an uppercase letter is 32 less than that of its corresponding lowercase letter. As a result, the value of text2VsText3 is -32.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#compareTo(java.lang.String)
Question 46 of 65
46. Question
Given:
int[][] matrix1 = new int[][];
int[][] matrix2 = new int[2][];
int[][] matrix3 = new int[][3];
int[2][3] matrix4 = new int[2][3];
Which array declaration is valid?
Correct
When declaring an array with the new operator (and without an array initializer), the size of the first dimension must always be specified. The sizes of other dimensions may be skipped.
Options A and C are invalid as the first dimension’s size is missing. Option D is invalid as well because dimension’s size isn’t allowed to be specify on the left-hand side of the assignment.
Incorrect
When declaring an array with the new operator (and without an array initializer), the size of the first dimension must always be specified. The sizes of other dimensions may be skipped.
Options A and C are invalid as the first dimension’s size is missing. Option D is invalid as well because dimension’s size isn’t allowed to be specify on the left-hand side of the assignment.
Unattempted
When declaring an array with the new operator (and without an array initializer), the size of the first dimension must always be specified. The sizes of other dimensions may be skipped.
Options A and C are invalid as the first dimension’s size is missing. Option D is invalid as well because dimension’s size isn’t allowed to be specify on the left-hand side of the assignment.
Question 47 of 65
47. Question
Given:
class Foo {
String name = “Foo”;
void print() {
this.print(new Bar().name); // Line 1
}
void print() {
this.print(super.name); // Line 2
}
}
public class Test {
public static void main(String[] args) {
Foo foo = new Bar();
foo.print();
}
}
What is the program’s output?
Correct
Despite variable foo has the reference type Foo, it still refers to an instance of the Bar class at runtime. This means the print method that gets executed is the one defined in the Bar class.
The no-argument print method in the Bar class then calls an overloaded method, passing in the value of the name field defined in the superclass. Notice this overloaded method is prefixed with the this keyword, but it is, in fact, inherited from the Foo class.
Since the name field in the Foo class is passed to the one-argument print method, its value – “Foo” – is printed to the console.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html https://docs.oracle.com/javase/tutorial/java/IandI/super.html
Incorrect
Despite variable foo has the reference type Foo, it still refers to an instance of the Bar class at runtime. This means the print method that gets executed is the one defined in the Bar class.
The no-argument print method in the Bar class then calls an overloaded method, passing in the value of the name field defined in the superclass. Notice this overloaded method is prefixed with the this keyword, but it is, in fact, inherited from the Foo class.
Since the name field in the Foo class is passed to the one-argument print method, its value – “Foo” – is printed to the console.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html https://docs.oracle.com/javase/tutorial/java/IandI/super.html
Unattempted
Despite variable foo has the reference type Foo, it still refers to an instance of the Bar class at runtime. This means the print method that gets executed is the one defined in the Bar class.
The no-argument print method in the Bar class then calls an overloaded method, passing in the value of the name field defined in the superclass. Notice this overloaded method is prefixed with the this keyword, but it is, in fact, inherited from the Foo class.
Since the name field in the Foo class is passed to the one-argument print method, its value – “Foo” – is printed to the console.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html https://docs.oracle.com/javase/tutorial/java/IandI/super.html
Question 48 of 65
48. Question
Given:
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
if (test.isPositive(1))
throw new RuntimeException();
System.out.println(“try”);
} catch (Exception e) {
System.out.println(“catch”);
} finally {
System.out.println(“finally”);
}
}
boolean isPositive(int input) {
return input > 0;
}
}
What is the program’s output?
Correct
When an exception is thrown in a try block, all the statements after the throwing is skipped, hence the string “try” isn’t printed.
The type of the exception object is RuntimeException, a subclass of Exception, hence it’s caught and handled by the catch block. After that, the runtime exception executes the finally block.
Incorrect
When an exception is thrown in a try block, all the statements after the throwing is skipped, hence the string “try” isn’t printed.
The type of the exception object is RuntimeException, a subclass of Exception, hence it’s caught and handled by the catch block. After that, the runtime exception executes the finally block.
Unattempted
When an exception is thrown in a try block, all the statements after the throwing is skipped, hence the string “try” isn’t printed.
The type of the exception object is RuntimeException, a subclass of Exception, hence it’s caught and handled by the catch block. After that, the runtime exception executes the finally block.
Question 49 of 65
49. Question
Given:
StringBuilder builder = new StringBuilder(“ABC”);
builder.reverse().setCharAt(0, “D”);
System.out.println(builder);
What is the program’s output?
interface Bar extends Foo {
@Override // Line 1
void methodA();
@Override // Line 2
void methodC();
}
class Baz implements Bar {
@Override // Line 3
public void methodA() {
// a valid body
}
@Override // Line 4
public void methodB() {
// a valid body
}
@Override // Line 5
public void methodC() {
// a valid body
}
}
Which lines of code cause compilation failure?
Correct
The Bar interface extends Foo, but this super-interface doesn’t have any method named methodC, hence a compile-time error on line 2.
All the other @Override annotations are valid as a decorated method always overrides one in its supertype.
Incorrect
The Bar interface extends Foo, but this super-interface doesn’t have any method named methodC, hence a compile-time error on line 2.
All the other @Override annotations are valid as a decorated method always overrides one in its supertype.
Unattempted
The Bar interface extends Foo, but this super-interface doesn’t have any method named methodC, hence a compile-time error on line 2.
All the other @Override annotations are valid as a decorated method always overrides one in its supertype.
Question 51 of 65
51. 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++;
System.out.print(number + " ");
}
}
}
What is the program's output?
Correct
Let’s go over iterations of the while construct:
Iteration 1:
Variable number is increased from 0 to 1, then compared to 5
Since 1 < 5, the body of the while construct is executed, increasing number to 2 and printing it out
Iteration 2:
Variable number is increased from 2 to 3, then compared to 5
Since 3 < 5, the body of the while construct is executed, increasing number to 4 and printing it out
Iteration 3:
Variable number is increased from 4 to 5, then compared to 5
Since 5 isn't less than 5, the condition expression evaluates to false, and the while construct exits
So, the System.out.print statement is called twice to print numbers 2 and 4.
Incorrect
Let’s go over iterations of the while construct:
Iteration 1:
Variable number is increased from 0 to 1, then compared to 5
Since 1 < 5, the body of the while construct is executed, increasing number to 2 and printing it out
Iteration 2:
Variable number is increased from 2 to 3, then compared to 5
Since 3 < 5, the body of the while construct is executed, increasing number to 4 and printing it out
Iteration 3:
Variable number is increased from 4 to 5, then compared to 5
Since 5 isn't less than 5, the condition expression evaluates to false, and the while construct exits
So, the System.out.print statement is called twice to print numbers 2 and 4.
Unattempted
Let’s go over iterations of the while construct:
Iteration 1:
Variable number is increased from 0 to 1, then compared to 5
Since 1 < 5, the body of the while construct is executed, increasing number to 2 and printing it out
Iteration 2:
Variable number is increased from 2 to 3, then compared to 5
Since 3 < 5, the body of the while construct is executed, increasing number to 4 and printing it out
Iteration 3:
Variable number is increased from 4 to 5, then compared to 5
Since 5 isn't less than 5, the condition expression evaluates to false, and the while construct exits
So, the System.out.print statement is called twice to print numbers 2 and 4.
Question 52 of 65
52. Question
Which command lists all the modules required by a target module?
Correct
The java –list-modules command lists all the observable on the whole system, not dependencies of a module.
The jdeps — list-deps command lists the module dependencies and also the package names of JDK internal APIs (if referenced).
Notice the three commands java, javac and jdeps are important for this exam.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html#GUID-A543FEBE-908A-49BF-996C-39499367ADB4
Incorrect
The java –list-modules command lists all the observable on the whole system, not dependencies of a module.
The jdeps — list-deps command lists the module dependencies and also the package names of JDK internal APIs (if referenced).
Notice the three commands java, javac and jdeps are important for this exam.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html#GUID-A543FEBE-908A-49BF-996C-39499367ADB4
Unattempted
The java –list-modules command lists all the observable on the whole system, not dependencies of a module.
The jdeps — list-deps command lists the module dependencies and also the package names of JDK internal APIs (if referenced).
Notice the three commands java, javac and jdeps are important for this exam.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html#GUID-A543FEBE-908A-49BF-996C-39499367ADB4
Question 53 of 65
53. Question
Given:
class Foo {
List getList(List input) { return new ArrayList(input); } // Method A
}
public class Bar extends Foo {
List getList() { return new ArrayList();} // Method B
Collection getList(Collection input) {return new ArrayList();} // Method C
ArrayList getList(ArrayList input) { return new ArrayList();} // Method D
Collection getList(List input) {return new ArrayList();} // Method E
}
Which of the following statement is correct?
Correct
For a method in a subclass to override a method in a superclass, their parameters must be the same. In the Bar class, methods B, C and D have a different parameter type from method A, meaning neither of them overrides method A.
Method E has the same parameter type as method A. However, its return type isn’t the same or a subtype of method A’s return type. As a result, method E doesn’t override method A. In fact, this method doesn’t even compile.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Incorrect
For a method in a subclass to override a method in a superclass, their parameters must be the same. In the Bar class, methods B, C and D have a different parameter type from method A, meaning neither of them overrides method A.
Method E has the same parameter type as method A. However, its return type isn’t the same or a subtype of method A’s return type. As a result, method E doesn’t override method A. In fact, this method doesn’t even compile.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Unattempted
For a method in a subclass to override a method in a superclass, their parameters must be the same. In the Bar class, methods B, C and D have a different parameter type from method A, meaning neither of them overrides method A.
Method E has the same parameter type as method A. However, its return type isn’t the same or a subtype of method A’s return type. As a result, method E doesn’t override method A. In fact, this method doesn’t even compile.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
Question 54 of 65
54. Question
Given the Foo.java file:
package test;
public class Foo {
String text;
public Foo(String text) {
this.text = text;
}
public String toString() {
return text;
}
}
And Bar.java file:
package test;
import java.util.*;
public class Bar {
public static void main(String[] args) {
Foo foo1 = new Foo(“Hi”);
Foo foo2 = new Foo(“Hey”);
Foo[] foos = {foo1, foo2};
System.out.println(Arrays.toString(foos));
}
}
Which of the following statements is correct about the given code?
Correct
Even an asterisk is used in the import statement to indicate all types in the java.util package, only the referenced types (the Arrays class in this case) are loaded when the program runs.
For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java.lang package and (2) the current package (the package for the current file). Both the String and System classes belong to the java.lang package, while the Foo class is in the same package as Bar, hence no other import statements are needed.
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Incorrect
Even an asterisk is used in the import statement to indicate all types in the java.util package, only the referenced types (the Arrays class in this case) are loaded when the program runs.
For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java.lang package and (2) the current package (the package for the current file). Both the String and System classes belong to the java.lang package, while the Foo class is in the same package as Bar, hence no other import statements are needed.
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Unattempted
Even an asterisk is used in the import statement to indicate all types in the java.util package, only the referenced types (the Arrays class in this case) are loaded when the program runs.
For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java.lang package and (2) the current package (the package for the current file). Both the String and System classes belong to the java.lang package, while the Foo class is in the same package as Bar, hence no other import statements are needed.
Reference: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Question 55 of 65
55. Question
Given:
String string = String.format(“Welcome to [placeholder] century”, “st”, 21);
System.out.println(string);
Which string when replacing [placeholder] produces “Welcome to 21st century” on the console?
Correct
Many format arguments can be provided to the format method, and they are often in the same order as format specifiers enclosed in the format string. However, we can change these arguments’ positions, provided the positions are indicated in the format specifiers by argument indices, prefixed with the percent % character. For example, %1 denotes the first argument, %2 does the second, and so on.
Normally a decimal integer is indicated by letter “d”, but there’s nothing wrong if we want to use it as a string – represented by letter “s”. Therefore, option C is the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#syntax
Incorrect
Many format arguments can be provided to the format method, and they are often in the same order as format specifiers enclosed in the format string. However, we can change these arguments’ positions, provided the positions are indicated in the format specifiers by argument indices, prefixed with the percent % character. For example, %1 denotes the first argument, %2 does the second, and so on.
Normally a decimal integer is indicated by letter “d”, but there’s nothing wrong if we want to use it as a string – represented by letter “s”. Therefore, option C is the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#syntax
Unattempted
Many format arguments can be provided to the format method, and they are often in the same order as format specifiers enclosed in the format string. However, we can change these arguments’ positions, provided the positions are indicated in the format specifiers by argument indices, prefixed with the percent % character. For example, %1 denotes the first argument, %2 does the second, and so on.
Normally a decimal integer is indicated by letter “d”, but there’s nothing wrong if we want to use it as a string – represented by letter “s”. Therefore, option C is the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#syntax
Question 56 of 65
56. Question
Given:
List list = List.of(); // Line 1
for (Object element : list) { // Line 2
System.out.println(element);
}
What is the output of the given code?
public class Test implements Foo, Bar { // Line 1
@Override // Line 2
public void myMethod() {
System.out.println(myField); // Line 3
}
public static void main(String[] args) {
Test test = new Test();
test.myMethod(); // Line 4
}
}
What is the program’s output?
Correct
The myField referenced from within the Test class is ambiguous as both the interfaces Foo and Bar have a field with that name, resulting in a compile-time error. If we want to refer to a field in a particular interface, we can prefix it with the interface’s name, such as Foo.myField or Bar.myField.
Here are explanations on other options:
A class can implements multiple interfaces, hence line 1 is valid – the order of interfaces in the class’s declaration doesn’t matter
myMethod in the Test class override both methods of the same name in the Foo and Bar interfaces – there’s nothing wrong over here
The invocation of myMethod in the main class is just a call to the method defined in the Test class
Incorrect
The myField referenced from within the Test class is ambiguous as both the interfaces Foo and Bar have a field with that name, resulting in a compile-time error. If we want to refer to a field in a particular interface, we can prefix it with the interface’s name, such as Foo.myField or Bar.myField.
Here are explanations on other options:
A class can implements multiple interfaces, hence line 1 is valid – the order of interfaces in the class’s declaration doesn’t matter
myMethod in the Test class override both methods of the same name in the Foo and Bar interfaces – there’s nothing wrong over here
The invocation of myMethod in the main class is just a call to the method defined in the Test class
Unattempted
The myField referenced from within the Test class is ambiguous as both the interfaces Foo and Bar have a field with that name, resulting in a compile-time error. If we want to refer to a field in a particular interface, we can prefix it with the interface’s name, such as Foo.myField or Bar.myField.
Here are explanations on other options:
A class can implements multiple interfaces, hence line 1 is valid – the order of interfaces in the class’s declaration doesn’t matter
myMethod in the Test class override both methods of the same name in the Foo and Bar interfaces – there’s nothing wrong over here
The invocation of myMethod in the main class is just a call to the method defined in the Test class
Question 58 of 65
58. Question
Given:
public class Test {
int add(int… addends) {
System.out.println(“Variable arity”);
int sum = 0;
for (int addend : addends) {
sum += addend;
}
return sum;
}
Number add(Number addend1, Number addend2) {
System.out.println(“Object arguments”);
return (int) addend1 + (int) addend2;
}
long add(long addend1, long addend2) {
System.out.println(“Primitive arguments”);
return addend1 + addend2;
}
public static void main(String[] args) {
Test test = new Test();
Number sum = test.add(Integer.valueOf(“1”), Integer.valueOf(“2”));
}
}
What is the program output?
Correct
As per section 15.12.2 of the Java Language Specification, the process of determining applicability begins by determining the potentially applicable methods. Then, to ensure compatibility with the Java programming language prior to Java SE 5.0, the process continues in three phases:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
The second method doesn’t require boxing or unboxing, and it doesn’t have variable arity either. Therefore, this method is picked up in the first step, and option B is correct.
Just to make it clear, the third method is the next choice as it would be picked up in the second step, while the first method would only be chosen in the third step.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Incorrect
As per section 15.12.2 of the Java Language Specification, the process of determining applicability begins by determining the potentially applicable methods. Then, to ensure compatibility with the Java programming language prior to Java SE 5.0, the process continues in three phases:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
The second method doesn’t require boxing or unboxing, and it doesn’t have variable arity either. Therefore, this method is picked up in the first step, and option B is correct.
Just to make it clear, the third method is the next choice as it would be picked up in the second step, while the first method would only be chosen in the third step.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Unattempted
As per section 15.12.2 of the Java Language Specification, the process of determining applicability begins by determining the potentially applicable methods. Then, to ensure compatibility with the Java programming language prior to Java SE 5.0, the process continues in three phases:
The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the second phase.
The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase, then processing continues to the third phase.
The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
The second method doesn’t require boxing or unboxing, and it doesn’t have variable arity either. Therefore, this method is picked up in the first step, and option B is correct.
Just to make it clear, the third method is the next choice as it would be picked up in the second step, while the first method would only be chosen in the third step.
Reference: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2
Question 59 of 65
59. Question
Given:
String text = “abcd”;
text.substring(1, 3);
text.subSequence(2, 0);
System.out.println(text);
What is the output?
int result = Arrays.mismatch(array1, 1, 3, array2, 2, 3);
System.out.println(result);
What is the output when executing the given code?
Correct
As per the JDK API Specification, the Arrays#mismatch method finds and returns the index of the first mismatch between two Object arrays over the specified range, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array.
If the two arrays share a common prefix, then the returned index is the length of the common prefix and it follows that there is a mismatch between the two elements at that index within the respective arrays. If one array is a proper prefix of the other, then the returned index is the length of the smaller array and it follows that the index is only valid for the larger array. Otherwise, there is no mismatch.
In the given code, the first array for comparison is {“b”, “c”} and the second is {“c”}. These arrays are different right from the first element, resulting in the value of 0.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#mismatch(java.lang.Object%5B%5D,int,int,java.lang.Object%5B%5D,int,int)
Incorrect
As per the JDK API Specification, the Arrays#mismatch method finds and returns the index of the first mismatch between two Object arrays over the specified range, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array.
If the two arrays share a common prefix, then the returned index is the length of the common prefix and it follows that there is a mismatch between the two elements at that index within the respective arrays. If one array is a proper prefix of the other, then the returned index is the length of the smaller array and it follows that the index is only valid for the larger array. Otherwise, there is no mismatch.
In the given code, the first array for comparison is {“b”, “c”} and the second is {“c”}. These arrays are different right from the first element, resulting in the value of 0.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#mismatch(java.lang.Object%5B%5D,int,int,java.lang.Object%5B%5D,int,int)
Unattempted
As per the JDK API Specification, the Arrays#mismatch method finds and returns the index of the first mismatch between two Object arrays over the specified range, otherwise return -1 if no mismatch is found. The index will be in the range of 0 (inclusive) up to the length (inclusive) of the smaller array.
If the two arrays share a common prefix, then the returned index is the length of the common prefix and it follows that there is a mismatch between the two elements at that index within the respective arrays. If one array is a proper prefix of the other, then the returned index is the length of the smaller array and it follows that the index is only valid for the larger array. Otherwise, there is no mismatch.
In the given code, the first array for comparison is {“b”, “c”} and the second is {“c”}. These arrays are different right from the first element, resulting in the value of 0.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#mismatch(java.lang.Object%5B%5D,int,int,java.lang.Object%5B%5D,int,int)
public static void main(String[] args) {
Foo foo = new Bar();
foo.print();
Bar bar = new Bar();
bar.print();
}
}
What is the given program’s output?
Correct
When method overriding happens, the method that gets called is determined by the type of the object at runtime. On the other hand, when method hiding occurs, the method that is invoked is determined by the reference type of the variable that we use to make the call.
In the given program, print is a static method. The actual implementation that is executed at runtime is determined by the reference types of variables foo and bar, which are Foo and Bar, respectively.
Incorrect
When method overriding happens, the method that gets called is determined by the type of the object at runtime. On the other hand, when method hiding occurs, the method that is invoked is determined by the reference type of the variable that we use to make the call.
In the given program, print is a static method. The actual implementation that is executed at runtime is determined by the reference types of variables foo and bar, which are Foo and Bar, respectively.
Unattempted
When method overriding happens, the method that gets called is determined by the type of the object at runtime. On the other hand, when method hiding occurs, the method that is invoked is determined by the reference type of the variable that we use to make the call.
In the given program, print is a static method. The actual implementation that is executed at runtime is determined by the reference types of variables foo and bar, which are Foo and Bar, respectively.
Question 62 of 65
62. Question
Which two statements correctly create a LocalDate instance representing 01 January 2019?
Correct
The LocalDate class has a constructor but it isn’t part of the public API, hence inaccessible to our code. When it comes to creating a new LocalDate instance, we must use a static factory method or modify an existing instance.
The date representation in option B is malformed. When no DateTimeFormatter is provided, the parse method uses ISO_LOCAL_DATE as the default. Just like any other ISO formatter, this formatter requires a single digit number representing day of month or month of year to be prefixed with 0. The statement compiles but will throw DateTimeParseException at runtime.
The second argument passed to the of method in option D is of a wrong type. It should be a constant of the Month enum type instead of a string, such as Month.JANURARY.
Option E is correct as it returns the first day of year 2019.
Incorrect
The LocalDate class has a constructor but it isn’t part of the public API, hence inaccessible to our code. When it comes to creating a new LocalDate instance, we must use a static factory method or modify an existing instance.
The date representation in option B is malformed. When no DateTimeFormatter is provided, the parse method uses ISO_LOCAL_DATE as the default. Just like any other ISO formatter, this formatter requires a single digit number representing day of month or month of year to be prefixed with 0. The statement compiles but will throw DateTimeParseException at runtime.
The second argument passed to the of method in option D is of a wrong type. It should be a constant of the Month enum type instead of a string, such as Month.JANURARY.
Option E is correct as it returns the first day of year 2019.
Unattempted
The LocalDate class has a constructor but it isn’t part of the public API, hence inaccessible to our code. When it comes to creating a new LocalDate instance, we must use a static factory method or modify an existing instance.
The date representation in option B is malformed. When no DateTimeFormatter is provided, the parse method uses ISO_LOCAL_DATE as the default. Just like any other ISO formatter, this formatter requires a single digit number representing day of month or month of year to be prefixed with 0. The statement compiles but will throw DateTimeParseException at runtime.
The second argument passed to the of method in option D is of a wrong type. It should be a constant of the Month enum type instead of a string, such as Month.JANURARY.
Option E is correct as it returns the first day of year 2019.
Question 63 of 65
63. Question
Which two of the following are main goals of the Java module system?
Correct
As described in the JSR, the specific goals of the module system are to provide
Reliable configuration, to replace the brittle, error-prone class-path mechanism with a means for program components to declare explicit dependences upon one another, along with
Strong encapsulation, to allow a component to declare which of its public types are accessible to other components, and which are not.
These features will benefit application developers, library developers, and implementors of the Java SE Platform itself directly and, also, indirectly, since they will enable a scalable platform, greater platform integrity, and improved performance.
Reference: http://openjdk.java.net/projects/jigsaw/spec/sotms/
Incorrect
As described in the JSR, the specific goals of the module system are to provide
Reliable configuration, to replace the brittle, error-prone class-path mechanism with a means for program components to declare explicit dependences upon one another, along with
Strong encapsulation, to allow a component to declare which of its public types are accessible to other components, and which are not.
These features will benefit application developers, library developers, and implementors of the Java SE Platform itself directly and, also, indirectly, since they will enable a scalable platform, greater platform integrity, and improved performance.
Reference: http://openjdk.java.net/projects/jigsaw/spec/sotms/
Unattempted
As described in the JSR, the specific goals of the module system are to provide
Reliable configuration, to replace the brittle, error-prone class-path mechanism with a means for program components to declare explicit dependences upon one another, along with
Strong encapsulation, to allow a component to declare which of its public types are accessible to other components, and which are not.
These features will benefit application developers, library developers, and implementors of the Java SE Platform itself directly and, also, indirectly, since they will enable a scalable platform, greater platform integrity, and improved performance.
Reference: http://openjdk.java.net/projects/jigsaw/spec/sotms/
Question 64 of 65
64. Question
Given:
List list = new ArrayList<>(1);
list.add(2);
list.add(3);
System.out.println(list);
What is the output?
Correct
The ArrayList constructor with an int parameter creates an empty list with the specified initial capacity. It doesn’t insert any element to the list. Notice the capacity grows automatically when elements are added.
The add method with a single parameter appends the specified element to the end of the list. This means number 2 is appended first, then number 3. As a result, the list will contain these two numbers in their order they’re added.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html
Incorrect
The ArrayList constructor with an int parameter creates an empty list with the specified initial capacity. It doesn’t insert any element to the list. Notice the capacity grows automatically when elements are added.
The add method with a single parameter appends the specified element to the end of the list. This means number 2 is appended first, then number 3. As a result, the list will contain these two numbers in their order they’re added.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html
Unattempted
The ArrayList constructor with an int parameter creates an empty list with the specified initial capacity. It doesn’t insert any element to the list. Notice the capacity grows automatically when elements are added.
The add method with a single parameter appends the specified element to the end of the list. This means number 2 is appended first, then number 3. As a result, the list will contain these two numbers in their order they’re added.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html
Question 65 of 65
65. Question
Given:
int i, j;
for (i = 3, j = 1; i + j < 7; i + 1, j + 2) {
if (i == j) {
break;
}
}
System.out.println(i + " " + j);
What is the output of the given code fragment?
Correct
The increment expression in the for loop is invalid. It must be composed of valid Java statements separated by commas (,). Therefore, the compilation fails.
Had the increment expression been i = i + 1, j = j + 2, option B would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Incorrect
The increment expression in the for loop is invalid. It must be composed of valid Java statements separated by commas (,). Therefore, the compilation fails.
Had the increment expression been i = i + 1, j = j + 2, option B would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Unattempted
The increment expression in the for loop is invalid. It must be composed of valid Java statements separated by commas (,). Therefore, the compilation fails.
Had the increment expression been i = i + 1, j = j + 2, option B would have been the correct answer.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
X
Use Page numbers below to navigate to other practice tests