In an inheritance hierarchy, when is the constructor of a superclass invoked relative to the subclass constructor?
✅ Correct Answer: B) The superclass constructor is invoked before any statements in the subclass constructor execute.
Due to constructor chaining (explicit `this()` or `super()`, or implicit `super()`), the superclass constructor is always invoked and completes its execution before any other statements in the subclass constructor body are executed.
Q2242hard
Consider a Java array declared as `String[] names;`. Which statement accurately describes `names`?
✅ Correct Answer: B) `names` is a reference variable that points to an array object on the heap, which itself holds references to `String` objects (or `null`).
In Java, arrays are objects. An array variable like `String[] names` is a reference that points to the actual array object on the heap, which then stores references to its elements.
Q2243easy
What is the primary purpose of the `java.io.File` class in Java?
✅ Correct Answer: B) To represent file and directory pathnames in a platform-independent manner.
The `java.io.File` class is used to represent files and directories as abstract pathnames, providing methods to manipulate their properties and check their existence, but not their content.
✅ Correct Answer: A) In try
In catch
In finally
Caught
An exception is thrown in the 'try' block, which is caught by the 'catch' block. The 'finally' block then executes after the 'catch' block, but before the method returns its value.
Q2245easycode error
What is the result of compiling and executing this Java code?
java
public class FinalParameterReassignment {
public void modify(final String param) {
param = "new value";
System.out.println(param);
}
public static void main(String[] args) {
new FinalParameterReassignment().modify("original");
}
}
✅ Correct Answer: A) Compile-time error: "The final parameter param cannot be assigned."
When a method parameter is declared as `final`, its reference (or value, for primitives) cannot be reassigned within the method body.
Q2246easycode error
What will be the result of attempting to compile and run this Java code?
java
public class MyClass {
public static void main(String[] args) {
String status = null;
switch (status) {
case "READY":
System.out.println("Status is Ready");
break;
default:
System.out.println("Unknown Status");
}
}
}
✅ Correct Answer: C) Runtime error: java.lang.NullPointerException
If the 'switch' expression evaluates to 'null' (and it's not a switch expression with pattern matching that explicitly handles null, which is for later Java versions), a 'NullPointerException' is thrown at runtime.
Q2247easycode error
What compile-time error will occur when compiling this Java code?
java
public class MyClass {
public static void main(String[] args) {
long id = 100L;
switch (id) {
case 100L:
System.out.println("ID is 100");
break;
default:
System.out.println("Other ID");
}
}
}
✅ Correct Answer: B) Compile-time error: Incompatible types. Found: 'long', Required: 'char, byte, short, int, Character, Byte, Short, Integer, String, or an enum'
The 'switch' statement in Java does not support 'long' as a controlling expression type. It only accepts char, byte, short, int, their wrapper types, String, or enums.
Q2248hardcode error
What compilation error will this Java code produce?
java
class Test {
public static void main(String[] args) {
int j = 0;
do {
j++;
if (j == 2) {
continue OUTER_LOOP;
}
} while (j < 5);
System.out.println("Final j: " + j);
}
}
✅ Correct Answer: A) Label 'OUTER_LOOP' not found
The `continue` statement with a label must target an existing enclosing labeled loop. In this code, `OUTER_LOOP` is not defined, leading to a "label not found" compile-time error.
Q2249mediumcode error
What error will this Java code produce?
java
public class ArrayError {
public static void main(String[] args) {
int[][] arr = new int[2][2] { {1,2}, {3,4} };
System.out.println(arr[0][0]);
}
}
✅ Correct Answer: A) Compile-time error: array dimension cannot be specified when an initializer expression is provided
When an array initializer block (e.g., `{ {1,2}, {3,4} }`) is used, you cannot specify the dimensions (e.g., `[2][2]`) for the array in the `new` expression. You must choose one method of initialization.
Q2250mediumcode output
What does this code print?
java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie", "David"));
Iterator<String> it = names.iterator();
it.next(); // Advance once
it.next(); // Advance twice
StringBuilder sb = new StringBuilder();
it.forEachRemaining(name -> sb.append(name).append(" "));
System.out.println(sb.toString().trim());
}
}
✅ Correct Answer: A) Charlie David
The `forEachRemaining()` method processes all elements from the current position of the iterator to the end. Since `next()` was called twice, 'Alice' and 'Bob' are skipped, and 'Charlie' and 'David' are processed.
Q2251easy
Can `TreeMap` store `null` values?
✅ Correct Answer: B) Yes, it can store `null` values.
While `TreeMap` does not allow `null` keys, it does permit `null` values to be associated with non-`null` keys.
Q2252easycode output
What is the output of the following Java program?
java
public class Main {
public static void main(String[] args) {
int count = 0;
while (count < 5) {
if (count == 3) {
break;
}
System.out.print(count + "");
count++;
}
}
}
✅ Correct Answer: A) 012
The 'while' loop continues as long as 'count' is less than 5. When 'count' reaches 3, the 'break' statement terminates the loop, so 0, 1, and 2 are printed.
Q2253hardcode error
What is the error encountered when compiling this Java code?
java
public class ArraySyntaxError {
public static void main(String[] args) {
int[] numbers;
numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]);
}
}
✅ Correct Answer: A) Compile-time error: Array initializer is not allowed here
An array initializer shorthand `{1, 2, 3, ...}` can only be used in conjunction with an array declaration (e.g., `int[] numbers = {1, 2, 3};`). It cannot be used as a standalone statement to assign values to an already declared array variable. For assignment after declaration, you must use `new int[]{1, 2, 3, 4, 5};`.
Q2254easycode error
What is the error in the following Java code?
java
public class Main {
public static void main(String[] args) {
int x = 100;
Integer y = (Integer) x;
System.out.println(y);
}
}
✅ Correct Answer: A) Compile-time error: Incompatible types: int cannot be converted to java.lang.Integer.
While Java supports autoboxing (int to Integer implicitly), an explicit cast from a primitive type (int) to its wrapper class (Integer) is not allowed directly and causes a compile-time error.
Q2255easycode output
What is the output of this code?
java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
Iterator<String> it = names.iterator();
System.out.print(it.next());
System.out.print("-" + it.next());
}
}
✅ Correct Answer: A) Alice-Bob
The `next()` method returns the next element in the iteration. The first call returns 'Alice', and the second call returns 'Bob', which are then concatenated with a hyphen and printed.
Q2256medium
Consider `ClassA` and `ClassB` where `ClassB extends ClassA`. If you have `ClassA obj = new ClassB();`, which statement is true?
✅ Correct Answer: C) `obj` can access methods defined in `ClassA`, and if overridden in `ClassB`, the `ClassB` version will be executed.
This is an example of polymorphism and upcasting. The reference type `ClassA` determines which methods can be called, but the actual object type `ClassB` determines which implementation of an overridden method is executed.
Q2257hardcode error
What kind of runtime error or unexpected behavior will occur when running this Java code, primarily related to thread lifecycle?
java
public class InterruptionTest implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(100); // TIMED_WAITING state
System.out.println("Working...");
} catch (InterruptedException e) {
// Swallowing the exception without handling or re-interrupting
System.out.println("Interrupted, but continuing...");
}
}
System.out.println("Thread finished.");
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new InterruptionTest());
t.start();
Thread.sleep(200); // Give it time to work
t.interrupt(); // Interrupt the thread
Thread.sleep(300); // Give it time to react (or not)
}
}
✅ Correct Answer: C) The thread will enter an infinite loop of 'Working...' and 'Interrupted, but continuing...'.
When `Thread.sleep()` is interrupted, it throws `InterruptedException` and clears the thread's interrupted status. If the `catch` block simply swallows the exception without calling `Thread.currentThread().interrupt()` to re-assert the interruption, the `while (!Thread.currentThread().isInterrupted())` condition will become true again, causing the thread to continue its loop indefinitely.
Q2258hard
When an immutable class needs to be serializable, what special consideration must be taken regarding its `readObject` method (or `readResolve`) to preserve immutability during deserialization?
✅ Correct Answer: B) The `readObject` method must carefully validate the deserialized state and perform defensive copies of any mutable fields to prevent external modification immediately after deserialization.
The `readObject` method (or `readResolve` for canonical instances) must perform the same defensive copying and validation as the constructor to ensure that the deserialized object is truly immutable and not susceptible to state changes by the deserialization stream or subsequent references.
Q2259medium
Which statement accurately describes the element order in a `HashSet`?
✅ Correct Answer: C) No specific order is guaranteed; it may change over time.
`HashSet` does not maintain any insertion order, natural sorted order, or any other specific order of its elements. The order can even change with structural modifications.
Q2260medium
In which scenario is `orElseThrow()` the most suitable method to use with an `Optional`?
✅ Correct Answer: B) When the absence of a value indicates an exceptional situation that should halt program execution or be handled by an exception mechanism.
`orElseThrow()` is appropriate when a missing value is considered an error condition. It allows you to throw a specific exception if the `Optional` is empty, signaling an abnormal program state.