public class DaemonThreadBehavior {
public static void main(String[] args) throws InterruptedException {
Thread daemonThread = new Thread(() -> {
while (true) {
try {
System.out.println("Daemon running...");
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Daemon interrupted.");
break;
}
}
});
daemonThread.setDaemon(true);
daemonThread.start();
System.out.println("Main thread started daemon.");
Thread.sleep(250);
System.out.println("Main thread exiting.");
}
}
✅ Correct Answer: B) Main thread started daemon.
Daemon running...
Daemon running...
Daemon running...
Main thread exiting.
Daemon threads do not prevent the JVM from exiting. When the last non-daemon thread (in this case, the main thread) finishes, the JVM terminates, abruptly stopping any running daemon threads. The daemon thread prints a few times before the main thread exits, causing the JVM to shut down.
Q2122easy
Which method removes leading and trailing whitespace from a string?
✅ Correct Answer: B) trim()
The `trim()` method returns a new string with leading and trailing whitespace removed. Note: `strip()` is similar but introduced in Java 11.
Q2123hardcode error
What is the result of running this Java code?
java
import java.util.TreeMap;
import java.util.Map;
public class TreeMapError3 {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "Ten");
map.put(20, "Twenty");
map.put(30, "Thirty");
Map<Integer, String> sub = map.subMap(25, 15);
System.out.println(sub.size());
}
}
✅ Correct Answer: A) An IllegalArgumentException is thrown.
The `subMap(fromKey, toKey)` method (and its overloaded variants) requires that `fromKey` must be less than or equal to `toKey`. If `fromKey` is greater than `toKey`, an `IllegalArgumentException` is thrown.
Q2124mediumcode error
What is the compilation error in the provided Java code?
java
interface Drivable {
void drive();
void stop() { // This line is problematic
System.out.println("Stopping");
}
}
public class MyCar implements Drivable {
public void drive() {
System.out.println("Driving MyCar");
}
}
✅ Correct Answer: A) Abstract methods do not specify a body
Prior to Java 8, interface methods could not have a body unless they were declared 'default' or 'static'. Without these keywords, a method in an interface is implicitly abstract and cannot have an implementation.
Q2125easycode output
What is the output of this code?
java
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileReaderTest {
public static void main(String[] args) {
// Assume nonexistent.txt does NOT exist
try {
FileReader reader = new FileReader("nonexistent.txt");
System.out.print("File found");
reader.close();
} catch (FileNotFoundException e) {
System.out.print("File not found!");
} catch (IOException e) {
System.out.print("Other IO Error!");
}
}
}
✅ Correct Answer: A) File not found!
If the specified file does not exist, the `FileReader` constructor throws a `FileNotFoundException`, which is caught and handled.
Q2126medium
How can you provide a custom sorting order for elements in a `TreeSet` that is different from their natural ordering?
✅ Correct Answer: B) By passing a `Comparator` object to the `TreeSet`'s constructor.
A `TreeSet` can be constructed with a `Comparator` instance, which defines the custom order in which elements are to be sorted and compared within the set.
Q2127easycode error
What error will occur when this code is compiled or executed?
java
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Buffer");
String str = sb;
System.out.println(str);
}
}
✅ Correct Answer: A) Compile-time error: Incompatible types
A `StringBuffer` object cannot be directly assigned to a `String` variable because they are different types. An explicit conversion using `toString()` method is required.
Q2128medium
In a nested `try-catch-finally` structure, if an exception occurs in the inner `try` block and is successfully caught by its inner `catch` block, what is the execution sequence concerning the `finally` blocks?
✅ Correct Answer: B) The inner `finally` block executes, then the outer `finally` block executes.
When an exception occurs in a nested `try`, the control flows through its inner `catch` (if present) and then its inner `finally`. After the inner `try-catch-finally` completes, the outer `finally` block will execute.
Q2129easycode error
What kind of error will occur when compiling or running the following Java code snippet?
java
import java.io.File;
import java.io.IOException;
public class FileError8 {
public static void main(String[] args) throws IOException {
File file = new File("invalid\0name.txt"); // \0 is the null character
file.createNewFile();
System.out.println("File created.");
}
}
✅ Correct Answer: C) An IOException will be thrown at runtime due to the invalid character in the file name.
The null character (`\0`) is generally not allowed in file paths on most operating systems. Attempting to create a file with such a character will result in an `IOException` at runtime, indicating an invalid argument or file name.
Q2130medium
Why might a custom exception class need to implement `java.io.Serializable` and provide a `serialVersionUID`?
✅ Correct Answer: B) To ensure the exception can be passed between different JVMs or persisted to disk.
Implementing `Serializable` and providing `serialVersionUID` is necessary if the custom exception needs to be serialized, for example, when sending it over a network or storing it in a file, ensuring compatibility during deserialization.
Q2131easycode output
What is the output of this Java code?
java
public class AnonymousRunnable {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Anonymous thread running.");
}
}).start();
System.out.println("Main method finished.");
}
}
✅ Correct Answer: C) The output order is not guaranteed, but both messages will appear.
A new thread is created using an anonymous `Runnable` and started. Both the new thread and the main thread execute concurrently. Therefore, the exact order of their output cannot be predicted reliably.
Q2132easy
What is the primary characteristic of a Queue data structure?
✅ Correct Answer: A) First-In, First-Out (FIFO)
Queues adhere to the First-In, First-Out (FIFO) principle, meaning the first element added to the queue is the first one to be removed.
Q2133easycode error
What is the compilation error in the `Main` class?
java
class Person {
String firstName = "John";
String lastName = "Doe";
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
System.out.println(p.fullName);
}
}
✅ Correct Answer: A) Cannot find symbol `fullName`
The `Person` class does not have a field named `fullName`. Attempting to access a non-existent field results in a 'cannot find symbol' compilation error.
Q2134hardcode error
What is the result of executing this Java code snippet?
java
public class ChainedPrimitiveCast {
public static void main(String[] args) {
int val = 10;
Number num = val;
Byte b = (Byte) num;
System.out.println(b);
}
}
✅ Correct Answer: A) A ClassCastException occurs at runtime on the line casting to Byte.
The `int val` is autoboxed to an `Integer` object when assigned to `Number num`. Therefore, `num` actually holds an `Integer` object. Attempting to cast an `Integer` object to a `Byte` object directly results in a `ClassCastException` at runtime, as they are distinct sibling classes under `Number`.
Q2135hard
Why do `private` methods in a superclass not participate in polymorphism, even if a subclass defines a method with the exact same signature?
✅ Correct Answer: B) `private` methods are not inherited by subclasses.
`private` methods are not inherited by subclasses. Therefore, they cannot be overridden, and any method with the same signature in a subclass is considered a completely new method, not an override, preventing polymorphic behavior.
Q2136hardcode output
What is the output of this code?
java
public class Q6_BlockedState {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
synchronized (lock) {
System.out.println("T1 holding lock.");
try {
Thread.sleep(100); // Hold lock
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
System.out.println("T1 releasing lock.");
}
});
Thread t2 = new Thread(() -> {
System.out.println("T2 trying to acquire lock.");
synchronized (lock) { // Will block here
System.out.println("T2 acquired lock.");
}
System.out.println("T2 finished.");
});
t1.start();
Thread.sleep(50); // Ensure t1 acquires lock
t2.start();
Thread.sleep(20); // Give t2 time to try and block
System.out.println("T2 State: " + t2.getState());
t1.join(); // Wait for t1 to finish and release lock
Thread.sleep(20); // Give t2 time to acquire lock and finish
System.out.println("T2 Final State: " + t2.getState());
}
}
✅ Correct Answer: A) T1 holding lock.
T2 trying to acquire lock.
T2 State: BLOCKED
T1 releasing lock.
T2 acquired lock.
T2 finished.
T2 Final State: TERMINATED
Thread `t1` acquires the lock first. When `t2` attempts to enter its `synchronized (lock)` block, it finds the lock held by `t1` and transitions to the `BLOCKED` state. After `t1` releases the lock (by finishing its `synchronized` block), `t2` acquires it, runs its code, and then terminates.
Q2137mediumcode error
What is the error in this Java code snippet?
java
public class MyClass {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("example");
sb.replace('e', 'X');
System.out.println(sb);
}
}
✅ Correct Answer: B) A compile-time error: No suitable method found for replace(char,char).
The `StringBuilder` class does not have a `replace(char oldChar, char newChar)` method like the `String` class. Its `replace` method expects `(int start, int end, String str)` arguments, leading to a compile-time error.
Q2138medium
What is the primary effect of declaring a variable with the `final` keyword in Java?
✅ Correct Answer: B) It prevents the variable's value from being modified after its initial assignment.
The `final` keyword makes a variable a constant, meaning its value cannot be reassigned once it has been initialized. For reference variables, it means the reference cannot change, but the object it points to can still be modified.
Q2139medium
Is `java.util.LinkedList` inherently thread-safe?
✅ Correct Answer: B) No, it is not thread-safe and requires external synchronization.
`java.util.LinkedList` is not thread-safe. If multiple threads access a linked list concurrently and at least one of them modifies the list structurally, it must be synchronized externally, typically using `Collections.synchronizedList()` or a `ReentrantLock`.
Q2140hardcode output
What does this code print?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> dq = new LinkedList<>();
dq.add(10);
dq.add(20);
System.out.print(dq.poll() + " ");
System.out.print(dq.peekFirst() + " ");
dq.addFirst(5);
System.out.print(dq.pollLast() + " ");
System.out.print(dq.pollLast() + " ");
System.out.print(dq.pollLast());
}
}
✅ Correct Answer: A) 10 20 20 5 null
`poll()` removes and returns the head (10). `peekFirst()` returns the head (20) without removing. `addFirst(5)` adds 5. `pollLast()` removes 20, then 5. The last `pollLast()` on an empty deque returns `null`.