✅ Correct Answer: B) No, it is not thread-safe, but it can be synchronized externally using `Collections.synchronizedSortedMap()`.
`TreeMap` is not thread-safe by default. If multiple threads access a `TreeMap` concurrently and at least one of the threads modifies the map, it must be synchronized externally, typically using `Collections.synchronizedSortedMap()`.
Q2642hardcode output
What is the output of the following Java program, focusing on thread interruption?
java
public class InterruptionRunnable {
public static void main(String[] args) throws InterruptedException {
Runnable interruptibleTask = () -> {
try {
System.out.println("Task started.");
Thread.sleep(1000); // Will be interrupted
System.out.println("Task finished normally.");
} catch (InterruptedException e) {
System.out.println("Task interrupted. Flag state: " + Thread.currentThread().isInterrupted());
}
};
Thread worker = new Thread(interruptibleTask, "Worker");
worker.start();
Thread.sleep(100); // Give task a chance to start
worker.interrupt();
worker.join();
System.out.println("Main thread done.");
}
}
✅ Correct Answer: A) Task started.
Task interrupted. Flag state: false
Main thread done.
When `Thread.sleep()` is interrupted, it throws an `InterruptedException` and clears the thread's interrupted status flag. Therefore, inside the catch block, `Thread.currentThread().isInterrupted()` will return `false`, even though an interruption just occurred.
Q2643easy
Which method is used by a `Collection` to return an `Iterator` instance?
✅ Correct Answer: C) `iterator()`
All classes implementing the `Collection` interface (which extends `Iterable`) must provide an implementation for the `iterator()` method to return an `Iterator`.
Q2644easycode error
What is the error in the following Java code snippet?
java
public class ArrayError {
public static void main(String[] args) {
int size = 5.0;
int[] arr = new int[size];
}
}
✅ Correct Answer: A) Compile-time error: Incompatible types, double cannot be converted to int.
The variable `size` is declared as an `int`, but an attempt is made to assign a `double` literal `5.0` to it. This requires an explicit cast and without it, results in a compile-time type mismatch error.
Q2645hardcode output
What is the output of this code?
java
import java.util.LinkedList;
import java.util.ListIterator;
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("X");
list.add("Y");
list.add("Z");
ListIterator<String> it = list.listIterator();
it.next(); // Passes 'X'
it.add("A"); // Adds 'A' before 'Y'
it.next(); // Passes 'Y'
it.remove(); // Removes 'Y'
it.next(); // Passes 'Z'
it.set("W"); // Replaces 'Z' with 'W'
System.out.println(list);
}
}
✅ Correct Answer: C) [X, A, W]
`it.add("A")` inserts 'A' at the current iterator position. `it.remove()` removes the element last returned by `next()` or `previous()`. `it.set("W")` replaces the last element returned by `next()` or `previous()`.
Q2646mediumcode output
What will be printed to the console when this code runs?
java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Double> prices = new ArrayList<>();
prices.add(10.5);
prices.add(20.0);
prices.set(0, 15.0);
System.out.println(prices);
}
}
✅ Correct Answer: A) [15.0, 20.0]
The `set(index, element)` method replaces the element at the specified position with the new element. Here, the element at index 0 (10.5) is replaced by 15.0.
Q2647hardcode output
What is the output of this code?
java
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
public class Test {
public static void main(String[] args) throws IOException {
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw, 2); // Buffer size of 2 characters
bw.write('A');
bw.write('B');
bw.write('C');
bw.close();
System.out.println(sw.toString());
}
}
✅ Correct Answer: A) ABC
When 'B' is written, the buffer becomes full ('AB'). This triggers an automatic flush to the StringWriter. Then 'C' is written to the now empty buffer. Finally, bw.close() flushes 'C'. The total output is 'ABC'.
Q2648easycode error
What compilation error will occur in the following Java code?
java
class Product {
public abstract void getDescription();
}
✅ Correct Answer: C) Error: The abstract method getDescription in type Product can only be defined in an abstract class
An abstract method can only be declared within an abstract class or an interface. A concrete class like 'Product' cannot contain an abstract method.
Q2649mediumcode error
What is the result of attempting to run the following Java code?
java
public class Main {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.println("Thread running"));
try {
t.setPriority(100); // This line
t.start();
} catch (IllegalArgumentException e) {
System.err.println("Caught error: " + e.getMessage());
}
}
}
✅ Correct Answer: C) A runtime exception: java.lang.IllegalArgumentException with a message like 'priority is not in range [1,10]'.
Thread priorities in Java must be between Thread.MIN_PRIORITY (1) and Thread.MAX_PRIORITY (10). Setting a priority outside this range will throw an IllegalArgumentException at runtime.
Q2650medium
Which statement correctly describes the allowance of null keys and null values in a `java.util.HashMap`?
✅ Correct Answer: A) Allows one null key and multiple null values.
A HashMap permits a single null key and any number of null values. This is a common distinction from Hashtable, which does not allow nulls.
Q2651medium
What is the primary purpose of encapsulation in Java?
✅ Correct Answer: B) To hide the internal implementation details of an object and protect its state from external, unauthorized access.
Encapsulation's main goal is to bundle data with methods that operate on that data and restrict direct access to the internal state, thereby hiding implementation details.
Q2652hardcode output
What does this code print?
java
public class IntegerArrayNullPointerException {
public static void main(String[] args) {
Integer[] nums = new Integer[3];
nums[0] = 10;
nums[2] = 20;
int sum = 0;
try {
for (Integer num : nums) {
sum += num;
}
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
return;
}
System.out.println(sum);
}
}
✅ Correct Answer: A) NullPointerException
The `Integer[] nums` array is initialized, and `nums[1]` remains `null`. When the enhanced for-loop iterates, `num` will be `null` for the second element. The expression `sum += num` attempts to unbox the `Integer` `num` to an `int`, which causes a `NullPointerException` when `num` is `null`.
Q2653hard
When considering the implementation of `StringBuffer`, which statement accurately describes how its thread safety is generally maintained for operations like `append` or `insert`?
✅ Correct Answer: B) Most modifying public methods are declared as `synchronized`, using the `StringBuffer` instance's intrinsic lock.
`StringBuffer` achieves its thread safety by making many of its public modifying methods (`append`, `insert`, `delete`, etc.) `synchronized`. This uses the `StringBuffer` instance itself as the monitor, ensuring only one thread can execute these methods at a time on that instance.
Q2654mediumcode output
What is the output of this code?
java
import java.util.LinkedList;
import java.util.Queue;
public class QueueIsNull {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.offer("One");
queue.poll();
System.out.println(queue.peek());
System.out.println(queue.poll());
}
}
✅ Correct Answer: C) null
null
After 'One' is offered and then polled, the queue becomes empty. Calling `peek()` on an empty queue returns `null`. Calling `poll()` on an empty queue also returns `null`.
Q2655mediumcode output
What is the output of the following Java code?
java
public class StringBufferTest {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("racecar");
sb.reverse();
System.out.print(sb.equals("racecar") + " " + (sb.toString().equals("racecar")));
}
}
✅ Correct Answer: A) false true
After `sb.reverse()`, 'racecar' remains 'racecar'. However, `StringBuffer.equals()` is not overridden from `Object.equals()`, so it compares object references, which are different. `sb.toString()` converts it to a String, and `String.equals()` compares content, so it will be true.
Q2656mediumcode error
What is the result of attempting to compile and run this Java code with the given `execute` method calls?
java
public class OverloadChecker {
public void execute(int a, double b) {
System.out.println("int, double: " + a + ", " + b);
}
public void execute(double a, int b) {
System.out.println("double, int: " + a + ", " + b);
}
public static void main(String[] args) {
OverloadChecker oc = new OverloadChecker();
oc.execute(10, 20); // This line causes the error
}
}
✅ Correct Answer: A) Compile-time error: Reference to 'execute' is ambiguous, both 'execute(int, double)' and 'execute(double, int)' match.
When calling `execute(10, 20)`, both integer literals can be widened to `double`. The compiler cannot determine if `(int, int)` should map to `(int, double)` (by widening the second parameter) or `(double, int)` (by widening the first parameter), leading to an ambiguous call.
Q2657medium
What is a main advantage of implementing `Runnable` over extending the `Thread` class when creating a multithreaded application?
✅ Correct Answer: B) Java does not support multiple inheritance, so `Runnable` allows a class to extend another class while still being runnable.
Since Java does not support multiple inheritance, implementing `Runnable` allows a class to inherit from another class while still defining a task that can run in a separate thread. This promotes separation of concerns between the task and the thread execution mechanism.
Q2658mediumcode error
What kind of error will occur when running this Java code?
java
public class ArrayError {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
✅ Correct Answer: B) Runtime error: ArrayIndexOutOfBoundsException
The loop condition `i <= numbers.length` allows `i` to reach `numbers.length`, which is an invalid index for a zero-based array. This will cause an `ArrayIndexOutOfBoundsException` at runtime when trying to access `numbers[3]`.
Q2659easy
Once a single-dimensional array is created in Java, what can be said about its size?
✅ Correct Answer: A) Its size is fixed and cannot be changed.
Java arrays have a fixed size that is determined at the time of creation and cannot be altered later.
Q2660easy
Which of the following is NOT a valid scenario for method overloading?
✅ Correct Answer: D) Method `start()` with `void` return type and `start()` with `int` return type (same parameters).
Method overloading requires the parameter lists to be different. Methods differing only by their return type (with identical parameter lists) are not valid overloaded methods and will cause a compile-time error.