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 11 "
0 of 65 questions answered correctly
Your time:
Time has elapsed
Your Final Score is : 0
You have attempted : 0
Number of Correct Questions : 0 and scored 0
Number of Incorrect Questions : 0 and Negative marks 0
Average score
Your score
OCP Java SE 11 Programmer I 1Z0-815
You have attempted: 0
Number of Correct Questions: 0 and scored 0
Number of Incorrect Questions: 0 and Negative marks 0
You can review your answers by clicking view questions. Important Note : Open Reference Documentation Links in New Tab (Right Click and Open in New Tab).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Answered
Review
Question 1 of 65
1. Question
Given:
public class Test {
int i1;
Integer i2;
public static void main(String[] args) {
Test test = new Test();
int sum = 0;
try {
sum = test.i1++ + test.i2++;
} catch (Exception e) { }
System.out.println(test.i1 + ” ” + test.i2);
}
}
What it the program’s output?
Correct
In the given class, the i1 and i2 fields aren’t explicitly initialized, implying the compiler will set them to the default value of their class. Therefore, when the Test object is constructed, variable i1 is set to 0 and i2 is to set to null.
Let’s take a look at the body of the try block:
sum = test.i1++ + test.i2++;
The expression test.i2 evaluates to null. When an increment operation is made on a null object, a NullPointerException is thrown. However, before this exception is thrown, test.i1 has already been increased.
As the result, the final value of test.i1 is 1, and that of test.i2 is null.
Incorrect
In the given class, the i1 and i2 fields aren’t explicitly initialized, implying the compiler will set them to the default value of their class. Therefore, when the Test object is constructed, variable i1 is set to 0 and i2 is to set to null.
Let’s take a look at the body of the try block:
sum = test.i1++ + test.i2++;
The expression test.i2 evaluates to null. When an increment operation is made on a null object, a NullPointerException is thrown. However, before this exception is thrown, test.i1 has already been increased.
As the result, the final value of test.i1 is 1, and that of test.i2 is null.
Unattempted
In the given class, the i1 and i2 fields aren’t explicitly initialized, implying the compiler will set them to the default value of their class. Therefore, when the Test object is constructed, variable i1 is set to 0 and i2 is to set to null.
Let’s take a look at the body of the try block:
sum = test.i1++ + test.i2++;
The expression test.i2 evaluates to null. When an increment operation is made on a null object, a NullPointerException is thrown. However, before this exception is thrown, test.i1 has already been increased.
As the result, the final value of test.i1 is 1, and that of test.i2 is null.
Question 2 of 65
2. Question
Given:
public class Person {
String fullName;
public Person(String… nameParts) {
if (nameParts == null) throw new StringIndexOutOfBoundsException();
if (nameParts.length > 2) throw new ArrayIndexOutOfBoundsException();
if (nameParts.length == 2) fullName = nameParts[0] + nameParts[1];
else fullName = nameParts[0];
}
}
And:
public class Test {
static public void main(String[] args) {
Person person = new Person(null, null);
System.out.println(person.fullName);
}
}
What is the program’s output?
Correct
When two null arguments are used to call the Person constructor, they’re considered an array with two null elements. When two strings of the null value are concatenated, they just form the nullnull string.
Incorrect
When two null arguments are used to call the Person constructor, they’re considered an array with two null elements. When two strings of the null value are concatenated, they just form the nullnull string.
Unattempted
When two null arguments are used to call the Person constructor, they’re considered an array with two null elements. When two strings of the null value are concatenated, they just form the nullnull string.
Question 3 of 65
3. Question
Given:
class Person {
String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class Test {
static List filter(List input, Predicate predicate) {
var output = new ArrayList();
for (Person person : input) {
if (predicate.test(person))
output.add(person);
return output;
}
return output;
}
public static void main(String[] args) {
var john = new Person(“John”);
var jane = new Person(“Jane”);
var mark = new Person(“Mark”);
var input = List.of(john, jane, mark);
var output = filter(input, p -> p.name.startsWith(“J”));
System.out.println(output);
}
}
What is the given program’s output?
Correct
The Predicate passed to the filter method returns true if the name of a given Person starts with “J”, and false otherwise. Among all elements of the input list, the elements referenced by variables john and jane satisfy that condition, meaning they make the expression predicate.test(person) in the filter method evaluate to true. However, this method returns right away after the first matched Person object is found. Consequently, only the person with name “John” is added to the output.
Incorrect
The Predicate passed to the filter method returns true if the name of a given Person starts with “J”, and false otherwise. Among all elements of the input list, the elements referenced by variables john and jane satisfy that condition, meaning they make the expression predicate.test(person) in the filter method evaluate to true. However, this method returns right away after the first matched Person object is found. Consequently, only the person with name “John” is added to the output.
Unattempted
The Predicate passed to the filter method returns true if the name of a given Person starts with “J”, and false otherwise. Among all elements of the input list, the elements referenced by variables john and jane satisfy that condition, meaning they make the expression predicate.test(person) in the filter method evaluate to true. However, this method returns right away after the first matched Person object is found. Consequently, only the person with name “John” is added to the output.
Question 4 of 65
4. Question
Given:
public class Test {
public static void main(String[] args) {
int x, y = 2, z = 4;
try {
x = z % y;
y /= x;
z *= y;
} catch (RuntimeException e) {
x = y / z;
z += y;
}
System.out.println(x + ” ” + y + ” ” + z);
}
}
What is the program’s output?
Correct
In the given code, the x variable is initialized to 0 by the expression z % y. This value causes an ArithmethicException when the next expression, y /=x, is executed. Since an exception is thrown, the last statement in the try block is ignored. At this point, variables y and z keep their original values.
Notice ArithmeticException is a subtype of RuntimeException, meaning the thrown exception is caught by the catch block. Inside this block, variable x is set to 0 and z is updated to 6. Meanwhile, the value of variable y is unchanged.
Incorrect
In the given code, the x variable is initialized to 0 by the expression z % y. This value causes an ArithmethicException when the next expression, y /=x, is executed. Since an exception is thrown, the last statement in the try block is ignored. At this point, variables y and z keep their original values.
Notice ArithmeticException is a subtype of RuntimeException, meaning the thrown exception is caught by the catch block. Inside this block, variable x is set to 0 and z is updated to 6. Meanwhile, the value of variable y is unchanged.
Unattempted
In the given code, the x variable is initialized to 0 by the expression z % y. This value causes an ArithmethicException when the next expression, y /=x, is executed. Since an exception is thrown, the last statement in the try block is ignored. At this point, variables y and z keep their original values.
Notice ArithmeticException is a subtype of RuntimeException, meaning the thrown exception is caught by the catch block. Inside this block, variable x is set to 0 and z is updated to 6. Meanwhile, the value of variable y is unchanged.
Question 5 of 65
5. Question
Which statement is correct about a module declaration?
Correct
Option A is incorrect as a module declaration must always be named module-info.java.
Option B is incorrect as a module declaration doesn’t belong to any package – it’s an integral part of the module itself.
Option D is incorrect as a module declaration must have at least the module keyword, a module name and a pair of curly brackets.
Incorrect
Option A is incorrect as a module declaration must always be named module-info.java.
Option B is incorrect as a module declaration doesn’t belong to any package – it’s an integral part of the module itself.
Option D is incorrect as a module declaration must have at least the module keyword, a module name and a pair of curly brackets.
Unattempted
Option A is incorrect as a module declaration must always be named module-info.java.
Option B is incorrect as a module declaration doesn’t belong to any package – it’s an integral part of the module itself.
Option D is incorrect as a module declaration must have at least the module keyword, a module name and a pair of curly brackets.
Question 6 of 65
6. Question
Given:
class Foo {
String string = “Foo”;
void print() {
System.out.println(string);
}
}
class Bar extends Foo {
static String string = “Bar”;
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
In the given program, the Bar class extends the Foo class. However, the print method in the Bar class is static while the method with the same signature in the Foo class is non-static. A static method cannot hide or override a non-static one, hence a compile-time error.
Incorrect
In the given program, the Bar class extends the Foo class. However, the print method in the Bar class is static while the method with the same signature in the Foo class is non-static. A static method cannot hide or override a non-static one, hence a compile-time error.
Unattempted
In the given program, the Bar class extends the Foo class. However, the print method in the Bar class is static while the method with the same signature in the Foo class is non-static. A static method cannot hide or override a non-static one, hence a compile-time error.
public class Test {
public static void main(String[] args) {
test.StringBuilder builder1 = new test.StringBuilder(“test”); // Line 3
java.lang.StringBuilder builder2 = new java.lang.StringBuilder(“test”);
System.out.println(builder1.equals(builder2));
}
}
What is the given program’s output?
Correct
There’s nothing wrong when importing a class from another package, meaning line 1 is valid.
When the compiler reaches line 2, a class with the simple name StringBuilder already exists in the compilation unit due to the import on line 1. The declaration on line 2 therefore leads to a class name conflict, which in turn causes a compile-time error.
Had line 1 been removed, option B would have been the correct answer as there’s no more class conflict.
Incorrect
There’s nothing wrong when importing a class from another package, meaning line 1 is valid.
When the compiler reaches line 2, a class with the simple name StringBuilder already exists in the compilation unit due to the import on line 1. The declaration on line 2 therefore leads to a class name conflict, which in turn causes a compile-time error.
Had line 1 been removed, option B would have been the correct answer as there’s no more class conflict.
Unattempted
There’s nothing wrong when importing a class from another package, meaning line 1 is valid.
When the compiler reaches line 2, a class with the simple name StringBuilder already exists in the compilation unit due to the import on line 1. The declaration on line 2 therefore leads to a class name conflict, which in turn causes a compile-time error.
Had line 1 been removed, option B would have been the correct answer as there’s no more class conflict.
Question 8 of 65
8. Question
Given:
int i = 0;
for (; i < 1; i = i) {
System.out.println("Inside");
}
System.out.println("Outside");
What happens when compiling and executing the given code fragment?
Correct
After the body of the for statement is reached, the “Inside” string is printed to the console. The increment expression does nothing but to assign the i variable to itself, meaning the condition expression always evaluates to true. As a result, that string is printed repeatedly forever.
Incorrect
After the body of the for statement is reached, the “Inside” string is printed to the console. The increment expression does nothing but to assign the i variable to itself, meaning the condition expression always evaluates to true. As a result, that string is printed repeatedly forever.
Unattempted
After the body of the for statement is reached, the “Inside” string is printed to the console. The increment expression does nothing but to assign the i variable to itself, meaning the condition expression always evaluates to true. As a result, that string is printed repeatedly forever.
Question 9 of 65
9. Question
Given:
int i1 = 1000;
int i2 = 1_000; // Line 1
int i3 = 1,000; // Line 2
System.out.println(i1 == i2);
System.out.println(i1 == i3);
What is the output of the given code fragment?
Correct
In Java, digits in a numeric literal can be grouped using the underscore character, not the comma. Consequently, the compiler fails on line 2.
Incorrect
In Java, digits in a numeric literal can be grouped using the underscore character, not the comma. Consequently, the compiler fails on line 2.
Unattempted
In Java, digits in a numeric literal can be grouped using the underscore character, not the comma. Consequently, the compiler fails on line 2.
Although the reference type of the foo variable is Foo, the actual object it refers to at runtime is a Bar. When myMethod, an instance method, is called on this object, the method defined in the subclass Bar overrides the method with the same signature in the superclass Foo. This overriding method is the one that gets called, hence the second string on the output is “Bar”.
Unlike methods, fields are never overridden. A field of an object is always associated with the reference type of the variable referring to the object. In the given code, the foo variable points to an object of type Bar, but its reference type is Foo. Therefore, foo.myField refers to the superclass’s field, and the first string in the output is “Foo”.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
Incorrect
Although the reference type of the foo variable is Foo, the actual object it refers to at runtime is a Bar. When myMethod, an instance method, is called on this object, the method defined in the subclass Bar overrides the method with the same signature in the superclass Foo. This overriding method is the one that gets called, hence the second string on the output is “Bar”.
Unlike methods, fields are never overridden. A field of an object is always associated with the reference type of the variable referring to the object. In the given code, the foo variable points to an object of type Bar, but its reference type is Foo. Therefore, foo.myField refers to the superclass’s field, and the first string in the output is “Foo”.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
Unattempted
Although the reference type of the foo variable is Foo, the actual object it refers to at runtime is a Bar. When myMethod, an instance method, is called on this object, the method defined in the subclass Bar overrides the method with the same signature in the superclass Foo. This overriding method is the one that gets called, hence the second string on the output is “Bar”.
Unlike methods, fields are never overridden. A field of an object is always associated with the reference type of the variable referring to the object. In the given code, the foo variable points to an object of type Bar, but its reference type is Foo. Therefore, foo.myField refers to the superclass’s field, and the first string in the output is “Foo”.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/override.html https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
Question 12 of 65
12. Question
Given a method:
void switchString(String arg) {
switch (arg) {
case “A” | “B”:
System.out.println(“Hi”);
default:
System.out.println(“Hello”);
}
}
What is printed to the console if the given method is called with argument “a”?
Correct
The syntax combining cases in the given code is invalid. If we want to associate multiple cases with the same code block, we should do like this:
switch (arg) {
The syntax combining cases in the given code is invalid. If we want to associate multiple cases with the same code block, we should do like this:
switch (arg) {
The syntax combining cases in the given code is invalid. If we want to associate multiple cases with the same code block, we should do like this:
switch (arg) {
On line 1, variables i, j and k are all declared, but only j is initialized. On line 2, variable k is initialized using the values of variables i and j. However, at this point, variable i hasn’t been initialized. Therefore, the compilation fails on line 2.
Incorrect
On line 1, variables i, j and k are all declared, but only j is initialized. On line 2, variable k is initialized using the values of variables i and j. However, at this point, variable i hasn’t been initialized. Therefore, the compilation fails on line 2.
Unattempted
On line 1, variables i, j and k are all declared, but only j is initialized. On line 2, variable k is initialized using the values of variables i and j. However, at this point, variable i hasn’t been initialized. Therefore, the compilation fails on line 2.
Question 14 of 65
14. Question
Given three module declarations:
module test {
requires foo;
}
And:
module foo {
requires bar;
exports my.foo;
}
And:
module bar {
exports bar;
}
Which graph describes the given modules’ dependencies:
Correct
The test module depends on the foo module, which in turn depends on bar. There are no transitive dependencies, hence the test module doesn’t depend on the bar module.
In addition to explicit dependencies, all modules depend on the base module.
Notice the exports directive specify packages – it has nothing to do with the module graph.
Incorrect
The test module depends on the foo module, which in turn depends on bar. There are no transitive dependencies, hence the test module doesn’t depend on the bar module.
In addition to explicit dependencies, all modules depend on the base module.
Notice the exports directive specify packages – it has nothing to do with the module graph.
Unattempted
The test module depends on the foo module, which in turn depends on bar. There are no transitive dependencies, hence the test module doesn’t depend on the bar module.
In addition to explicit dependencies, all modules depend on the base module.
Notice the exports directive specify packages – it has nothing to do with the module graph.
Question 15 of 65
15. Question
Given:
interface Foo {
String myField; // Line 1
String myMethod(); // Line 2
}
public abstract class Bar implements Foo { // Line 3
abstract void myMethod(String arg); // Line 4
}
Which line fails to compile?
Correct
When a field is declared in an interface, it’s by default public, static and final. The myField field in the Foo interface is final, but it’s not set to any value. This uninitialized state leads to a compile-time error.
Incorrect
When a field is declared in an interface, it’s by default public, static and final. The myField field in the Foo interface is final, but it’s not set to any value. This uninitialized state leads to a compile-time error.
Unattempted
When a field is declared in an interface, it’s by default public, static and final. The myField field in the Foo interface is final, but it’s not set to any value. This uninitialized state leads to a compile-time error.
Question 16 of 65
16. Question
Given:
public class Test {
public static void main(String[] args) {
try {
throwException(); // Line 1
} catch (IOException e) { // Line 2
e.printStackTrace();
}
}
static void throwException() throws RuntimeException { // Line 3
throw new RuntimeException();
}
}
Which lines of code cause a compile-time error?
Correct
The throws clause on line 3 is redundant as the specified exception is unchecked. However, it doesn’t harm if we still indicate such an exception on the method’s declaration.
Since RuntimeException is unchecked, the exception handling mechanism in the main method isn’t needed. Nevertheless, when it’s in use, and the exception type specified in the catch block is checked, this exception type must match the type of exception objects that can be thrown.
In the given program, no IOException is thrown, hence a compile-time error occurs where such an exception is caught.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Incorrect
The throws clause on line 3 is redundant as the specified exception is unchecked. However, it doesn’t harm if we still indicate such an exception on the method’s declaration.
Since RuntimeException is unchecked, the exception handling mechanism in the main method isn’t needed. Nevertheless, when it’s in use, and the exception type specified in the catch block is checked, this exception type must match the type of exception objects that can be thrown.
In the given program, no IOException is thrown, hence a compile-time error occurs where such an exception is caught.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Unattempted
The throws clause on line 3 is redundant as the specified exception is unchecked. However, it doesn’t harm if we still indicate such an exception on the method’s declaration.
Since RuntimeException is unchecked, the exception handling mechanism in the main method isn’t needed. Nevertheless, when it’s in use, and the exception type specified in the catch block is checked, this exception type must match the type of exception objects that can be thrown.
In the given program, no IOException is thrown, hence a compile-time error occurs where such an exception is caught.
Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Question 17 of 65
17. Question
Which of the following describes polymorphism in Java?
Correct
Option A describes inheritance, while option B portrays overriding.
At first glance, options B and C look the same. Nonetheless, their key difference is that in option C, subclasses can share some functionality with the parent class. This is a feature of polymorphism.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
Incorrect
Option A describes inheritance, while option B portrays overriding.
At first glance, options B and C look the same. Nonetheless, their key difference is that in option C, subclasses can share some functionality with the parent class. This is a feature of polymorphism.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
Unattempted
Option A describes inheritance, while option B portrays overriding.
At first glance, options B and C look the same. Nonetheless, their key difference is that in option C, subclasses can share some functionality with the parent class. This is a feature of polymorphism.
Reference: https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
Question 18 of 65
18. Question
Which option indicates the destination directory for class files when executing the javac command?
Correct
Here’s a description of the -d option of the javac command:
Sets the destination directory for class files. If a class is part of a package, then javac puts the class file in a subdirectory that reflects the package name and creates directories as needed.
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 -d option of the javac command:
Sets the destination directory for class files. If a class is part of a package, then javac puts the class file in a subdirectory that reflects the package name and creates directories as needed.
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 -d option of the javac command:
Sets the destination directory for class files. If a class is part of a package, then javac puts the class file in a subdirectory that reflects the package name and creates directories as needed.
All the other options aren’t recognized by this command.
Reference: https://docs.oracle.com/en/java/javase/11/tools/javac.html
Question 19 of 65
19. Question
Given:
String text = “hello”;
text.concat(“bye”);
text.concat(“hello”);
text.concat(“bye”);
System.out.println(text);
What is the output?
Correct
Notice a String object is immutable – it cannot be changed after being created. The concat method appends the string argument to the end of the current string and returns the concatenation. The method doesn’t modify the String object it’s invoked on, thus the final value of the string referenced by variable text is still “hello”.
Incorrect
Notice a String object is immutable – it cannot be changed after being created. The concat method appends the string argument to the end of the current string and returns the concatenation. The method doesn’t modify the String object it’s invoked on, thus the final value of the string referenced by variable text is still “hello”.
Unattempted
Notice a String object is immutable – it cannot be changed after being created. The concat method appends the string argument to the end of the current string and returns the concatenation. The method doesn’t modify the String object it’s invoked on, thus the final value of the string referenced by variable text is still “hello”.
Question 20 of 65
20. Question
Given:
public class Test {
void switchNumber(long number) {
switch (number) {
case 1.0:
System.out.println(“Floating point”);
case 1:
System.out.println(“Integer”);
}
}
public static void main(String[] args) {
Test test = new Test();
test.switchNumber(1L);
}
}
What is the output of the program?
Correct
As per the Oracle Java Tutorial, a switch statement can only work with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
In the given code, the switch expression is of type long, hence it fails to compile.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Incorrect
As per the Oracle Java Tutorial, a switch statement can only work with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
In the given code, the switch expression is of type long, hence it fails to compile.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Unattempted
As per the Oracle Java Tutorial, a switch statement can only work with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
In the given code, the switch expression is of type long, hence it fails to compile.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Question 21 of 65
21. Question
Given:
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5};
int[][] matrix = new int[3][2];
for (int i = 0; i < array1.length; i++) {
matrix[i][0] = array1[i];
}
for (int i = 0; i < array2.length; i++) {
matrix[i][1] = array2[i];
}
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
What is the output when executing the given code fragment?
Correct
When the two-dimensional array matrix is created, all of its elements are initialized to 0. The two for loops that follow populate matrix with elements from array1 and array2. During this process, elements from an original array are scattered across different arrays in the matrix.
Specifically, array1 has three elements, which are used to set the first element of each array in the matrix. Likewise, two elements of array2 are used to set the second element of each matrix array. The last element at the position [2][1] isn’t re-set during the population, so it keeps its default value.
Incorrect
When the two-dimensional array matrix is created, all of its elements are initialized to 0. The two for loops that follow populate matrix with elements from array1 and array2. During this process, elements from an original array are scattered across different arrays in the matrix.
Specifically, array1 has three elements, which are used to set the first element of each array in the matrix. Likewise, two elements of array2 are used to set the second element of each matrix array. The last element at the position [2][1] isn’t re-set during the population, so it keeps its default value.
Unattempted
When the two-dimensional array matrix is created, all of its elements are initialized to 0. The two for loops that follow populate matrix with elements from array1 and array2. During this process, elements from an original array are scattered across different arrays in the matrix.
Specifically, array1 has three elements, which are used to set the first element of each array in the matrix. Likewise, two elements of array2 are used to set the second element of each matrix array. The last element at the position [2][1] isn’t re-set during the population, so it keeps its default value.
Question 22 of 65
22. Question
Given:
interface Foo {
int myField = 0;
void myMethod();
}
What of the following statements is correct?
Correct
Option A is incorrect as an abstract class doesn’t need to override that method.
Option B is incorrect as in such a case, the field defined in the class just hides the one in the Foo interface.
Option C is incorrect as unlike overriding methods, an overloaded one doesn’t need to have a less restrictive access modifier.
Option D is incorrect as an interface field is a constant – it cannot be changed.
Incorrect
Option A is incorrect as an abstract class doesn’t need to override that method.
Option B is incorrect as in such a case, the field defined in the class just hides the one in the Foo interface.
Option C is incorrect as unlike overriding methods, an overloaded one doesn’t need to have a less restrictive access modifier.
Option D is incorrect as an interface field is a constant – it cannot be changed.
Unattempted
Option A is incorrect as an abstract class doesn’t need to override that method.
Option B is incorrect as in such a case, the field defined in the class just hides the one in the Foo interface.
Option C is incorrect as unlike overriding methods, an overloaded one doesn’t need to have a less restrictive access modifier.
Option D is incorrect as an interface field is a constant – it cannot be changed.
public class Bar extends Foo {
Bar(String arg) {
System.out.println(“Bar: ” + arg);
}
public static void main(String[] args) {
new Bar(“test”);
}
}
What is the program’s output?
Correct
Inside the given Bar constructor, there’s no call to another constructor of the same class or to a superclass’s constructor. This means a call to the no-argument constructor of the superclass is added automatically. However, such a constructor doesn’t exist, leading to a compile-time error.
Notice if the Foo class had been defined with no explicit constructor, the compiler would have automatically generated a no-argument constructor for it. In case at least one constructor is declared, the compiler will back off, and no constructor is created by default.
Incorrect
Inside the given Bar constructor, there’s no call to another constructor of the same class or to a superclass’s constructor. This means a call to the no-argument constructor of the superclass is added automatically. However, such a constructor doesn’t exist, leading to a compile-time error.
Notice if the Foo class had been defined with no explicit constructor, the compiler would have automatically generated a no-argument constructor for it. In case at least one constructor is declared, the compiler will back off, and no constructor is created by default.
Unattempted
Inside the given Bar constructor, there’s no call to another constructor of the same class or to a superclass’s constructor. This means a call to the no-argument constructor of the superclass is added automatically. However, such a constructor doesn’t exist, leading to a compile-time error.
Notice if the Foo class had been defined with no explicit constructor, the compiler would have automatically generated a no-argument constructor for it. In case at least one constructor is declared, the compiler will back off, and no constructor is created by default.
Question 24 of 65
24. Question
Given:
public class Test {
static String text1 = printAndEcho(“a”);
static {
printAndEcho(“b”);
}
static String text2 = printAndEcho(“c”);
static String printAndEcho(String text) {
System.out.print(text);
return text;
}
public static void main(String[] args) { }
}
What is printed to the console when the main method runs?
Correct
All members of the given class are static, hence they are initialized and executed when the class is loaded. The emptiness of the main method doesn’t affect that process.
The expressions initializing the two static fields as well as the static initialization block are executed in the order they are defined. As a result, the string abc is printed when the Test class is loaded.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Incorrect
All members of the given class are static, hence they are initialized and executed when the class is loaded. The emptiness of the main method doesn’t affect that process.
The expressions initializing the two static fields as well as the static initialization block are executed in the order they are defined. As a result, the string abc is printed when the Test class is loaded.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Unattempted
All members of the given class are static, hence they are initialized and executed when the class is loaded. The emptiness of the main method doesn’t affect that process.
The expressions initializing the two static fields as well as the static initialization block are executed in the order they are defined. As a result, the string abc is printed when the Test class is loaded.
Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Question 25 of 65
25. Question
Given:
try {
throw new IOException();
} catch (IOException e) {
System.out.println(“IOException”);
} finally {
System.out.println(“finally”);
} catch (Exception e) {
System.out.println(“Exception”);
}
What is the given code’s output?
Correct
A finally block, if existent, must be the last block in an exception handling handler. This isn’t the case over here, leading to a compile-time error.
Incorrect
A finally block, if existent, must be the last block in an exception handling handler. This isn’t the case over here, leading to a compile-time error.
Unattempted
A finally block, if existent, must be the last block in an exception handling handler. This isn’t the case over here, leading to a compile-time error.
Question 26 of 65
26. Question
Given:
StringBuilder builder = new StringBuilder(“ABCDE”)
.delete(1, 2)
.deleteCharAt(3);
System.out.println(builder);
What is the program’s output?
Given:
int x = 1, y = -2;
x -= 3;
y /= 4;
System.out.println(x + ” ” + y);
What is the output of the given code?
Correct
The two statements in the middle is equivalent to:
x = x – 3;
y = y / 4;
Incorrect
The two statements in the middle is equivalent to:
x = x – 3;
y = y / 4;
Unattempted
The two statements in the middle is equivalent to:
x = x – 3;
y = y / 4;
Question 28 of 65
28. Question
Given the foo module:
module foo {
exports foo to test;
}
With a class:
package foo;
public class MyFoo { }
And the bar module:
module bar {
exports bar;
requires java.base;
}
With another class:
package bar;
public class MyBar { }
These MyFoo and MyBar classes are used in another class:
public class MyTest {
public static void main(String[] args) {
new MyFoo(); // Line 1
new MyBar(); // Line 2
}
}
Here’s the declaration of the module containing MyTest:
module test {
requires bar;
}
What happens when compiling and executing the main method?
Correct
The exports to directive in the foo module exports the foo package to the test module, but it doesn’t exempt the target module from explicitly requiring the dependency module. Such a directive is missing in the test module’s declaration, leading to a compile-time error on line 1.
Had the directive requires foo been added to the test module, option E would have been the correct answer.
Incorrect
The exports to directive in the foo module exports the foo package to the test module, but it doesn’t exempt the target module from explicitly requiring the dependency module. Such a directive is missing in the test module’s declaration, leading to a compile-time error on line 1.
Had the directive requires foo been added to the test module, option E would have been the correct answer.
Unattempted
The exports to directive in the foo module exports the foo package to the test module, but it doesn’t exempt the target module from explicitly requiring the dependency module. Such a directive is missing in the test module’s declaration, leading to a compile-time error on line 1.
Had the directive requires foo been added to the test module, option E would have been the correct answer.
Question 29 of 65
29. Question
Given:
interface Foo {
abstract void methodA();
void methodB();
static void methodC() {
// a valid body
}
}
abstract class Bar implements Foo {
@Override
public abstract void methodB();
@Override
public static void methodC() {
// a valid body
}
}
Which of the following changes when applied independently makes the Bar class compile?
Correct
methodC in the Foo interface is static and attached to the interface itself. When the Bar class implements this interface, it doesn’t inherit that static method. As a result, the @Override annotation on methodC in the Bar class is invalid. Note that we can keep the @Override annotation on methodB, but removing it is also all right.
A method in an interface is abstract by default, hence we don’t need to add the abstract keyword. However, it’s still valid if we do. This means option B is incorrect.
If we removed the static keyword on methodC in the Bar class, its @Override annotation is still there, hence the class fails to compile. Option C is incorrect, then.
methodA and methodB in the Foo interface are abstract, but the Bar class is abstract as well. This means Bar doesn’t need to override either of those methods. Therefore, options D and E are incorrect.
Incorrect
methodC in the Foo interface is static and attached to the interface itself. When the Bar class implements this interface, it doesn’t inherit that static method. As a result, the @Override annotation on methodC in the Bar class is invalid. Note that we can keep the @Override annotation on methodB, but removing it is also all right.
A method in an interface is abstract by default, hence we don’t need to add the abstract keyword. However, it’s still valid if we do. This means option B is incorrect.
If we removed the static keyword on methodC in the Bar class, its @Override annotation is still there, hence the class fails to compile. Option C is incorrect, then.
methodA and methodB in the Foo interface are abstract, but the Bar class is abstract as well. This means Bar doesn’t need to override either of those methods. Therefore, options D and E are incorrect.
Unattempted
methodC in the Foo interface is static and attached to the interface itself. When the Bar class implements this interface, it doesn’t inherit that static method. As a result, the @Override annotation on methodC in the Bar class is invalid. Note that we can keep the @Override annotation on methodB, but removing it is also all right.
A method in an interface is abstract by default, hence we don’t need to add the abstract keyword. However, it’s still valid if we do. This means option B is incorrect.
If we removed the static keyword on methodC in the Bar class, its @Override annotation is still there, hence the class fails to compile. Option C is incorrect, then.
methodA and methodB in the Foo interface are abstract, but the Bar class is abstract as well. This means Bar doesn’t need to override either of those methods. Therefore, options D and E are incorrect.
Question 30 of 65
30. Question
Which of the following class declarations can be compiled?
Correct
Option A is invalid as a concreate method doesn’t have a body. Option B is invalid as an abstract method can only be defined in an abstract class or an interface. Option D is invalid as an abstract method is always non-static.
There’s nothing wrong with option C – we can define concrete methods inside an abstract class.
Incorrect
Option A is invalid as a concreate method doesn’t have a body. Option B is invalid as an abstract method can only be defined in an abstract class or an interface. Option D is invalid as an abstract method is always non-static.
There’s nothing wrong with option C – we can define concrete methods inside an abstract class.
Unattempted
Option A is invalid as a concreate method doesn’t have a body. Option B is invalid as an abstract method can only be defined in an abstract class or an interface. Option D is invalid as an abstract method is always non-static.
There’s nothing wrong with option C – we can define concrete methods inside an abstract class.
Question 31 of 65
31. Question
Given:
public class Test {
public static void main(String[] args) {
Test test1 = new Test(); // Line 0
Test test2 = test1; // Line 1
Test test3 = new Test(); // Line 2
test2 = test3; // Line 3
test3 = test1; // Line 4
test1 = test2; // Line 5
test3 = test2; // Line 6
}
}
After which line the object created on line 0 is eligible for garbage collection?
Correct
When a Foo object is created on line 0, it’s referenced by variable test1. The assignment on line 1 makes both variables test1 and test2 reference that object.
On line 3, variable test2 is set to another object that was created on line 2. At this point, only variable test1 refers to the first object.
On line 4, variable test3 is set to that object as well. It’s ready to be collected after both of these variables are set to another object, which only happens after line 6.
Incorrect
When a Foo object is created on line 0, it’s referenced by variable test1. The assignment on line 1 makes both variables test1 and test2 reference that object.
On line 3, variable test2 is set to another object that was created on line 2. At this point, only variable test1 refers to the first object.
On line 4, variable test3 is set to that object as well. It’s ready to be collected after both of these variables are set to another object, which only happens after line 6.
Unattempted
When a Foo object is created on line 0, it’s referenced by variable test1. The assignment on line 1 makes both variables test1 and test2 reference that object.
On line 3, variable test2 is set to another object that was created on line 2. At this point, only variable test1 refers to the first object.
On line 4, variable test3 is set to that object as well. It’s ready to be collected after both of these variables are set to another object, which only happens after line 6.
Question 32 of 65
32. Question
Given:
String string = “abcabcabc”;
int index1 = string.lastIndexOf(“cab”);
int index2 = string.lastIndexOf(“bca”, index1);
System.out.println(index1 + ” ” + index2);
What’s the output of the program?
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
String result = test.identifyNumber(1);
System.out.println(result);
}
String identifyNumber(int number) {
switch (number) {
default:
return “Zero”;
case 1:
return “Positive”;
case -1:
return “Negative”;
}
}
}
What is the program’s output?
Correct
The default label only matches an argument if all the other labels don’t, regardless of its position.
In the given code, when the label 1 matches, the identifyNumber returns right away, hence the result is “Positive”.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Incorrect
The default label only matches an argument if all the other labels don’t, regardless of its position.
In the given code, when the label 1 matches, the identifyNumber returns right away, hence the result is “Positive”.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Unattempted
The default label only matches an argument if all the other labels don’t, regardless of its position.
In the given code, when the label 1 matches, the identifyNumber returns right away, hence the result is “Positive”.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Question 34 of 65
34. Question
Given:
int[] array1 = {1, 2, 3};
int[] array2 = {1, 3};
int result = Arrays.compare(array1, array2);
System.out.println(result);
What is the output?
Correct
As per the JDK API Specification, the Arrays#compare method returns the value 0 if the first and second array are equal and contain the same elements in the same order; a value less than 0 if the first array is lexicographically less than the second array; and a value greater than 0 if the first array is lexicographically greater than the second array.
The arrays referenced by variables array1 and array2 has their first elements being the same, while the second element of array1 is less than that of array2. Therefore, the comparison result is a negative number.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#compare(int%5B%5D,int%5B%5D)
Incorrect
As per the JDK API Specification, the Arrays#compare method returns the value 0 if the first and second array are equal and contain the same elements in the same order; a value less than 0 if the first array is lexicographically less than the second array; and a value greater than 0 if the first array is lexicographically greater than the second array.
The arrays referenced by variables array1 and array2 has their first elements being the same, while the second element of array1 is less than that of array2. Therefore, the comparison result is a negative number.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#compare(int%5B%5D,int%5B%5D)
Unattempted
As per the JDK API Specification, the Arrays#compare method returns the value 0 if the first and second array are equal and contain the same elements in the same order; a value less than 0 if the first array is lexicographically less than the second array; and a value greater than 0 if the first array is lexicographically greater than the second array.
The arrays referenced by variables array1 and array2 has their first elements being the same, while the second element of array1 is less than that of array2. Therefore, the comparison result is a negative number.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#compare(int%5B%5D,int%5B%5D)
Question 35 of 65
35. Question
Given:
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
String text = test.convertToUpperCase(null);
System.out.println(text);
} catch (Exception e) {
try {
if (e instanceof RuntimeException)
throw e;
} finally {
System.out.println(“inner”);
}
} finally {
System.out.println(“outer”);
}
}
String convertToUpperCase(String input) {
return input.toUpperCase();
}
}
What happens when executing the given program?
Correct
When the convertToUpperCase method is called with a null argument, it throws a NullPointerException. This exception is then caught by the catch block within the main method.
Since NullPointerException is a subclass of RuntimeException, the caught exception is re-thrown. However, the system will execute finally blocks before throwing that exception up the call stack. The string “inner” is printed by the catch block, while “outer” is by the outer finally block. This means “inner” goes before “outer”.
Incorrect
When the convertToUpperCase method is called with a null argument, it throws a NullPointerException. This exception is then caught by the catch block within the main method.
Since NullPointerException is a subclass of RuntimeException, the caught exception is re-thrown. However, the system will execute finally blocks before throwing that exception up the call stack. The string “inner” is printed by the catch block, while “outer” is by the outer finally block. This means “inner” goes before “outer”.
Unattempted
When the convertToUpperCase method is called with a null argument, it throws a NullPointerException. This exception is then caught by the catch block within the main method.
Since NullPointerException is a subclass of RuntimeException, the caught exception is re-thrown. However, the system will execute finally blocks before throwing that exception up the call stack. The string “inner” is printed by the catch block, while “outer” is by the outer finally block. This means “inner” goes before “outer”.
Question 36 of 65
36. Question
Given:
interface Foo {
String name = “Foo”;
}
class Bar implements Foo {
static String name = “Bar”;
}
public class Test extends Bar implements Foo {
public static void main(String[] args) {
Foo foo = new Bar();
System.out.println(foo.name); // Line 1
System.out.println(name); // Line 2
}
}
What is the program’s output?
Correct
On line 2, the name variable is ambiguous as both the interface Foo and class Bar define such a field. This ambiguity leads to a compile-time error.
Notice a field defined within a subtype can hide fields of the same name in supertypes, but a field defined in a supertype cannot hide other fields in other supertypes.
The access on line 1 is valid as the variable is clear: it’s the name field defined in the reference type of foo, which is Foo.
Incorrect
On line 2, the name variable is ambiguous as both the interface Foo and class Bar define such a field. This ambiguity leads to a compile-time error.
Notice a field defined within a subtype can hide fields of the same name in supertypes, but a field defined in a supertype cannot hide other fields in other supertypes.
The access on line 1 is valid as the variable is clear: it’s the name field defined in the reference type of foo, which is Foo.
Unattempted
On line 2, the name variable is ambiguous as both the interface Foo and class Bar define such a field. This ambiguity leads to a compile-time error.
Notice a field defined within a subtype can hide fields of the same name in supertypes, but a field defined in a supertype cannot hide other fields in other supertypes.
The access on line 1 is valid as the variable is clear: it’s the name field defined in the reference type of foo, which is Foo.
Question 37 of 65
37. Question
Assuming required class files of a program are stored in two directories: dir1 and dir2. Which of the following is a correct way to launch that program?
Correct
When launching a program with the java command, the classpath option indicates a semicolon (;) separated list of directories, JAR archives, and ZIP archives to search for class files.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Incorrect
When launching a program with the java command, the classpath option indicates a semicolon (;) separated list of directories, JAR archives, and ZIP archives to search for class files.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Unattempted
When launching a program with the java command, the classpath option indicates a semicolon (;) separated list of directories, JAR archives, and ZIP archives to search for class files.
Reference: https://docs.oracle.com/en/java/javase/11/tools/java.html
Question 38 of 65
38. Question
Given:
String string = “foo:and:bar”;
String[] array = string.split(“:”, 2);
System.out.println(Arrays.toString(array));
What is the output?
Correct
The split method splits this string around matches of the given regular expression. In the given code, the expression is just a simple string containing only a colon character.
The limit argument to the method controls the number of times the pattern is applied and therefore affects the length of the resulting array. In this case, the limit is 2, meaning the resulting array has two elements, and the split happens at the first occurrence of the colon character.
If there had been no limit, or the limit argument is less than 0 or greater than 2, option A would have been the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String,int)
Incorrect
The split method splits this string around matches of the given regular expression. In the given code, the expression is just a simple string containing only a colon character.
The limit argument to the method controls the number of times the pattern is applied and therefore affects the length of the resulting array. In this case, the limit is 2, meaning the resulting array has two elements, and the split happens at the first occurrence of the colon character.
If there had been no limit, or the limit argument is less than 0 or greater than 2, option A would have been the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String,int)
Unattempted
The split method splits this string around matches of the given regular expression. In the given code, the expression is just a simple string containing only a colon character.
The limit argument to the method controls the number of times the pattern is applied and therefore affects the length of the resulting array. In this case, the limit is 2, meaning the resulting array has two elements, and the split happens at the first occurrence of the colon character.
If there had been no limit, or the limit argument is less than 0 or greater than 2, option A would have been the correct answer.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String,int)
Question 39 of 65
39. Question
Given:
class Foo {
Foo() {
System.out.println(“Foo”);
}
}
public class Bar extends Foo {
Bar() {
super(); // Line 1
this(“Bar”); // Line 2
}
Bar(String arg) { // Line 3
System.out.println(arg);
}
public static void main(String[] args) {
new Bar();
}
}
What is the program’s output?
Correct
A call to this() or super() inside a constructor, if any, must be the first statement. This isn’t the case over, hence a compile-time error occurs. Of course both this() and super() cannot be the first statement at the same time, meaning that we cannot call more than one constructor inside the body of another constructor.
Incorrect
A call to this() or super() inside a constructor, if any, must be the first statement. This isn’t the case over, hence a compile-time error occurs. Of course both this() and super() cannot be the first statement at the same time, meaning that we cannot call more than one constructor inside the body of another constructor.
Unattempted
A call to this() or super() inside a constructor, if any, must be the first statement. This isn’t the case over, hence a compile-time error occurs. Of course both this() and super() cannot be the first statement at the same time, meaning that we cannot call more than one constructor inside the body of another constructor.
Question 40 of 65
40. 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) {
if (number % 2 == 0) break;
System.out.print(number + " ");
number++;
}
}
}
What is the program's output?
Correct
In the first iteration of the while construct, the if condition expression evaluates to true as number is 0. This means the break statement is executed and the while construct exits straight away. As a result, the System.out.print statement has no chance to run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Incorrect
In the first iteration of the while construct, the if condition expression evaluates to true as number is 0. This means the break statement is executed and the while construct exits straight away. As a result, the System.out.print statement has no chance to run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Unattempted
In the first iteration of the while construct, the if condition expression evaluates to true as number is 0. This means the break statement is executed and the while construct exits straight away. As a result, the System.out.print statement has no chance to run.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Question 41 of 65
41. Question
Given the output:
foo -> bar
foo -> java.base
Which command can produce that result?
Correct
The given output is a dependency summary. To produce such an outcome, we must use the jdeps command with the -s or -summary option.
Notice option B would have also been correct had one leading dash been removed.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Incorrect
The given output is a dependency summary. To produce such an outcome, we must use the jdeps command with the -s or -summary option.
Notice option B would have also been correct had one leading dash been removed.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Unattempted
The given output is a dependency summary. To produce such an outcome, we must use the jdeps command with the -s or -summary option.
Notice option B would have also been correct had one leading dash been removed.
Reference: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
Question 42 of 65
42. Question
Given:
class Foo {
String myField = “Foo”;
}
public class Bar extends Foo {
String myField = “Bar”;
void myMethod() {
System.out.println(myField);
}
public static void main(String[] args) {
Bar bar = new Bar();
Foo foo = (Foo) bar; // Line 1
foo.myMethod(); // Line 2
}
}
What is the program’s output?
Correct
On line 1, an object of type Bar is assigned to a variable of type Foo. This is upcasting, thus the assignment is valid.
In the last statement, the myMethod method is called on an object referenced by the Foo reference type. Since there’s no such a method in the Foo class, the compiler refuses to compile the given code.
Incorrect
On line 1, an object of type Bar is assigned to a variable of type Foo. This is upcasting, thus the assignment is valid.
In the last statement, the myMethod method is called on an object referenced by the Foo reference type. Since there’s no such a method in the Foo class, the compiler refuses to compile the given code.
Unattempted
On line 1, an object of type Bar is assigned to a variable of type Foo. This is upcasting, thus the assignment is valid.
In the last statement, the myMethod method is called on an object referenced by the Foo reference type. Since there’s no such a method in the Foo class, the compiler refuses to compile the given code.
Question 43 of 65
43. Question
Given:
List list = new ArrayList<>(List.of(“A”, “B”));
list.addAll(1, List.of(“A”, “C”));
list.remove(“A”);
System.out.println(list);
What is the output of the given code fragment?
Correct
The addAll method inserts all new elements, “A” and “C” at the specified position. This means after this method is called, the given list is [A, A, C, B].
The remove method removes the first occurrence of the specified element, meaning the first “A” is deleted. The list will then contain the remaining three elements: [A, C, B].
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Incorrect
The addAll method inserts all new elements, “A” and “C” at the specified position. This means after this method is called, the given list is [A, A, C, B].
The remove method removes the first occurrence of the specified element, meaning the first “A” is deleted. The list will then contain the remaining three elements: [A, C, B].
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Unattempted
The addAll method inserts all new elements, “A” and “C” at the specified position. This means after this method is called, the given list is [A, A, C, B].
The remove method removes the first occurrence of the specified element, meaning the first “A” is deleted. The list will then contain the remaining three elements: [A, C, B].
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html
Question 44 of 65
44. Question
Given:
public class Test {
public static void main(String[] args) {
String text;
if (text == null) {// Line 1
text = “foo”; // Line 2
}
System.out.println(text); // Line 3
}
}
What is the program’s output?
Correct
A local variable is different a class-level field in that it’s not automatically set to the default value of its type. As a result, the text variable on line 1 is checked when it hasn’t been set, resulting in a compile-time error.
Incorrect
A local variable is different a class-level field in that it’s not automatically set to the default value of its type. As a result, the text variable on line 1 is checked when it hasn’t been set, resulting in a compile-time error.
Unattempted
A local variable is different a class-level field in that it’s not automatically set to the default value of its type. As a result, the text variable on line 1 is checked when it hasn’t been set, resulting in a compile-time error.
Question 45 of 65
45. Question
Given:
public class Test {
void modify(String string, StringBuilder builder, int number) {
string = string.toUpperCase();
builder = builder.append(“builder”);
number++;
}
static public void main(String[] args) {
Test test = new Test();
String text = “string”;
StringBuilder builder = new StringBuilder();
int number = 0;
test.modify(text, builder, number);
System.out.println(text + builder + number);
}
}
What is the program’s output?
Correct
String is an immutable class, meaning the toUpperCase method returns a new string instead of mutating the current one. As a result, the string argument passed to the modify method isn’t affected by operations inside the method.
Meanwhile, the StringBuilder class is mutable. The append method therefore modifies the StringBuilder object passed to method modify. Consequently, all changes made to the StringBuilder argument is seen after that method returns.
The number parameter of the modify method is of a primitive type. Unlike an object reference parameter that keeps the address of the passed-in argument, a primitive parameter stores a copy of the argument itself. Any changes made to this parameter only impact the copy, not the original value. This means the change to the number parameter inside the modify method is invisible to the main method.
Incorrect
String is an immutable class, meaning the toUpperCase method returns a new string instead of mutating the current one. As a result, the string argument passed to the modify method isn’t affected by operations inside the method.
Meanwhile, the StringBuilder class is mutable. The append method therefore modifies the StringBuilder object passed to method modify. Consequently, all changes made to the StringBuilder argument is seen after that method returns.
The number parameter of the modify method is of a primitive type. Unlike an object reference parameter that keeps the address of the passed-in argument, a primitive parameter stores a copy of the argument itself. Any changes made to this parameter only impact the copy, not the original value. This means the change to the number parameter inside the modify method is invisible to the main method.
Unattempted
String is an immutable class, meaning the toUpperCase method returns a new string instead of mutating the current one. As a result, the string argument passed to the modify method isn’t affected by operations inside the method.
Meanwhile, the StringBuilder class is mutable. The append method therefore modifies the StringBuilder object passed to method modify. Consequently, all changes made to the StringBuilder argument is seen after that method returns.
The number parameter of the modify method is of a primitive type. Unlike an object reference parameter that keeps the address of the passed-in argument, a primitive parameter stores a copy of the argument itself. Any changes made to this parameter only impact the copy, not the original value. This means the change to the number parameter inside the modify method is invisible to the main method.
Question 46 of 65
46. Question
Given:
List
Correct
The list variable references a collection of two elements: “A” and “B”. The for-each loop walks through both elements and prints them out.
Notice the continue statement doesn’t play any role as it only instructs the loop to move on to the next iteration, which the loop already does regardless.
Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html
Incorrect
The list variable references a collection of two elements: “A” and “B”. The for-each loop walks through both elements and prints them out.
Notice the continue statement doesn’t play any role as it only instructs the loop to move on to the next iteration, which the loop already does regardless.
Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html
Unattempted
The list variable references a collection of two elements: “A” and “B”. The for-each loop walks through both elements and prints them out.
Notice the continue statement doesn’t play any role as it only instructs the loop to move on to the next iteration, which the loop already does regardless.
Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html
Question 47 of 65
47. Question
Which of the following must be installed to set up a Java development environment on a computer?
Correct
JDK is the only software required to set up a development environment.
JRE is used to run a compiled program instead of working with source files.
We often use an IDE to write programs, but it isn’t compulsory.
Incorrect
JDK is the only software required to set up a development environment.
JRE is used to run a compiled program instead of working with source files.
We often use an IDE to write programs, but it isn’t compulsory.
Unattempted
JDK is the only software required to set up a development environment.
JRE is used to run a compiled program instead of working with source files.
We often use an IDE to write programs, but it isn’t compulsory.
Question 48 of 65
48. Question
Given:
List list = new ArrayList<>(List.of(“A”, “A”, “B”, “B”));
System.out.println(list.indexOf(“B”) + ” ” + list.lastIndexOf(“A”));
What is the output of the given code?
Correct
The indexOf method returns the index of the first occurrence of the specified element, while the lastIndexOf method returns the last occurrence.
The two strings “B” are at positions 2 and 3, and the first of them is 2. Meanwhile, the two strings “A” are at positions 0 and 1, and the last of them is 1.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#indexOf(java.lang.Object) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#lastIndexOf(java.lang.Object)
Incorrect
The indexOf method returns the index of the first occurrence of the specified element, while the lastIndexOf method returns the last occurrence.
The two strings “B” are at positions 2 and 3, and the first of them is 2. Meanwhile, the two strings “A” are at positions 0 and 1, and the last of them is 1.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#indexOf(java.lang.Object) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#lastIndexOf(java.lang.Object)
Unattempted
The indexOf method returns the index of the first occurrence of the specified element, while the lastIndexOf method returns the last occurrence.
The two strings “B” are at positions 2 and 3, and the first of them is 2. Meanwhile, the two strings “A” are at positions 0 and 1, and the last of them is 1.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#indexOf(java.lang.Object) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#lastIndexOf(java.lang.Object)
Question 49 of 65
49. Question
Given:
LocalDateTime dateTime = LocalDateTime.parse(“2019-01-01”); // Line 1
String formatted = dateTime.format(DateTimeFormatter.ISO_DATE_TIME); // Line 2
System.out.println(formatted);
What is the given code fragment’s output?
Correct
The String passed to the parse method must represent a valid date-time and is parsed using DateTimeFormatter.ISO_LOCAL_DATE_TIME. A time component is missing in this string, resulting in a DateTimeParseException at runtime.
Incorrect
The String passed to the parse method must represent a valid date-time and is parsed using DateTimeFormatter.ISO_LOCAL_DATE_TIME. A time component is missing in this string, resulting in a DateTimeParseException at runtime.
Unattempted
The String passed to the parse method must represent a valid date-time and is parsed using DateTimeFormatter.ISO_LOCAL_DATE_TIME. A time component is missing in this string, resulting in a DateTimeParseException at runtime.
Question 50 of 65
50. Question
Given:
class Foo {
static String text = “Foo”;
}
class Bar extends Foo {
protected void printText(String text) {
System.out.println(text);
}
}
public class Test extends Bar {
String text = “Bar”;
void printText() { // Line 1
String text = super.text; // Line 2
super.printText(text); // Line 3
}
static public void main(String[] args) {
new Test().printText();
}
}
What is the program’s output?
Correct
On line 1, the printText method is declared with a more restrictive access modifier than the method of the same name in the Bar class. However, notice these methods have different parameter types. This means the method in the Test class doesn’t override the one in the Bar class, hence it doesn’t need to carry an equal-or-less restrictive modifier.
One line 2, the super keyword is used to reference the text field in the superclass. The Bar class doesn’t declare such a field, but it inherits from the Foo class. Therefore, nothing is wrong over here. Notice text is a static field and should be accessed using a class reference, but it’s still valid to use the super keyword.
On line 3, the printText method of the superclass, Bar, is called. The text local variable shadows the field of the same name, hence the value found on line 2 is printed.
Incorrect
On line 1, the printText method is declared with a more restrictive access modifier than the method of the same name in the Bar class. However, notice these methods have different parameter types. This means the method in the Test class doesn’t override the one in the Bar class, hence it doesn’t need to carry an equal-or-less restrictive modifier.
One line 2, the super keyword is used to reference the text field in the superclass. The Bar class doesn’t declare such a field, but it inherits from the Foo class. Therefore, nothing is wrong over here. Notice text is a static field and should be accessed using a class reference, but it’s still valid to use the super keyword.
On line 3, the printText method of the superclass, Bar, is called. The text local variable shadows the field of the same name, hence the value found on line 2 is printed.
Unattempted
On line 1, the printText method is declared with a more restrictive access modifier than the method of the same name in the Bar class. However, notice these methods have different parameter types. This means the method in the Test class doesn’t override the one in the Bar class, hence it doesn’t need to carry an equal-or-less restrictive modifier.
One line 2, the super keyword is used to reference the text field in the superclass. The Bar class doesn’t declare such a field, but it inherits from the Foo class. Therefore, nothing is wrong over here. Notice text is a static field and should be accessed using a class reference, but it’s still valid to use the super keyword.
On line 3, the printText method of the superclass, Bar, is called. The text local variable shadows the field of the same name, hence the value found on line 2 is printed.
Question 51 of 65
51. Question
Given:
public class Test {
void methodA() throws FileNotFoundException {
throw new RuntimeException(); // Line 1
}
void methodB() throws NullPointerException {
throw new IOException(); // Line 2
}
void methodC() throws FileNotFoundException {
methodA(); // Line 3
methodB(); // Line 4
}
public static void main(String[] args) {
Test test = new Test();
test.methodC(); // Line 5
}
}
Which two lines of code cause compile-time errors?
Correct
On line 2, an IOException is thrown without being caught or specified. On line 5, the FileNotFoundException type that’s specified in the declaration of methodC isn’t caught or specified either.
Notice NullPointerException and RuntimeException are unchecked, thus we don’t need to handle them.
Incorrect
On line 2, an IOException is thrown without being caught or specified. On line 5, the FileNotFoundException type that’s specified in the declaration of methodC isn’t caught or specified either.
Notice NullPointerException and RuntimeException are unchecked, thus we don’t need to handle them.
Unattempted
On line 2, an IOException is thrown without being caught or specified. On line 5, the FileNotFoundException type that’s specified in the declaration of methodC isn’t caught or specified either.
Notice NullPointerException and RuntimeException are unchecked, thus we don’t need to handle them.
Question 52 of 65
52. Question
Given:
int i, j;
for (i = 0, j = 0; i + j < 10; i++) {
j = i;
while (true) {
if (j % 2 == 0) {
break;
}
}
}
System.out.println(i + " " + j);
What is the output of the given code?
Correct
In the first iteration of the for loop, both variables i and j equals to 0. This means the if expression evaluates to true, and the while construct exits as the break statement gets executed.
In the second iteration of the for loop, variable i is increased to 1, then variable j is raised as well. Inside the while loop, the if expression never evaluates to true, meaning the control cannot exit this while construct. As a result, the program runs into an infinite loop.
Incorrect
In the first iteration of the for loop, both variables i and j equals to 0. This means the if expression evaluates to true, and the while construct exits as the break statement gets executed.
In the second iteration of the for loop, variable i is increased to 1, then variable j is raised as well. Inside the while loop, the if expression never evaluates to true, meaning the control cannot exit this while construct. As a result, the program runs into an infinite loop.
Unattempted
In the first iteration of the for loop, both variables i and j equals to 0. This means the if expression evaluates to true, and the while construct exits as the break statement gets executed.
In the second iteration of the for loop, variable i is increased to 1, then variable j is raised as well. Inside the while loop, the if expression never evaluates to true, meaning the control cannot exit this while construct. As a result, the program runs into an infinite loop.
Question 53 of 65
53. Question
Which is not correct about benefits of the modular JDK?
Correct
With the modular JDK, we can create custom runtimes consisting of only modules needed for our apps or the devices we’re targeting. This means the runtime’s size can be much smaller than it was. Option A is incorrect, then.
With the modular JDK, internal APIs used by the platform itself are encapsulated and hidden from applications. Option B is thus incorrect.
When an application fires up, the JVM walks through the module graph. If any module is missing, the JVM produces an error and shuts down. This helps avoid catastrophic consequences if such an issue were only found at runtime. Hence, option C is incorrect.
Incorrect
With the modular JDK, we can create custom runtimes consisting of only modules needed for our apps or the devices we’re targeting. This means the runtime’s size can be much smaller than it was. Option A is incorrect, then.
With the modular JDK, internal APIs used by the platform itself are encapsulated and hidden from applications. Option B is thus incorrect.
When an application fires up, the JVM walks through the module graph. If any module is missing, the JVM produces an error and shuts down. This helps avoid catastrophic consequences if such an issue were only found at runtime. Hence, option C is incorrect.
Unattempted
With the modular JDK, we can create custom runtimes consisting of only modules needed for our apps or the devices we’re targeting. This means the runtime’s size can be much smaller than it was. Option A is incorrect, then.
With the modular JDK, internal APIs used by the platform itself are encapsulated and hidden from applications. Option B is thus incorrect.
When an application fires up, the JVM walks through the module graph. If any module is missing, the JVM produces an error and shuts down. This helps avoid catastrophic consequences if such an issue were only found at runtime. Hence, option C is incorrect.
Question 54 of 65
54. Question
Given:
public class Person {
static var name; // Line 1
var age; // Line 2
public Person(var name) { // Line 3
this.name = name;
}
public static var getName() { // Line 4
return name;
}
public void setAge(var age) { // Line 5
this.age = age;
}
public var getAge() { // Line 6
return age;
}
}
Which line of code successfully compiles?
Which of the following array declarations is valid?
Correct
Options A and C are incorrect as the element types on two sides of the assignment are incompatible.
In option B, the element types on the two sides aren’t the same. However, Integer is a subtype of Number, hence there’s nothing wrong over here.
Option D is incorrect as a two-dimensional array cannot be assigned to a variable of a type which is a one-dimensional array.
Option E is incorrect as the array length on the right-hand side of the assignment must have been left off.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Incorrect
Options A and C are incorrect as the element types on two sides of the assignment are incompatible.
In option B, the element types on the two sides aren’t the same. However, Integer is a subtype of Number, hence there’s nothing wrong over here.
Option D is incorrect as a two-dimensional array cannot be assigned to a variable of a type which is a one-dimensional array.
Option E is incorrect as the array length on the right-hand side of the assignment must have been left off.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Unattempted
Options A and C are incorrect as the element types on two sides of the assignment are incompatible.
In option B, the element types on the two sides aren’t the same. However, Integer is a subtype of Number, hence there’s nothing wrong over here.
Option D is incorrect as a two-dimensional array cannot be assigned to a variable of a type which is a one-dimensional array.
Option E is incorrect as the array length on the right-hand side of the assignment must have been left off.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Question 56 of 65
56. Question
Given:
List list = new ArrayList<>(List.of(1, 2, 3, 4, 5));
System.out.print(list.subList(1, 3).size() + ” elements: “);
System.out.println(list);
What is the output of the given code fragment?
Correct
The subList method returns a view of the portion of the original list, starting at the index specified by the first parameter (inclusive) and ending at the index specified by the second parameter (exclusive).
In the given code, the subList method is called with arguments 1 and 3, meaning the returned view contains two elements at indices 1 and 2. Notice this method doesn’t modify the backing list, hence the list getting printed out is the original one.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#subList(int,int)
Incorrect
The subList method returns a view of the portion of the original list, starting at the index specified by the first parameter (inclusive) and ending at the index specified by the second parameter (exclusive).
In the given code, the subList method is called with arguments 1 and 3, meaning the returned view contains two elements at indices 1 and 2. Notice this method doesn’t modify the backing list, hence the list getting printed out is the original one.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#subList(int,int)
Unattempted
The subList method returns a view of the portion of the original list, starting at the index specified by the first parameter (inclusive) and ending at the index specified by the second parameter (exclusive).
In the given code, the subList method is called with arguments 1 and 3, meaning the returned view contains two elements at indices 1 and 2. Notice this method doesn’t modify the backing list, hence the list getting printed out is the original one.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#subList(int,int)
abstract class Bar extends Foo {
// Line 1
public String x;
// Line 2
public static String y;
// Line 3
static void methodA() { }
// Line 4
abstract void methodB();
}
On which line the @Override annotation can be added?
Correct
The @Override annotation isn’t applicable to fields, hence cannot be added to line 1 or line 2.
Both methods named methodA in the Foo and Bar classes are static, implying the one in the subclass hides the one in the superclass instead of overriding it. The @Override annotation doesn’t apply to method hiding, thus cannot be added to line 3.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Override.html
Incorrect
The @Override annotation isn’t applicable to fields, hence cannot be added to line 1 or line 2.
Both methods named methodA in the Foo and Bar classes are static, implying the one in the subclass hides the one in the superclass instead of overriding it. The @Override annotation doesn’t apply to method hiding, thus cannot be added to line 3.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Override.html
Unattempted
The @Override annotation isn’t applicable to fields, hence cannot be added to line 1 or line 2.
Both methods named methodA in the Foo and Bar classes are static, implying the one in the subclass hides the one in the superclass instead of overriding it. The @Override annotation doesn’t apply to method hiding, thus cannot be added to line 3.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Override.html
Question 58 of 65
58. Question
Given:
package test;
import java.lang.*; // Line 1
public class MyTest {
public static void main(String[] args) {
java.lang.String text = “test”; // Line 2
System.out.println(text);
}
}
Which statement is correct about the given code?
Correct
The java.lang package is imported into all types by default, hence the import statement in the given code can be removed.
Notice types are only loaded when they are first referenced in the code. This means an import statement with the asterisk (*) character doesn’t load all types in a package.
Incorrect
The java.lang package is imported into all types by default, hence the import statement in the given code can be removed.
Notice types are only loaded when they are first referenced in the code. This means an import statement with the asterisk (*) character doesn’t load all types in a package.
Unattempted
The java.lang package is imported into all types by default, hence the import statement in the given code can be removed.
Notice types are only loaded when they are first referenced in the code. This means an import statement with the asterisk (*) character doesn’t load all types in a package.
Question 59 of 65
59. Question
Given:
public class Test {
public static void main(String[] args) {
Test test = new Test();
String[] array = {“Abc”, “aBc”, “abC”};
String string = test.appendCharacter(array);
System.out.println(string);
}
String appendCharacter(String[] array) {
StringBuilder builder = new StringBuilder();
myLabel:
for (String element : array) {
for (int i = 0; i < element.length(); i++) {
char c = element.charAt(i);
if (c < 'A' || c > ‘Z’) continue myLabel;
builder.append(c);
}
}
return builder.toString();
}
}
What is the program’s output?
Correct
When the first array element goes into the inner for loop, its first character, ‘A’, is appended to the StringBuilder object. The second character of this element isn’t in uppercase, hence the continue statement gets executed, skipping the current iteration of the outer for loop.
The first character of the two remaining array elements aren’t in uppercase either. This means the next two iterations of the outer for loop are skipped before any character has a chance to be appended to the string builder.
As a result, the given StringBuilder object contains only a single character – letter ‘A’.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Incorrect
When the first array element goes into the inner for loop, its first character, ‘A’, is appended to the StringBuilder object. The second character of this element isn’t in uppercase, hence the continue statement gets executed, skipping the current iteration of the outer for loop.
The first character of the two remaining array elements aren’t in uppercase either. This means the next two iterations of the outer for loop are skipped before any character has a chance to be appended to the string builder.
As a result, the given StringBuilder object contains only a single character – letter ‘A’.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Unattempted
When the first array element goes into the inner for loop, its first character, ‘A’, is appended to the StringBuilder object. The second character of this element isn’t in uppercase, hence the continue statement gets executed, skipping the current iteration of the outer for loop.
The first character of the two remaining array elements aren’t in uppercase either. This means the next two iterations of the outer for loop are skipped before any character has a chance to be appended to the string builder.
As a result, the given StringBuilder object contains only a single character – letter ‘A’.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Question 60 of 65
60. Question
Given:
public class Test {
static int number;
static public void main(String[] args) {
{
{
int number = 1; // Line 1
}
int number = 2; // Line 2
}
System.out.println(number);
}
}
What is the program’s output?
Correct
A local variable is visible only within the method or block where it’s declared. As a result, the number variable declared on line 1 isn’t visible on line 2 and on the println statement. Likewise, the variable declared on line 2 isn’t visible on the println statement either. Consequently, the number that gets printed is the value of the number static field.
Incorrect
A local variable is visible only within the method or block where it’s declared. As a result, the number variable declared on line 1 isn’t visible on line 2 and on the println statement. Likewise, the variable declared on line 2 isn’t visible on the println statement either. Consequently, the number that gets printed is the value of the number static field.
Unattempted
A local variable is visible only within the method or block where it’s declared. As a result, the number variable declared on line 1 isn’t visible on line 2 and on the println statement. Likewise, the variable declared on line 2 isn’t visible on the println statement either. Consequently, the number that gets printed is the value of the number static field.
Question 61 of 65
61. Question
Given:
public class Person {
static final String name; // Line 1
Person(String name) {
this.name = name; // Line 2
}
public static void main(String[] args) {
Person person1 = new Person(“John”);
Person person2 = new Person(“Jane”);
System.out.println(person1.name); // Line 3
}
}
What is the program’s output?
Correct
When a static field is declared as final, it must be set when the class is loaded. This can be done by initializing the field at the declaration point:
static final String name = “John”;
Or using a static initialization block:
static {
name = “john”;
}
In the given program, the static field name isn’t initialized in either way, leading to a compile-time error at the position it’s declared.
Incorrect
When a static field is declared as final, it must be set when the class is loaded. This can be done by initializing the field at the declaration point:
static final String name = “John”;
Or using a static initialization block:
static {
name = “john”;
}
In the given program, the static field name isn’t initialized in either way, leading to a compile-time error at the position it’s declared.
Unattempted
When a static field is declared as final, it must be set when the class is loaded. This can be done by initializing the field at the declaration point:
static final String name = “John”;
Or using a static initialization block:
static {
name = “john”;
}
In the given program, the static field name isn’t initialized in either way, leading to a compile-time error at the position it’s declared.
Question 62 of 65
62. Question
Given:
List original = new ArrayList<>();
original.add(“A”);
original.add(“A”);
List copy = List.copyOf(original);
copy.remove(“A”);
System.out.println(original);
What is the output of the given code?
String retrieveName() {
return name.toUpperCase();
}
}
Which change must be applied to make the given class adhere to the encapsulation concept?
Correct
When a Person object is created, its name field can only be accessed via the retrieveName method. This means the field and method of such an instance forms a single unit, and the given class is already encapsulated.
Incorrect
When a Person object is created, its name field can only be accessed via the retrieveName method. This means the field and method of such an instance forms a single unit, and the given class is already encapsulated.
Unattempted
When a Person object is created, its name field can only be accessed via the retrieveName method. This means the field and method of such an instance forms a single unit, and the given class is already encapsulated.
Question 64 of 65
64. Question
Given:
public class Test {
static boolean b1;
static Boolean b2;
static boolean[] a1 = new boolean[1];
static Boolean[] a2 = new Boolean[1];
public static void main(String[] args) {
Boolean check;
if (b1 || b2)
check = a1[0] = a2[0];
else if (b1 && b2)
check = a2[0] = a1[0];
else
check = a1[0] == a2[0];
System.out.println(check);
}
}
What is the given program’s output?
Correct
Notice boolean is a primitive type while Boolean is an object reference type. When not explicitly set, a field of the boolean type is initialized to false, but a field of the Boolean type is initialized to null.
In the given program, the field b2 is initialized to null. This null value causes a NullPointerException when the expression b1 || b2 in the if construct is evaluated.
Incorrect
Notice boolean is a primitive type while Boolean is an object reference type. When not explicitly set, a field of the boolean type is initialized to false, but a field of the Boolean type is initialized to null.
In the given program, the field b2 is initialized to null. This null value causes a NullPointerException when the expression b1 || b2 in the if construct is evaluated.
Unattempted
Notice boolean is a primitive type while Boolean is an object reference type. When not explicitly set, a field of the boolean type is initialized to false, but a field of the Boolean type is initialized to null.
In the given program, the field b2 is initialized to null. This null value causes a NullPointerException when the expression b1 || b2 in the if construct is evaluated.
class Bar extends Foo {
static String string = “Bar”;
public static void main(String[] args) {
Bar.print();
System.out.println(new Bar().string);
}
}
What is the given program’s output?
Correct
The Bar class inherits method print from the Foo class, hence there’s nothing wrong with the expression Bar.print(). This method invocation prints the string field defined in the Foo class to the console.
The Bar class has a string field of its own. This field hides the field of the same name in the Foo class. As a result, the second statement in the main method prints the value of the string field in the Bar class.
Incorrect
The Bar class inherits method print from the Foo class, hence there’s nothing wrong with the expression Bar.print(). This method invocation prints the string field defined in the Foo class to the console.
The Bar class has a string field of its own. This field hides the field of the same name in the Foo class. As a result, the second statement in the main method prints the value of the string field in the Bar class.
Unattempted
The Bar class inherits method print from the Foo class, hence there’s nothing wrong with the expression Bar.print(). This method invocation prints the string field defined in the Foo class to the console.
The Bar class has a string field of its own. This field hides the field of the same name in the Foo class. As a result, the second statement in the main method prints the value of the string field in the Bar class.
X
Use Page numbers below to navigate to other practice tests