✅ Correct Answer: A) Runtime error: java.lang.IndexOutOfBoundsException
The `read(char[] cbuf, int off, int len)` method throws an `IndexOutOfBoundsException` if `off` is negative, `len` is negative, or `off + len` is greater than `cbuf.length`. Here, `0 + 10` is greater than `5`, causing the exception.
Q3602easy
In a `for` loop, which part is executed only once at the very beginning of the loop?
✅ Correct Answer: C) The initialization statement.
The initialization statement (e.g., `int i = 0;`) is executed exactly once before the loop begins its first iteration.
Q3603mediumcode error
What error will occur when running the following Java code?
java
public class WaitWithoutMonitor {
public static void main(String[] args) {
Object lock = new Object();
try {
lock.wait(); // Calling wait() without owning the monitor
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
✅ Correct Answer: B) java.lang.IllegalMonitorStateException
The `wait()` method must be called from within a `synchronized` block on the object whose monitor is being waited upon. Failing to do so throws an `IllegalMonitorStateException` at runtime.
Q3604hard
Consider a class `MyClass` with two overloaded constructors: `MyClass(double d)` and `MyClass(Integer i)`. Which of the following attempts to instantiate `MyClass` would result in a *compilation error* due to constructor ambiguity?
✅ Correct Answer: A) `new MyClass(100);`
When `100` (an `int`) is passed, the compiler can either autobox it to `Integer` or widen it to `double`. Since both conversions are considered equally applicable, the call is ambiguous, leading to a compile-time error.
Q3605easy
If a concrete class extends an abstract class that contains abstract methods, what must the concrete class do?
✅ Correct Answer: A) It must implement all abstract methods from the abstract class.
For a class to be concrete (non-abstract), it must provide implementations for all inherited abstract methods; otherwise, it must also be declared abstract.
Q3606medium
You want to define a custom functional interface `Calculator` that takes two integers and returns their sum. Which signature correctly defines its single abstract method?
✅ Correct Answer: A) `int calculate(int a, int b);`
For a `Calculator` interface to take two integers and return their integer sum, its abstract method must accept two `int` parameters and return an `int`.
Q3607mediumcode error
Consider the following Java code snippet. What is the compilation error it will produce?
java
public class OperatorError {
public static void main(String[] args) {
double d = 10.5;
int result = d >> 2;
System.out.println(result);
}
}
✅ Correct Answer: B) Bad operand types for binary operator '>>'
Bitwise shift operators (like `>>`) can only be applied to integer types (byte, short, char, int, long). Applying it to a `double` will result in a compilation error related to incompatible operand types.
Q3608medium
What is the recommended approach for ensuring that a `BufferedReader` (and its underlying stream) is properly closed after use?
✅ Correct Answer: C) Wrapping its instantiation in a `try-with-resources` statement.
`try-with-resources` ensures that any resource that implements `AutoCloseable` (like `BufferedReader`) is automatically closed when the `try` block exits, even if exceptions occur.
Q3609hard
What is the primary purpose of `Thread.setDefaultUncaughtExceptionHandler()` or `Thread.setUncaughtExceptionHandler()`?
✅ Correct Answer: B) To provide a mechanism for custom handling of uncaught exceptions that propagate up through a thread's `run` method, preventing the thread from abruptly dying.
These handlers are designed to catch exceptions that escape the `run()` method of a thread. They allow for custom logging, error reporting, or clean-up operations instead of the default behavior of simply terminating the thread and printing a stack trace.
Q3610easycode error
What will happen when this Java code is compiled?
java
public class MyClass {
public static void main(String[] args) {
if (true) {
int temp = 100;
}
System.out.println(temp);
}
}
✅ Correct Answer: C) A compilation error: cannot find symbol symbol: variable temp.
The variable 'temp' is declared within the 'if' block, making it a local variable to that block. It cannot be accessed from outside its scope, resulting in a compile-time error.
Q3611hard
Regarding the `synchronized` keyword, which statement about method overriding is true?
✅ Correct Answer: C) The `synchronized` keyword can be added or removed in an overriding method without affecting its validity.
The `synchronized` keyword, like `strictfp`, is not part of a method's signature or overriding contract. It is an implementation detail related to thread safety and can be independently added or removed in an overriding method without causing a compile-time error.
Q3612mediumcode output
What is the output of the following Java code snippet?
java
import java.util.Arrays;
import java.util.List;
public class StreamTest {
public static void main(String[] args) {
List<Integer> values = Arrays.asList(1, 2, 3, 4);
Integer sum = values.stream()
.reduce(10, (a, b) -> a + b);
System.out.println(sum);
}
}
✅ Correct Answer: A) 20
The `reduce` operation starts with an identity of 10. It then adds each element of the stream to this accumulating sum: 10 + 1 + 2 + 3 + 4 = 20.
Q3613hard
In the context of polymorphism, why are constructors not considered polymorphic in the same way as instance methods?
✅ Correct Answer: A) Constructors cannot be inherited or overridden by subclasses.
Constructors are special methods used solely for object initialization; they are not inherited by subclasses and thus cannot be overridden. This inability to override prevents them from participating in runtime polymorphism (dynamic method dispatch).
Q3614easycode error
What will be the compile-time error in the following Java code snippet?
java
public class DataTypeError {
public static void main(String[] args) {
int myInt = 10.5;
System.out.println(myInt);
}
}
✅ Correct Answer: A) Incompatible types: possible lossy conversion from double to int
Assigning a double literal (10.5) directly to an int variable without an explicit cast causes a compile-time type mismatch error because it's a 'lossy conversion'.
Q3615mediumcode output
What is the most likely output order for the 'started' and 'finished' messages?
java
class SyncExample {
public synchronized static void staticMethod() {
System.out.println(Thread.currentThread().getName() + ": Static method started.");
try { Thread.sleep(200); } catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + ": Static method finished.");
}
public synchronized void instanceMethod() {
System.out.println(Thread.currentThread().getName() + ": Instance method started.");
try { Thread.sleep(200); } catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + ": Instance method finished.");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
SyncExample obj = new SyncExample();
Thread t1 = new Thread(() -> SyncExample.staticMethod(), "StaticThread");
Thread t2 = new Thread(() -> obj.instanceMethod(), "InstanceThread");
t1.start();
t2.start();
t1.join();
t2.join();
}
}
✅ Correct Answer: A) Both 'started' messages print, then both 'finished' messages print (order of threads may vary).
A `synchronized static` method locks on the class object, while a `synchronized instance` method locks on the instance object. Since they use different locks, they can execute concurrently, leading to interleaved output of their start/finish messages.
Q3616hardcode error
What is the result of running this Java code?
java
import java.util.TreeMap;
class NonComparableKey {}
public class TreeMapError9 {
public static void main(String[] args) {
TreeMap<NonComparableKey, String> map = new TreeMap<>(null);
map.put(new NonComparableKey(), "Value");
System.out.println(map.size());
}
}
✅ Correct Answer: C) A ClassCastException is thrown.
When a `null` `Comparator` is provided to the `TreeMap` constructor, it signifies that the `TreeMap` should use the natural ordering of its keys. If the key class (`NonComparableKey`) does not implement `Comparable`, a `ClassCastException` will occur at runtime during an insertion attempt.
Q3617easycode error
What compilation error will occur in the following Java code?
java
interface RemoteControl {
void turnOn();
void turnOff();
}
class TV implements RemoteControl {
@Override
public void turnOn() {
System.out.println("TV is ON");
}
}
✅ Correct Answer: A) Error: TV is not abstract and does not override abstract method turnOff() in RemoteControl
A concrete class implementing an interface must provide an implementation for all the abstract methods declared in that interface. Here, the 'TV' class fails to implement 'turnOff()'.
Q3618medium
If a custom exception `MyUncheckedException` extends `java.lang.RuntimeException`, what is the implication for a method `bar()` that might throw it?
✅ Correct Answer: C) Method `bar()` is not required to declare or handle `MyUncheckedException`.
Unchecked exceptions, like those extending `java.lang.RuntimeException`, do not require methods to explicitly declare or handle them, allowing them to propagate up the call stack naturally.
Q3619easycode error
Which error will be reported by the Java compiler for the given code?
✅ Correct Answer: A) Compile-time error: Method 'processData(int)' is already defined in 'Utility'.
Whether a method is static or an instance method is not part of its signature for overloading. Having two methods with the exact same name and parameter list, even if one is static and the other is not, results in a compile-time error because the method signature is identical.
Q3620hardcode error
What kind of runtime error or unexpected behavior will occur when running this Java code, primarily related to thread lifecycle?
java
public class Notifier implements Runnable {
private Object monitor = new Object();
public void run() {
try {
Thread.sleep(50); // Ensure main thread starts first
monitor.notifyAll(); // Problem line
} catch (InterruptedException | IllegalMonitorStateException e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) {
Notifier notifier = new Notifier();
Thread t = new Thread(notifier);
t.start();
}
}
✅ Correct Answer: C) An `IllegalMonitorStateException` will be thrown at runtime.
Similar to `wait()`, `notify()` and `notifyAll()` methods can only be called by the thread that owns the monitor lock of the object. Since the `run()` method in `Notifier` does not synchronize on `monitor` before calling `monitor.notifyAll()`, an `IllegalMonitorStateException` will be thrown.