What is the main benefit of providing a `Throwable cause` in a custom exception's constructor?
✅ Correct Answer: B) It allows for exception chaining, preserving the original root cause of the problem.
Providing a `Throwable cause` allows for exception chaining. This means a new exception can wrap an existing one, preserving the original cause of the error which is invaluable for debugging and understanding complex error flows.
Q2142hardcode output
What is the output of this code?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<String> list1 = new LinkedList<>();
list1.add("A");
list1.add(null);
list1.add("B");
list1.add(null);
list1.add("C");
LinkedList<String> list2 = new LinkedList<>();
list2.add(null);
list2.add("B");
list2.add("D");
list1.removeAll(list2);
System.out.println(list1);
}
}
✅ Correct Answer: C) [A, C]
`removeAll()` removes all elements from `list1` that are also contained in `list2`. Both `null` and `"B"` are present in `list2`, so all occurrences of `null` and `"B"` are removed from `list1`.
Q2143hard
You are developing a reactive microservice using `CompletableFuture` for asynchronous operations. A custom checked exception, `DataProcessingException`, can be thrown by a future. What is the most appropriate way to ensure `DataProcessingException` is propagated and handled correctly at the end of an asynchronous chain, rather than being wrapped in an `CompletionException` or `ExecutionException` without preserving its original type?
✅ Correct Answer: D) The `CompletableFuture` API will always wrap checked exceptions in `CompletionException` or `ExecutionException`, so direct propagation of the original checked type is not natively supported without unwrapping.
`CompletableFuture` and `ExecutorService` (when wrapping `Callable`) inherently wrap checked exceptions thrown during their execution within `CompletionException` or `ExecutionException`. To retrieve the original custom checked exception, you must catch these wrapper exceptions and inspect their `getCause()`.
Q2144easycode error
What will happen when this Java code is compiled?
java
public class MyClass {
public static void main(String[] args) {
double salary = 50000.75;
int annualSalary = salary;
System.out.println(annualSalary);
}
}
✅ Correct Answer: B) A compilation error: incompatible types: possible lossy conversion from double to int.
Assigning a double value to an int variable without an explicit cast is a narrowing primitive conversion that Java considers a potential loss of precision. This results in a compile-time error.
Q2145hardcode output
What is the output of the following Java code?
java
class Super {
public final void foo() { System.out.println("Super foo"); }
public static void bar() { System.out.println("Super bar"); }
}
class Sub extends Super {
// Cannot override foo() - it's final
public static void bar() { System.out.println("Sub bar"); }
}
public class Main {
public static void main(String[] args) {
Super s = new Sub();
s.foo();
s.bar();
Sub.bar();
}
}
✅ Correct Answer: A) Super foo
Super bar
Sub bar
Final methods cannot be overridden, so `s.foo()` calls `Super.foo()`. Static methods are hidden, not overridden; `s.bar()` calls `Super.bar()` based on the reference type, while `Sub.bar()` explicitly calls the `Sub`'s static method.
Q2146hardcode error
What is the output of this code?
java
public class Main {
public static void main(String[] args) {
Object lock = new Object();
System.out.println("Attempting to wait...");
try {
lock.wait(); // Calling wait() without owning the monitor
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("Done.");
}
}
✅ Correct Answer: A) Attempting to wait...
Exception in thread "main" java.lang.IllegalMonitorStateException
The `wait()` method can only be called by the thread that owns the monitor of the object (i.e., inside a `synchronized` block on that object). Calling it outside will throw an `IllegalMonitorStateException`.
Q2147easy
What is the requirement for the values used in `case` labels?
✅ Correct Answer: B) They must be constant expressions that can be evaluated at compile time.
Case labels must be constant expressions that can be resolved at compile time. This means they can be literals, final variables, or expressions involving only literals and final variables.
Q2148mediumcode error
What will be the compilation error in this code?
java
import java.io.IOException;
class Reader {
public void readData() throws IOException {
System.out.println("Reading data...");
}
}
class FileReader extends Reader {
@Override
public void readData() throws Exception {
System.out.println("Reading file data...");
}
}
✅ Correct Answer: A) Error: readData() in FileReader cannot override readData() in Reader; overridden method does not throw Exception
An overriding method can declare fewer or the same checked exceptions, or a subclass of the checked exceptions thrown by the superclass method. It cannot declare new, broader, or unrelated checked exceptions. 'Exception' is a broader exception than 'IOException'.
Q2149mediumcode error
What is the compile-time error in the following Java code?
java
class SuperClass {
public SuperClass(int x) {
System.out.println("SuperClass constructor: " + x);
}
}
class SubClass extends SuperClass {
public SubClass() {
System.out.println("SubClass constructor");
}
}
public class ConstructorError1 {
public static void main(String[] args) {
new SubClass();
}
}
✅ Correct Answer: A) Error: no suitable constructor found for SuperClass()
The subclass constructor `SubClass()` implicitly calls `super()`. However, `SuperClass` only defines a parameterized constructor `SuperClass(int x)` and no no-argument constructor. Thus, the implicit `super()` call in `SubClass()` fails during compilation.
Q2150easy
Which keyword is used to refer to the current object within an instance method or constructor of a class?
✅ Correct Answer: B) `this`
The `this` keyword refers to the current object, allowing differentiation between instance variables and local variables with the same name, or calling another constructor in the same class.
Q2151mediumcode error
What compilation error will this Java code produce?
java
public class SwitchError {
public static void main(String[] args) {
char grade = 'A';
if (grade == 'A' || grade == 'B') {
int result = switch (grade) {
case 'A' -> {
System.out.println("Excellent!");
yield 100;
}
case 'B' -> {
System.out.println("Good!");
break; // Incorrect usage within a switch expression
}
default -> 0;
};
System.out.println("Score: " + result);
}
}
}
✅ Correct Answer: C) Error: switch expression does not complete normally (missing yield or default)
In a switch expression, each case block that uses a statement block (`{...}`) must either `yield` a value or throw an exception. A plain `break;` statement does not yield a value, making the `case 'B'` branch incomplete for the expression.
Q2152hard
Why would a developer choose `appendCodePoint(int codePoint)` over `append(char c)` or `append(String str)` when working with `StringBuffer`?
✅ Correct Answer: B) To ensure correct handling and representation of Unicode supplementary characters (code points greater than `U+FFFF`).
`appendCodePoint()` is crucial for correctly handling Unicode supplementary characters, which require two `char` values (a surrogate pair) for their representation in Java's UTF-16 encoding. It ensures that such code points are correctly appended as a single logical unit, unlike `append(char)` which only appends a single `char`.
Q2153medium
Under what condition does the Java compiler automatically provide a default constructor for a class?
✅ Correct Answer: B) Only when the class contains no explicit constructors.
The Java compiler inserts a public, no-argument default constructor into a class if and only if no other constructors (either no-argument or parameterized) are explicitly defined by the programmer.
Q2154mediumcode error
What is the error in this Java code?
java
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static ArrayList getMixedList() {
ArrayList rawList = new ArrayList();
rawList.add("Hello");
rawList.add(123); // Integer
return rawList;
}
public static void main(String[] args) {
List<String> myStrings = getMixedList(); // Unchecked warning, not an error
String first = myStrings.get(0);
String second = myStrings.get(1); // Error occurs here
System.out.println(first + second);
}
}
✅ Correct Answer: C) Runtime Error: `ClassCastException`.
When `getMixedList()` returns a raw `ArrayList` containing both `String` and `Integer` objects, and it's assigned to `List<String>`, an unchecked warning occurs. Later, when attempting to cast the `Integer` at index 1 to a `String` (during `String second = myStrings.get(1);`), a `ClassCastException` occurs at runtime.
Q2155mediumcode error
What error will occur when compiling this Java code?
java
public class ConditionCheck {
public static void main(String[] args) {
String message;
if (true) {
String greeting = "Hello";
message = greeting;
}
System.out.println(greeting);
}
}
✅ Correct Answer: A) error: cannot find symbol variable greeting
The variable `greeting` is declared within the scope of the `if` block. It is not accessible outside that block, leading to a compile-time error when `System.out.println(greeting)` attempts to use it.
Q2156mediumcode error
Which of the following describes the error in the given Java code?
java
public class Test {
public static void main(String[] args) {
myBlock: {
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue myBlock;
}
System.out.print(i);
}
}
}
}
✅ Correct Answer: A) Compile-time error: label 'myBlock' must be a loop or switch label for 'continue'.
A labeled `continue` statement can only jump to a label that marks an enclosing loop. Here, `myBlock` labels a simple block of code, not a loop, thus `continue myBlock` causes a compile-time error.
Q2157easy
Which of the following interfaces does `TreeMap` implement to guarantee its sorted nature?
✅ Correct Answer: B) SortedMap
`TreeMap` implements the `SortedMap` interface, which extends `Map` and provides methods for maintaining a sorted order of its keys.
Q2158hardcode output
What is the output of this code?
java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add(null);
list.add("B");
list.add(null);
list.add("C");
boolean removed1 = list.remove(null);
boolean removed2 = list.remove("B");
boolean removed3 = list.remove(null);
System.out.println(list.size() + ":" + removed1 + ":" + removed2 + ":" + removed3);
}
}
✅ Correct Answer: A) 2:true:true:true
`list.remove(Object o)` removes the first occurrence of the specified object. Initially `[A, null, B, null, C]`. First `remove(null)` removes the null at index 1, list becomes `[A, B, null, C]`. Then `remove("B")` removes `B`, list becomes `[A, null, C]`. Finally, the last `remove(null)` removes the remaining null, list becomes `[A, C]`. All `remove` operations were successful, returning `true`.
Q2159hard
Given `Number num = 10;`, which of the following explicit casts will compile successfully but throw a `ClassCastException` at runtime?
✅ Correct Answer: B) `(Long) num`
`Number num = 10;` autoboxes `10` into an `Integer` object, so `num` actually holds an `Integer`. Casting `num` to `Long` will compile because `Integer` and `Long` are both `Number` types, but it will fail at runtime with a `ClassCastException` because an `Integer` object cannot be directly cast to a `Long` object. Options c and d involve unboxing/primitive conversion, not object casting.
Q2160hard
`java.util.concurrent.locks.StampedLock` introduces an "optimistic read" mode. What is the primary characteristic of this mode?
✅ Correct Answer: B) It attempts to read data without acquiring any lock, then validates if the data was modified during the read operation.
Optimistic read in `StampedLock` starts by reading data without acquiring a lock. It then obtains a 'stamp' and later `validate()`s it to check if any write occurred during the read, requiring a retry if validation fails. This can offer higher throughput for very short, contention-free reads.