When an exception is caught and then re-thrown wrapped within a new, different exception (i.e., exception chaining), how does the `finally` block interact with this process?
✅ Correct Answer: A) The `finally` block executes, and then the *newly wrapped* exception propagates.
The `finally` block executes before the method exits, regardless of whether an exception is caught, re-thrown, or wrapped and re-thrown. After `finally` completes, the chained (newly wrapped) exception continues its propagation.
Q2322medium
Regarding local variables accessed within a lambda expression, what is the key restriction they must adhere to?
✅ Correct Answer: B) They must be `final` or effectively final.
Lambda expressions can capture local variables from their enclosing scope, but these variables must be final or effectively final, meaning their value cannot change after initialization.
Q2323hardcode error
What is the error in the following Java code?
java
class MyData {
int value;
public MyData(int value) { this.value = value; }
@Override
public boolean equals(MyData other) { // Wrong parameter type for equals()
if (other == null || getClass() != other.getClass()) return false;
return this.value == other.value;
}
}
✅ Correct Answer: C) Compilation Error: `method does not override or implement a method from a supertype`.
The `equals` method from `java.lang.Object` has a signature `public boolean equals(Object obj)`. When attempting to override it, the parameter type must be `Object`. Using `MyData` as the parameter creates an overloaded method, not an override. The `@Override` annotation then correctly flags this as a compile-time error.
Q2324hard
In a `switch` expression using pattern matching (Java 17+), what is the primary purpose of adding a `when` clause to a `case` label (e.g., `case Integer i when i > 0 -> ...`)?
✅ Correct Answer: B) To define an additional boolean condition that must be true for the `case` to match.
The `when` clause in a pattern matching `switch` allows for a guarded pattern. It provides an additional boolean condition that must evaluate to `true` in conjunction with the type pattern matching for that specific `case` to be selected.
Q2325easycode output
What will be the output of this nested loop structure?
java
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break;
}
System.out.print("(" + i + "," + j + ")");
}
}
}
}
✅ Correct Answer: A) (0,0)(1,0)
The 'break' statement terminates the innermost loop (the 'j' loop) when 'j' becomes 1. The outer loop continues to its next iteration. So, for each 'i', only 'j=0' is processed.
Q2326hardcode error
What is the error in the following Java code?
java
class SecretAgent {
private void confidential() {
System.out.println("Top Secret");
}
}
class DoubleAgent extends SecretAgent {
@Override
public void confidential() { // Attempting to override private method
System.out.println("Compromised Secret");
}
}
✅ Correct Answer: C) Compilation Error: `method does not override or implement a method from a supertype`.
Private methods are not visible to subclasses and thus cannot be overridden. Using `@Override` on a method that does not actually override a superclass method will result in a compile-time error.
Q2327hardcode output
What does this code print?
java
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String data = "12345";
BufferedReader br = new BufferedReader(new StringReader(data));
char[] buf = new char[10];
int bytesRead = br.read(buf, 2, 3);
System.out.println("Read: " + bytesRead);
System.out.println("Buf: " + new String(buf, 0, 5));
br.close();
}
}
✅ Correct Answer: A) Read: 3
Buf: \u0000\u0000123
The `read(char[] cbuf, int off, int len)` method reads characters into the specified buffer `cbuf`, starting at the offset `off` for a maximum of `len` characters. Here, 3 characters ('1', '2', '3') are read into `buf` starting at index 2. The first two positions of `buf` remain null characters (\u0000).
Q2328easy
How would you define a lambda expression that takes no parameters and prints 'Hello World' to the console?
✅ Correct Answer: B) `() -> System.out.println("Hello World");`
For a lambda expression with no parameters, an empty pair of parentheses `()` is used before the arrow token `->`.
Q2329medium
What is the primary purpose of the `java.io.FileWriter` class?
✅ Correct Answer: C) To write character streams to a file.
`FileWriter` is a convenience class for writing character files. It is designed to write text data, converting characters into bytes using the platform's default charset.
Q2330easycode output
What does this code print?
java
class DataProcessingException extends Exception {
public DataProcessingException(String message) {
super(message);
}
}
public class Main {
public static void process(int value) throws DataProcessingException {
if (value < 0) {
throw new DataProcessingException("Negative value not allowed");
}
System.out.println("Data processed successfully: " + value);
}
public static void main(String[] args) {
try {
process(10);
} catch (DataProcessingException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Data processed successfully: 10
The `process` method is called with a positive value (10), so no exception is thrown. The method executes normally, printing 'Data processed successfully: 10'.
Q2331hard
Consider an `Iterator<Integer> it = new ArrayList<>(Arrays.asList(1, 2, 3)).iterator();`. If, within the lambda expression passed to `it.forEachRemaining()`, a structural modification to the underlying `ArrayList` is attempted (e.g., `list.add(4)`), what is the expected outcome?
✅ Correct Answer: C) A `ConcurrentModificationException` will be thrown by the `forEachRemaining()` method, terminating the iteration.
The `forEachRemaining()` method, like `next()` and `hasNext()`, is subject to the fail-fast behavior of standard Java collection iterators. If the underlying collection is structurally modified externally (including within the lambda itself) after the iterator is created and before `forEachRemaining()` completes, a `ConcurrentModificationException` will be thrown.
Q2332mediumcode output
What does this Java code snippet print, or what exception does it throw?
java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
try {
for (String s : list) {
if (s.equals("B")) {
list.remove(s);
}
}
System.out.println("No exception: " + list);
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
✅ Correct Answer: A) ConcurrentModificationException
Modifying an `ArrayList` directly (using `list.remove()`) while iterating over it with a for-each loop (which uses an implicit iterator) causes a `ConcurrentModificationException`.
Q2333hard
What is the primary reason an `ArrayList`'s standard `Iterator` is considered 'fail-fast'?
✅ Correct Answer: B) It quickly detects and throws a `ConcurrentModificationException` if the list is structurally modified by another means during iteration.
A fail-fast iterator detects structural modifications (add, remove) to the underlying collection from outside the iterator itself and throws a `ConcurrentModificationException` immediately, rather than risking undefined behavior later.
Q2334hard
Consider a scenario where a producer thread needs to hand off a single item to a consumer thread, blocking until the consumer is ready to receive it, and vice versa. Which `BlockingQueue` implementation is specifically designed for this synchronous hand-off without buffering any elements?
✅ Correct Answer: C) `SynchronousQueue`.
SynchronousQueue is a unique blocking queue that has zero capacity. An `offer` operation must wait for a `take` operation by another thread, and vice-versa. It's essentially a hand-off point for one-to-one communication.
Q2335hard
Given an `ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));` and a `ListIterator<String> lit = list.listIterator();`. If the sequence of operations is `lit.next(); lit.add("D"); lit.next();`, what will be the value returned by `lit.previous()` immediately after this sequence?
✅ Correct Answer: B) "B"
After `lit.next()`, the cursor is between "A" and "B". `lit.add("D")` inserts "D" at the current cursor position, making the list `["A", "D", "B", "C"]`, and the cursor advances past "D" to be between "D" and "B". The subsequent `lit.next()` returns "B". Then, `lit.previous()` returns "B".
Q2336medium
What is the primary implication of declaring a class as `final`?
✅ Correct Answer: C) It cannot be extended (subclassed).
A `final` class cannot be extended, preventing other classes from inheriting from it. While its methods cannot be overridden because it can't be extended, the primary implication is the prevention of subclassing.
Q2337hardcode error
What error occurs when running this Java code?
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class SubListCME {
public static void main(String[] args) {
List<String> mainList = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
List<String> subList = mainList.subList(1, 3); // View of [B, C]
Iterator<String> subListIterator = subList.iterator();
mainList.add("E"); // Modifies mainList, impacting subList's expected size/structure
while (subListIterator.hasNext()) {
System.out.println(subListIterator.next()); // Error on next()
}
}
}
✅ Correct Answer: A) java.util.ConcurrentModificationException
A subList is a view of the original list. Modifying the mainList structurally (mainList.add("E")) while iterating over a subList's iterator causes a ConcurrentModificationException due to the fail-fast behavior.
Q2338hardcode output
What is the output of this code?
java
public class VolatileSyncTest {
private volatile int count = 0;
private final Object lock = new Object();
public void increment() {
for (int i = 0; i < 1000; i++) {
synchronized (lock) { // Synchronizing 'this' (the object instance)
count++;
}
}
}
public static void main(String[] args) throws InterruptedException {
VolatileSyncTest test = new VolatileSyncTest();
Thread t1 = new Thread(test::increment);
Thread t2 = new Thread(test::increment);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(test.count);
}
}
✅ Correct Answer: A) 2000
Even though `count` is `volatile`, the `count++` operation is not atomic. However, wrapping it in a `synchronized` block makes each increment atomic and visible, ensuring a correct final count of 2000. The `volatile` keyword here is redundant for atomicity but does not cause issues.
Q2339mediumcode error
What kind of error will occur when compiling this Java code?
java
public class ArrayError {
public static void main(String[] args) {
double[] dArr = {1.0, 2.0};
int[] iArr = dArr;
System.out.println(iArr[0]);
}
}
✅ Correct Answer: A) Compile-time error: 'incompatible types: double[] cannot be converted to int[]'.
Arrays of different primitive types are not assignment-compatible even if the primitive types themselves are. An array of `double` cannot be directly assigned to a reference of an `int` array. This will cause a compile-time error due to incompatible types.
Q2340easycode error
What kind of error will occur when compiling this Java code?
java
public class Main {
public static void main(String[] args) {
break;
}
}
✅ Correct Answer: A) A compile-time error
The 'break' statement must be inside a loop or a switch statement. Placing it directly in a method causes a compile-time error.