public class Test {
public static void main(String[] args) {
String result = "";
outer: for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (i == 0) {
if (j == 1) { result += "X"; break outer; }
result += "A" + j;
} else {
result += "B" + j;
}
}
}
System.out.print(result);
}
}
✅ Correct Answer: B) A0X
When `i` is 0 and `j` is 1, 'X' is added to the result, and `break outer` immediately terminates both loops. No further iterations or additions occur.
Q1642easycode error
What is the result of compiling the following Java code?
✅ Correct Answer: A) Compile-time error: Method 'sayHello(String)' is already defined in 'Greeter'.
Method overloading in Java only considers the method name and the types (and order) of its parameters, not the parameter names. Since both methods have the same name ('sayHello') and the same parameter type (String), they are considered to have the same signature, leading to a compile-time error.
Q1643mediumcode error
Examine the following Java code. What compilation error will it produce?
java
import java.util.ArrayList;
import java.util.List;
public class FinalListExample {
public static void main(String[] args) {
final List<String> names = new ArrayList<>();
names.add("Alice");
names = new ArrayList<>(); // Attempt to reassign the final list reference
names.add("Bob");
}
}
✅ Correct Answer: A) Cannot assign a value to final variable 'names'
While 'List' is a mutable interface, the 'names' reference variable is declared as 'final'. This means it cannot be reassigned to point to a new ArrayList object, leading to a compilation error.
Q1644medium
What is the primary difference between calling the `start()` method and directly calling the `run()` method on a `Thread` object in Java?
✅ Correct Answer: A) `start()` executes the `run()` method in a new thread, while direct `run()` executes it in the current thread.
`start()` initiates the execution of the thread, causing the JVM to call the `run()` method in a newly created thread. Directly calling `run()` simply executes the method as a regular method call within the current thread, without creating a new thread.
Q1645hard
Beyond the memory consumed by storing actual `key-value` pairs, what significant memory overhead does a `HashMap` typically incur?
✅ Correct Answer: B) An internal array of `Node` objects (or `TreeNode` objects for treeified buckets), where each `Node` itself has overhead for references and its own fields.
A `HashMap` stores its entries in an array of `Node` (or `TreeNode`) objects. Each `Node` is an object with fields for hash, key, value, and a reference to the next node, incurring memory overhead beyond just the raw key/value data.
Q1646mediumcode error
What is the compilation error in the following code?
java
class Base {
public final void methodA() {
System.out.println("Base methodA");
}
}
class Derived extends Base {
@Override
public void methodA() {
System.out.println("Derived methodA");
}
}
✅ Correct Answer: B) Error: methodA() in Derived cannot override methodA() in Base; overridden method is final
A 'final' method in a superclass cannot be overridden in a subclass. Attempting to do so, even with the same signature and visibility, results in a compilation error.
Q1647hardcode error
What is the compilation error in the provided Java code?
java
class Test {
public static void main(String[] args) {
final int result;
do {
if (Math.random() > 0.5) {
result = 100;
}
} while (false); // Loop executes exactly once
System.out.println(result);
}
}
✅ Correct Answer: A) Variable 'result' might not have been initialized
The `final` variable `result` is conditionally initialized inside the `do` block. Even though the `do-while(false)` loop executes exactly once, the compiler cannot guarantee that the `if` condition will be met during that single execution. Therefore, it's possible for `result` to remain uninitialized before its usage, leading to a "variable might not have been initialized" error.
Q1648easy
Which of the following describes a key characteristic of a custom *unchecked* exception?
✅ Correct Answer: C) It is generally used for programming errors or unexpected states that are not easily recoverable.
Unchecked exceptions (subclasses of `RuntimeException`) are typically used for programming errors like `NullPointerException` or `IllegalArgumentException`, which often indicate defects in the code.
Q1649hardcode error
What is the runtime error when executing this Java code snippet?
java
import java.util.Comparator;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Comparator<String> customComparator = (s1, s2) -> {
if (s1.length() == s2.length()) {
return s1.compareTo(s2);
}
return s1.length() - s2.length();
};
TreeSet<String> set = new TreeSet<>(customComparator);
set.add("A");
set.add(null);
System.out.println(set.size());
}
}
✅ Correct Answer: B) java.lang.NullPointerException
When 'null' is added, the customComparator's compare method is invoked. Inside the comparator, 's1.length()' will be called on a null 's1' (the newly added null element), resulting in a NullPointerException.
Q1650hard
An `ArrayList` is initialized with `new ArrayList<Integer>(5)`. Then 8 elements are added, causing it to resize. After this, `trimToSize()` is called. What is the exact internal capacity of the `ArrayList` immediately after `trimToSize()`?
✅ Correct Answer: B) 8
`trimToSize()` reduces the capacity of the `ArrayList`'s internal array to its current size. Since 8 elements were added, the size is 8, so the capacity will be trimmed to 8.
Q1651hardcode error
What is the runtime error when executing this Java code snippet?
java
import java.util.Comparator;
import java.util.TreeSet;
class RecursiveCompare {
int value;
RecursiveCompare(int value) { this.value = value; }
}
public class Main {
public static void main(String[] args) {
Comparator<RecursiveCompare> buggyComparator = (a, b) -> {
return buggyComparator.compare(b, a); // Infinite recursion
};
TreeSet<RecursiveCompare> set = new TreeSet<>(buggyComparator);
set.add(new RecursiveCompare(1));
set.add(new RecursiveCompare(2));
System.out.println(set.size());
}
}
✅ Correct Answer: A) java.lang.StackOverflowError
The custom comparator 'buggyComparator' recursively calls itself with swapped arguments without a base case or a condition to terminate the recursion. This leads to an infinite loop of method calls on the stack, eventually causing a StackOverflowError when adding the second element.
Q1652hard
Regarding the `final` and `abstract` modifiers in Java, which statement is true?
✅ Correct Answer: B) An `abstract` class can contain `final` methods that cannot be overridden by subclasses.
An `abstract` class can define `final` methods, which ensures specific behavior is inherited without modification. An `abstract` method cannot be `final` as it must be implemented, and a `final` class cannot be `abstract` as it cannot be extended.
Q1653medium
What does `Optional.empty()` represent?
✅ Correct Answer: C) An `Optional` instance that signifies the definite absence of a value.
`Optional.empty()` is a static factory method that returns a singleton empty `Optional` instance, explicitly indicating that no value is present, without being `null` itself.
Q1654easycode output
What will be printed when this Java code is executed?
java
public class Main {
public static void main(String[] args) {
int x = 10;
x = 20;
System.out.println(x);
}
}
✅ Correct Answer: A) 20
The variable `x` is first initialized to 10 and then re-assigned to 20. The `System.out.println()` statement prints the most recent value stored in `x`.
The `createNewFile()` method requires that the parent directory of the file already exists. If the parent directory does not exist, an `IOException` is thrown, as indicated by the output. The message will likely refer to the missing directory.
Q1656medium
What is the fundamental difference in control flow between using `throw` and `return` in a method?
✅ Correct Answer: C) `throw` causes an abrupt termination of the current execution path and initiates exception handling, while `return` exits the method normally and passes control back to the caller.
`throw` transfers control to the nearest exception handler up the call stack, effectively terminating the current path. `return` exits the method normally, passing a value (if any) back to the caller and continuing normal execution.
Q1657easy
Which method checks if a string contains a specified sequence of characters?
✅ Correct Answer: C) contains(CharSequence s)
The `contains()` method returns true if this string contains the specified sequence of character values.
Q1658easycode output
What is the output of this Java code snippet?
java
import java.io.*;
class Inner implements Serializable {
private String innerValue;
public Inner(String v) { this.innerValue = v; }
public String getInnerValue() { return innerValue; }
}
class Outer implements Serializable {
private String outerValue;
private Inner innerObject;
public Outer(String o, String i) {
this.outerValue = o;
this.innerObject = new Inner(i);
}
public String getCombinedValue() {
return outerValue + "-" + innerObject.getInnerValue();
}
}
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Outer outer = new Outer("OuterData", "InnerData");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(outer);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Outer deserializedOuter = (Outer) ois.readObject();
ois.close();
System.out.println(deserializedOuter.getCombinedValue());
}
}
✅ Correct Answer: A) OuterData-InnerData
If an object contains references to other serializable objects, those objects are also automatically serialized as part of the object graph. Both `Outer` and `Inner` implement `Serializable`, so their states are preserved.
Q1659medium
If a variable is declared within the body of a `while` loop (e.g., `int x = 0;`), what is its scope?
✅ Correct Answer: B) It is accessible only within the current iteration of the loop body.
Variables declared inside the block of a loop (or any block) have block scope. They are created and exist only for the duration of that specific block's execution, meaning they are accessible only within the current iteration of the loop body.
Q1660medium
Which built-in functional interface is best suited for scenarios where you need to generate or supply a value without taking any input?
✅ Correct Answer: C) `java.util.function.Supplier<T>`
The `Supplier<T>` interface defines the abstract method `T get()`, which takes no arguments and returns a value of type T, making it perfect for scenarios requiring value generation or supply.