import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("banana", 2);
treeMap.put("apple", 1);
treeMap.put("cherry", 3);
System.out.println(treeMap.firstKey());
}
}
✅ Correct Answer: A) apple
TreeMap orders its keys naturally. For strings, this is lexicographical order. 'apple' comes before 'banana' and 'cherry', so `firstKey()` returns 'apple'.
Q3902hard
Which statement accurately describes the typical use case for a `LinkedBlockingDeque` when compared to a `LinkedBlockingQueue`?
✅ Correct Answer: C) `LinkedBlockingDeque` is suitable for work-stealing queues or LIFO queues, as it allows elements to be inserted and removed efficiently from both ends.
LinkedBlockingDeque implements the Deque interface, allowing efficient insertion and removal from both the head and tail. This makes it ideal for scenarios like work-stealing queues (where workers can 'steal' tasks from the opposite end) or implementing LIFO (stack-like) behavior in a blocking context, unlike a standard FIFO queue.
Q3903easy
Which of the following syntax is correct for an explicit type cast in Java?
✅ Correct Answer: A) int x = (int) 10.5;
The correct syntax for explicit type casting in Java involves placing the target type in parentheses before the value or variable to be cast, like `(int) value`.
Q3904mediumcode error
What error will occur when compiling or running this Java code?
java
public class ArrayError {
public static void main(String[] args) {
int[] data = null;
System.out.println(data[0]);
}
}
✅ Correct Answer: C) java.lang.NullPointerException
When an array reference is null, attempting to access any element of it will result in a java.lang.NullPointerException at runtime.
Q3905mediumcode error
What error will occur when compiling or running this Java code?
java
public class ArrayError {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println(numbers[3]);
}
}
✅ Correct Answer: B) java.lang.ArrayIndexOutOfBoundsException
Accessing an array element at an index equal to or greater than its length (or negative) results in a java.lang.ArrayIndexOutOfBoundsException at runtime.
Q3906hardcode error
What is the runtime error when executing this Java code snippet?
java
import java.util.TreeSet;
import java.util.Objects;
class Item implements Comparable<Item> {
String name;
Item(String name) { this.name = name; }
@Override
public int compareTo(Item other) {
return Objects.requireNonNull(other.name).compareTo(this.name);
}
}
public class Main {
public static void main(String[] args) {
TreeSet<Item> items = new TreeSet<>();
items.add(new Item("Banana"));
items.add(new Item(null));
System.out.println(items.size());
}
}
✅ Correct Answer: A) java.lang.NullPointerException
When an Item with a null name is added and compared with an existing Item, the `compareTo` method is invoked. The line `Objects.requireNonNull(other.name).compareTo(this.name)` becomes `"Banana".compareTo(null)` which throws a NullPointerException because String.compareTo() does not accept null arguments.
Q3907medium
Given a String `s = "Java Programming"`, what would be the result of calling `s.substring(5, 12)`?
✅ Correct Answer: B) "Program"
The `substring(beginIndex, endIndex)` method returns a substring starting at `beginIndex` (inclusive) and ending at `endIndex` (exclusive). Index 5 is 'P', and index 12 is 'm' (exclusive), so 'Program' is returned.
Q3908easycode error
What type of error will occur when running this Java code?
java
public class MixedLocks {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void doWork() throws InterruptedException {
synchronized (lockA) {
System.out.println("Lock A acquired.");
lockB.wait(); // Calling wait on lockB, while holding lockA
System.out.println("Work finished.");
}
}
public static void main(String[] args) throws InterruptedException {
MixedLocks m = new MixedLocks();
m.doWork();
}
}
✅ Correct Answer: B) java.lang.IllegalMonitorStateException
The `wait()` method must be called on the object that the current thread holds a monitor lock on. Here, the thread holds a lock on `lockA` but calls `wait()` on `lockB`, leading to an `IllegalMonitorStateException`.
Q3909hard
Why can an `abstract` class define a constructor in Java, even though it cannot be instantiated directly?
✅ Correct Answer: B) To initialize common instance variables for its concrete subclasses when they are instantiated.
An `abstract` class's constructor is invoked indirectly by the constructors of its concrete subclasses, allowing for the initialization of shared instance variables and common setup logic required by all derived types.
Q3910easy
What is the primary purpose of the `catch` block in Java exception handling?
✅ Correct Answer: B) To handle a specific type of exception that was thrown in the `try` block.
The `catch` block is specifically designed to catch and handle an exception of a particular type that was thrown within the associated `try` block.
Q3911easycode error
What will be the compilation error in the following Java code?
java
import java.util.function.Function;
@FunctionalInterface
interface MyProcessor {
void processData(String data);
int calculateHash(String data);
}
public class Main {
public static void main(String[] args) {
// Attempt to use MyProcessor
}
}
✅ Correct Answer: B) Invalid '@FunctionalInterface' annotation; MyProcessor is not a functional interface
A functional interface is an interface that has exactly one abstract method. `MyProcessor` declares two abstract methods, `processData` and `calculateHash`, making it invalid for the `@FunctionalInterface` annotation.
Q3912medium
For a functional interface `Function<String, Integer>`, which method reference type correctly maps to a method that takes a `String` and returns its length?
✅ Correct Answer: C) `String::length`
The `String::length` method reference maps to an instance method that takes no arguments and returns an `int`. When used with `Function<String, Integer>`, the compiler understands that the `String` input parameter of the functional interface will be the instance on which `length()` is called, and the `int` return type maps to `Integer`.
Q3913medium
In terms of when the condition is checked, how is a `do-while` loop classified?
✅ Correct Answer: B) Post-test loop
A `do-while` loop is a post-test loop because its condition is evaluated after the loop body has executed, determining whether to perform subsequent iterations.
Q3914easycode output
What does this Java code print?
java
import java.io.File;
public class FileTest {
public static void main(String[] args) {
File dir = new File("temp_dir_q6");
boolean created = dir.mkdir();
System.out.println(created + " " + dir.isDirectory());
dir.delete(); // Clean up
}
}
✅ Correct Answer: A) true true
The `mkdir()` method attempts to create a new directory. If successful, it returns `true` and the directory will then be recognized as a directory by `isDirectory()`, which also returns `true`. The directory is subsequently deleted for cleanup.
Q3915mediumcode output
What is the output of this Java code?
java
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
});
System.out.println(t.getState());
t.start();
Thread.sleep(10);
System.out.println(t.getState());
Thread.sleep(150);
System.out.println(t.getState());
}
}
✅ Correct Answer: B) NEW
TIMED_WAITING
TERMINATED
Initially, after creation but before `start()`, the thread is `NEW`. After `start()` and a brief time to become runnable, it quickly enters `TIMED_WAITING` due to its `Thread.sleep(100)` call. After the sleep and task completion, it becomes `TERMINATED`.
The inner `try` throws `IOException`, which is caught by its `catch` block. The inner `finally` executes, throwing a `RuntimeException`. This `RuntimeException` propagates out of `performOperation()`, is caught by the outer `catch (RuntimeException e)`, and then the outer `finally` executes.
Q3917mediumcode error
Which statement correctly identifies the error in this Java code that defines a static and an instance method with the same signature?
java
public class OverloadChecker {
public static void performAction(int value) {
System.out.println("Static action: " + value);
}
public void performAction(int value) { // This line causes the error
System.out.println("Instance action: " + value);
}
public static void main(String[] args) {
OverloadChecker.performAction(100);
}
}
✅ Correct Answer: A) Compile-time error: Method 'performAction(int)' is already defined in 'OverloadChecker'.
The `static` keyword is not part of a method's signature for overloading purposes. Since both methods have the same name and parameter list, they are considered duplicate definitions, leading to a compile-time error.
Q3918mediumcode output
What does this chained StringBuilder operation print?
java
public class StringBuilderTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("A").insert(1, "B").delete(0, 1).append("C");
System.out.println(sb);
}
}
✅ Correct Answer: A) BC
The operations proceed as follows: '' -> 'A' (append 'A') -> 'AB' (insert 'B' at 1) -> 'B' (delete 'A' from 0 to 1) -> 'BC' (append 'C').
Q3919hard
When a `BufferedWriter` wraps an `OutputStreamWriter` (e.g., `new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file.txt"), "UTF-8"))`), which component in this chain is primarily responsible for converting characters to bytes using the specified character encoding?
✅ Correct Answer: B) The `OutputStreamWriter`, as its explicit purpose is to bridge character streams to byte streams with a specified encoding.
The `OutputStreamWriter` is designed to translate character streams into byte streams, using the specified character encoding (e.g., UTF-8). The `BufferedWriter`'s role is solely to buffer character data before it is passed to the underlying `Writer` (the `OutputStreamWriter` in this case).
Q3920hardcode error
What is the compilation outcome of the following Java code snippet?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterError10 {
public static void main(String[] args) {
FileWriter fw;
try (fw = new FileWriter("res_test.txt")) { // 'fw' must be effectively final or declared inside try-with-resources
fw.write("Hello");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: B) A compilation error because `fw` is not declared as `final` or effectively `final` when used in a `try-with-resources` statement this way.
In Java 8 and later, if a variable is declared outside the `try-with-resources` statement and then initialized within it, that variable must be effectively final. Here, `fw` is not effectively final as it's not initialized before the `try` block, and its usage `try (fw = ...)` is not allowed. The resource must be declared directly within the `try()` parentheses.