How does `java.util.TreeMap` primarily maintain the order of its keys?
✅ Correct Answer: C) Based on the natural ordering of keys or a custom `Comparator` provided at construction.
`TreeMap` stores its entries in a sorted order. This order is determined either by the keys' natural ordering (if they implement `Comparable`) or by a `Comparator` supplied when the `TreeMap` is created.
Q3982medium
What is the primary purpose of a `Semaphore` in Java concurrency?
✅ Correct Answer: B) To control the number of threads that can concurrently access a limited set of resources.
A `Semaphore` is used to control access to a pool of resources, or to limit the number of concurrent operations. It maintains a set of permits, and threads acquire a permit to access a resource and release it when done.
Q3983hard
Given classes `Animal`, `Dog extends Animal`, and `Poodle extends Dog`. If an `Object obj` is known to be an instance of `Poodle`, and the following casts are attempted:
1. `(Animal) obj`
2. `(Dog) obj`
3. `(Poodle) obj`
4. `(Cat) obj` (where `Cat` is another direct subclass of `Animal`)
Which of these casts will result in a `ClassCastException` at runtime?
✅ Correct Answer: A) Only cast 4.
An object can always be cast to its own type, a superclass, or an implemented interface without a `ClassCastException`. A `ClassCastException` occurs only when attempting to cast an object to a type it is not compatible with, such as an unrelated class like `Cat`.
Q3984easycode output
What is the output of this Java code?
java
class MyThreadTask implements Runnable {
private String message;
public MyThreadTask(String msg) {
this.message = msg;
}
public void run() {
System.out.println(message + " from " + Thread.currentThread().getName());
}
}
public class MultiThreadExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThreadTask("Hello"));
Thread t2 = new Thread(new MyThreadTask("World"));
t1.start();
t2.start();
}
}
✅ Correct Answer: C) The output will contain both 'Hello from Thread-X' and 'World from Thread-Y' messages, but the order is not guaranteed.
Two separate threads are created and started concurrently. Each thread will print its message along with its default name. Since they run in parallel, the exact order of their output lines cannot be guaranteed.
Q3985mediumcode output
What does this code print?
java
import java.io.*;
class Config implements Serializable {
public static String VERSION = "1.0";
private String name;
public Config(String name) {
this.name = name;
}
public String getInfo() {
return name + ":" + VERSION;
}
}
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Config config1 = new Config("App1");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(config1);
oos.close();
Config.VERSION = "2.0"; // Static field changed AFTER serialization
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Config deserializedConfig = (Config) ois.readObject();
ois.close();
System.out.println(deserializedConfig.getInfo());
}
}
✅ Correct Answer: A) App1:2.0
Static fields are not part of an object's serialized state. Upon deserialization, the object references the current value of the static field in memory, not the value it had at the time of serialization.
Q3986hard
Consider a scenario where you have a functional interface `Processor` that has a method `process(T t)` which can throw a custom *checked* exception, `ProcessingFailureException`. You want to use this `Processor` within a Java Stream's `map` operation. What is the most robust and idiomatic pattern to handle `ProcessingFailureException` without cluttering the stream pipeline with `try-catch` blocks for each element or resorting to unchecked wrappers for every call?
✅ Correct Answer: C) Define a helper method `unchecked(Consumer<T> c)` or `unchecked(Function<T, R> f)` that internally wraps the lambda's execution in a `try-catch` block, converting the checked exception to an unchecked one, possibly using a custom unchecked wrapper.
The most robust and idiomatic pattern involves creating a utility wrapper method (e.g., `unchecked`) that allows a lambda expression to throw a checked exception, converting it to an unchecked one (often a custom `RuntimeException`) internally. This cleans up the stream pipeline and centralizes checked exception handling without losing the original exception type.
Q3987hardcode output
What is the output of this code?
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));
br.read(); // Read '1'
if (br.ready()) {
System.out.print("READY");
} else {
System.out.print("NOT_READY");
}
br.read(); // Read '2'
System.out.print((char)br.read());
br.close();
}
}
✅ Correct Answer: A) READY3
The `ready()` method returns true if the next read() is guaranteed not to block for input. Since the `StringReader` provides all data immediately, `BufferedReader` will buffer it, making `ready()` return true. After reading '1', 'READY' is printed. Then '2' is read, and '3' is printed.
Q3988easycode output
What does this code print?
java
public class StringTest {
public static void main(String[] args) {
String s = "apple";
System.out.println(s.toUpperCase());
}
}
✅ Correct Answer: C) APPLE
The `toUpperCase()` method converts all of the characters in this String to uppercase. Thus, "apple" becomes "APPLE".
Q3989hard
What is the fundamental difference in control flow impact between an unlabeled `break` statement and a `return` statement when both are encountered within an inner loop of a method?
✅ Correct Answer: B) `break` terminates the innermost enclosing loop or `switch` statement, while `return` terminates the entire method.
An unlabeled `break` statement exits the innermost enclosing loop (or `switch` statement). A `return` statement, however, exits the entire method in which it is invoked, passing control back to the caller of that method.
Q3990easycode error
What is the error in this code?
java
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
TreeMap<String, String> map = new TreeMap<>();
map.put("present", "value");
String result = map.get("absent");
System.out.println(result.length());
}
}
✅ Correct Answer: A) java.lang.NullPointerException
The `get()` method of `TreeMap` returns `null` if the specified key is not found in the map. Attempting to call a method like `length()` on a `null` reference (in this case, `result`) results in a NullPointerException.
Q3991mediumcode error
What error will occur when running this Java code snippet?
java
import java.util.HashMap;
import java.util.Map;
public class Test {
@SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
Map rawMap = new HashMap(); // Using raw type HashMap
rawMap.put("number", 123);
rawMap.put("text", "hello");
Integer num = (Integer) rawMap.get("number");
String value = (String) rawMap.get("number"); // Incorrect cast
System.out.println(num);
}
}
✅ Correct Answer: A) `ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String`
When using raw types, the compiler cannot enforce type safety. At runtime, attempting to cast an `Integer` object retrieved from the map to a `String` will result in a `ClassCastException`.
Q3992easycode error
What will happen when this Java code is compiled?
java
public class MyClass {
public static void main(String[] args) {
1number = 10;
System.out.println(1number);
}
}
✅ Correct Answer: B) A compilation error: illegal start of expression.
In Java, variable names (identifiers) cannot start with a digit. This violates the naming rules and results in a compilation error.
Q3993hard
Suppose you use mutable objects as keys in a `TreeMap` and then modify a key's relevant field (used in `compareTo`) *after* it has been inserted into the map. What is the most likely consequence?
✅ Correct Answer: C) The `TreeMap` may enter an inconsistent state, leading to incorrect retrieval or loss of the entry.
Modifying a mutable key after insertion invalidates the `TreeMap`'s internal structure and ordering. The key's position in the Red-Black Tree is determined at insertion, and changing its `compareTo` behavior post-insertion breaks the tree's invariants, potentially making the entry irretrievable or causing other logical errors.
Q3994medium
Which of the following statements regarding an interface in Java is INCORRECT?
✅ Correct Answer: C) An interface can have a constructor.
Interfaces cannot have constructors. While they can define methods, default methods, and static methods (since Java 8), they are not meant to be instantiated or manage instance state through constructors.