A thread explicitly calls `java.util.concurrent.locks.LockSupport.park()`. Assuming no unparking event or interrupt has occurred, what is the immediate state of this thread?
✅ Correct Answer: C) WAITING
`LockSupport.park()` is a low-level primitive for blocking a thread. When called without a timeout, it places the thread into the `WAITING` state until it is unparked or interrupted.
Q1402mediumcode error
What error occurs when compiling this Java code?
java
public class LoopTest {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 3)
System.out.println("Finished");
}
}
✅ Correct Answer: C) error: ';' expected
The 'do-while' loop in Java requires a semicolon after the 'while' condition. Missing it results in a compile-time syntax error.
Q1403easy
What happens if an explicit cast from a `long` to an `int` results in a value larger than `int` can hold?
✅ Correct Answer: B) The value is silently truncated or wrapped around.
When a `long` value that is too large for an `int` is explicitly cast, the higher-order bits are truncated, leading to a silent loss of data and a potentially unexpected value due to wrapping.
Q1404medium
You have an `Optional<Integer>` and you only want to proceed with further operations if the integer value is greater than 10. Which `Optional` method should you use for this conditional check?
✅ Correct Answer: D) `filter()`
The `filter()` method is used to apply a predicate to the contained value. If the value is present and matches the predicate, it returns an `Optional` with that value; otherwise, it returns an empty `Optional`.
Q1405hard
Relative to `HashMap` storing the same number of entries, `TreeMap` typically has:
✅ Correct Answer: C) Significantly higher memory overhead.
`TreeMap` is implemented using a Red-Black Tree, where each entry is a node object storing multiple references. This pointer-heavy structure generally results in a higher memory footprint per entry compared to `HashMap`, which uses an array of linked lists/trees.
Q1406hardcode output
What is the output of this code?
java
public class Q4_InterruptWait {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
synchronized (lock) {
try {
System.out.println("T: Waiting.");
lock.wait();
} catch (InterruptedException e) {
System.out.println("T: Interrupted while waiting.");
Thread.currentThread().interrupt();
}
System.out.println("T: Resumed/Finished.");
}
});
t.start();
Thread.sleep(50);
System.out.println("Main: T state (before interrupt): " + t.getState());
t.interrupt();
Thread.sleep(50);
System.out.println("Main: T state (after interrupt): " + t.getState());
}
}
✅ Correct Answer: A) T: Waiting.
Main: T state (before interrupt): WAITING
T: Interrupted while waiting.
T: Resumed/Finished.
Main: T state (after interrupt): TERMINATED
Thread `t` enters `WAITING` state after calling `lock.wait()`. When `t.interrupt()` is called, an `InterruptedException` is thrown, `t` handles it, prints its messages, and then `run()` completes, making its final state `TERMINATED`.
Q1407hard
When constructing a `BufferedReader` with an `InputStreamReader`, what is the most robust way to ensure correct character decoding from the underlying byte stream, especially when dealing with non-platform-default encodings?
✅ Correct Answer: B) Explicitly specifying the character set in the `InputStreamReader` constructor (e.g., `new InputStreamReader(is, StandardCharsets.UTF_8)`).
Explicitly specifying the `Charset` in the `InputStreamReader` constructor guarantees that the correct encoding is used for byte-to-character conversion, preventing issues with platform-dependent default encodings.
Q1408easy
What is the effect of calling the `delete()` method on a `File` object?
✅ Correct Answer: B) It attempts to delete the file or directory denoted by this abstract pathname.
The `delete()` method attempts to delete the file or directory specified by the `File` object. It returns true on success, false on failure.
Q1409medium
Which built-in functional interface is primarily used for evaluating a boolean condition on a given input?
✅ Correct Answer: A) `java.util.function.Predicate`
The `Predicate<T>` interface defines a single abstract method `boolean test(T t)` which is used to test an input against a condition and return a boolean result.
Q1410mediumcode error
What is the compile-time error in this Java code?
java
import java.util.function.Consumer;
public class LambdaError {
public static void main(String[] args) {
Object obj = (String s) -> System.out.println(s);
}
}
✅ Correct Answer: A) A lambda expression cannot be assigned directly to the `Object` type; it must be assigned to a functional interface.
Lambda expressions are implicitly converted to instances of functional interfaces. They cannot be directly assigned to a general type like `Object` because the compiler needs a specific target functional interface to infer the lambda's signature.
Q1411easycode output
What does this code print?
java
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> cities = new HashSet<>();
cities.add("New York");
cities.add("London");
cities.clear();
System.out.println(cities.isEmpty());
}
}
✅ Correct Answer: A) true
The `clear()` method removes all elements from the HashSet. After calling `clear()`, the set becomes empty, so `isEmpty()` returns `true`.
Q1412hardcode output
What is the output of this code?
java
public class Q1_ThreadStateWaitNotify {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
t.start();
Thread.sleep(50); // Give t time to enter WAITING
System.out.println(t.getState()); // State 1
synchronized (lock) {
lock.notify();
}
Thread.sleep(50); // Give t time to resume and possibly terminate
System.out.println(t.getState()); // State 2
}
}
✅ Correct Answer: A) WAITING
TERMINATED
After `t.start()` and `Thread.sleep(50)`, `t` has acquired the lock and called `lock.wait()`, putting it into the `WAITING` state. After `lock.notify()` is called and another `Thread.sleep(50)` allows `t` to resume, it exits the `synchronized` block and completes its `run()` method, transitioning to `TERMINATED`.
Q1413easycode output
What does this code print?
java
public class DataTypeTest {
public static void main(String[] args) {
boolean isActive = true;
System.out.println(isActive);
}
}
✅ Correct Answer: A) true
A boolean variable `isActive` is set to `true`. Printing a boolean variable outputs its literal value as a string.
Q1414medium
If you have two 2D integer arrays, `int[][] arrayA = new int[2][2];` and `int[][] arrayB;`, and then execute `arrayB = arrayA;`, what is the relationship between `arrayA` and `arrayB`?
✅ Correct Answer: B) `arrayA` and `arrayB` refer to the exact same 2D array object in memory.
Assigning one array variable to another (`arrayB = arrayA;`) performs a shallow copy, meaning both variables will reference the exact same underlying array object in memory.
Q1415hard
Consider a custom exception `ServiceFailureException` that needs to wrap various underlying `Throwable` causes while preserving the full stack trace of the original cause. Which of the following approaches is the most appropriate and idiomatic way to achieve this, especially when the cause is not known at the `ServiceFailureException` constructor call site?
✅ Correct Answer: C) Call `super(message)` in the constructor, then later call `ServiceFailureException.initCause(originalCause)` before throwing.
While passing the cause to the constructor `super(message, cause)` is ideal, `initCause()` is specifically designed for scenarios where the cause might not be available at the initial construction, allowing the cause to be set once and preserving the original stack trace effectively.
Q1416medium
Which of the following statements best describes the primary goal of abstraction in Java?
✅ Correct Answer: A) To hide the complex implementation details and show only the essential features of an object.
Abstraction focuses on 'what' an object does rather than 'how' it does it, hiding complexity. Encapsulation (option b) is about bundling data and methods, and inheritance (option c) is about code reuse.
Q1417mediumcode error
What type of error is caused by the generic method overloading in this Java code?
java
import java.util.ArrayList;
import java.util.List;
public class OverloadChecker {
public void displayList(List<String> list) {
System.out.println("List of Strings");
}
public void displayList(List<Integer> list) { // This line causes the error
System.out.println("List of Integers");
}
public static void main(String[] args) {
OverloadChecker oc = new OverloadChecker();
oc.displayList(new ArrayList<String>());
}
}
✅ Correct Answer: A) Compile-time error: Method 'displayList(List<String>)' has the same erasure 'displayList(List)' as another method.
Due to type erasure, at runtime, `List<String>` and `List<Integer>` both become `List`. The compiler detects that after erasure, the two methods have identical signatures (`displayList(List)`), thus flagging a 'same erasure' compile-time error.
Q1418mediumcode error
Which exception will be thrown when running the provided Java code?
✅ Correct Answer: B) NullPointerException when creating BufferedWriter.
The `BufferedWriter` constructor expects a non-null `Writer` object. Passing `nullWriter` (which is `null`) will cause a `NullPointerException` during the instantiation of `BufferedWriter` itself.
Q1419easy
Can a class be considered fully encapsulated if all its instance variables are declared `public`?
✅ Correct Answer: B) No, because public instance variables violate data hiding.
Declaring instance variables as public directly exposes the internal state, allowing uncontrolled access and modification, which goes against the principle of data hiding central to encapsulation.
Q1420hardcode 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("X");
list1.add("Y");
list1.add(null);
list1.add("X");
list1.add("Z");
LinkedList<String> list2 = new LinkedList<>();
list2.add("X");
list2.add(null);
list2.add("A");
list1.retainAll(list2);
System.out.println(list1);
}
}
✅ Correct Answer: A) [X, null, X]
`retainAll()` removes all elements from `list1` that are not contained in `list2`. Elements `"Y"` and `"Z"` are not in `list2`, so they are removed. All occurrences of `"X"` and `null` are retained.