class MyResource {
public MyResource(String name) throws IllegalArgumentException {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Resource name cannot be empty");
}
System.out.println("Resource '" + name + "' created.");
}
public static void main(String[] args) {
try {
MyResource res = new MyResource(null);
System.out.println("After creation");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Error: Resource name cannot be empty
The constructor of `MyResource` throws an `IllegalArgumentException` if the name is null. The `main` method catches this exception and prints its message. The line 'After creation' is not reached because the exception is thrown.
Q1302easycode error
What will happen when this Java code is compiled and executed?
java
class Base { public void methodA() {} }
class Derived extends Base { public void methodA() throws java.io.IOException {} }
✅ Correct Answer: A) Compilation Error
When overriding a method, the subclass's method cannot declare new checked exceptions that were not declared by the overridden method in the superclass. `IOException` is a new checked exception not declared by `Base.methodA()`, leading to a compilation error.
Q1303easycode output
What is the output of this Java code?
java
import java.io.FileReader;
import java.io.IOException;
public class FileReaderTest {
public static void main(String[] args) {
// Assume test.txt exists and contains "JAVA"
char[] buffer = new char[2];
try (FileReader reader = new FileReader("test.txt")) {
int charsRead = reader.read(buffer);
System.out.print(new String(buffer, 0, charsRead));
} catch (IOException e) {
System.out.print("Error");
}
}
}
✅ Correct Answer: A) JA
The `read(char[] cbuf)` method attempts to read up to `cbuf.length` characters. Since the buffer size is 2, it reads the first two characters 'J' and 'A'.
Q1304mediumcode error
What will be the ultimate outcome of running this Java program?
java
public class LoopTest {
public static void main(String[] args) {
String s = "a";
while (true) {
s = s + "a";
}
}
}
✅ Correct Answer: C) A java.lang.OutOfMemoryError: Java heap space.
The `while(true)` loop is infinite, and in each iteration, a new `String` object is created and appended to `s`. This continuous creation of new string objects consumes heap memory, eventually leading to a `java.lang.OutOfMemoryError: Java heap space`.
Q1305easycode error
What is wrong with this Java code?
java
import java.util.function.Consumer;
public class Test {
public static void main(String[] args) {
int counter = 0;
Consumer<String> printer = s -> {
System.out.println(s + counter);
counter++;
};
printer.accept("Count: ");
}
}
✅ Correct Answer: A) Local variables referenced from a lambda expression must be final or effectively final.
Lambda expressions capture local variables from their enclosing scope. These captured variables must be effectively final, meaning their value cannot be changed after initialization. Incrementing `counter` inside the lambda violates this rule.
Q1306medium
Which of the following data types is NOT directly supported as the controlling expression for a Java `switch` statement or expression?
✅ Correct Answer: C) long
`long` is not directly supported by the `switch` statement or expression. The supported types include `byte`, `short`, `char`, `int`, their wrapper classes, `String`, and `Enum`.
Q1307medium
Which statement correctly describes the return type rule for method overriding in Java?
✅ Correct Answer: B) The return type can be a subclass of the return type in the superclass method (covariant return type).
Java supports covariant return types for overridden methods, meaning the overriding method can return a subtype of the return type declared in the superclass method.
Q1308hardcode output
What is the output of this code?
java
public class Q9_NotifyAllVsNotify {
private static final Object lock = new Object();
private static int counter = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> { synchronized (lock) { try { lock.wait(); counter++; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } });
Thread t2 = new Thread(() -> { synchronized (lock) { try { lock.wait(); counter++; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } });
Thread t3 = new Thread(() -> { synchronized (lock) { try { lock.wait(); counter++; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } });
t1.start(); t2.start(); t3.start();
Thread.sleep(100); // Ensure all threads are waiting
System.out.println("Counter before notify: " + counter);
synchronized (lock) {
lock.notify(); // Only one thread will be woken up
}
Thread.sleep(100); // Give time for one thread to process
System.out.println("Counter after 1st notify: " + counter);
synchronized (lock) {
lock.notifyAll(); // Wake up remaining threads
}
Thread.sleep(100); // Give time for others to process
System.out.println("Counter after notifyAll: " + counter);
}
}
✅ Correct Answer: A) Counter before notify: 0
Counter after 1st notify: 1
Counter after notifyAll: 3
Initially, all three threads (`t1`, `t2`, `t3`) are in the `WAITING` state. The first `lock.notify()` wakes up only one arbitrary waiting thread, which increments `counter` to 1. The subsequent `lock.notifyAll()` wakes up the remaining two threads, which then also increment `counter`, bringing the total to 3.
Q1309hard
If an array is declared as `volatile Object[] data;`, what does the `volatile` keyword guarantee with respect to the array's elements in a multithreaded environment?
✅ Correct Answer: B) The `volatile` keyword ensures that the `data` array itself (the reference) is visible, but not necessarily the individual elements it contains.
Applying `volatile` to an array reference only guarantees visibility and ordering for the reference itself. It does not make individual elements of the array volatile; access to elements still requires additional synchronization or atomic operations to ensure visibility and atomicity across threads.
Q1310medium
Regarding the `remove()` and `poll()` methods of the Java `Queue` interface, what is the key difference in their behavior when the queue is empty?
✅ Correct Answer: B) `remove()` throws a `NoSuchElementException`, while `poll()` returns null.
`remove()` retrieves and removes the head of the queue, throwing `NoSuchElementException` if the queue is empty. `poll()` retrieves and removes the head of the queue, or returns `null` if the queue is empty.
Q1311mediumcode error
What error will occur when running the following Java code?
java
public class NotifyWithoutMonitor {
public static void main(String[] args) {
Object lock = new Object();
lock.notify(); // Calling notify() without owning the monitor
}
}
✅ Correct Answer: A) java.lang.IllegalMonitorStateException
Similar to `wait()`, `notify()` and `notifyAll()` methods must be called from within a `synchronized` block on the object whose monitor is held. Otherwise, an `IllegalMonitorStateException` is thrown.
Q1312medium
What is the typical range for thread priorities in Java, and how does setting priority affect thread scheduling?
✅ Correct Answer: B) 1 to 10; higher priority threads are given preference by the scheduler, but it's not a guarantee.
Thread priorities in Java range from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5 being NORM_PRIORITY. While higher priority threads are given preference by the thread scheduler, the exact behavior is platform-dependent and not a guarantee.
Q1313easycode error
What compile-time error will occur in the `Child` class?
java
class Parent {
public static void showStatic() {
System.out.println("Parent Static");
}
}
class Child extends Parent {
@Override
public void showStatic() {
System.out.println("Child Static");
}
}
✅ Correct Answer: A) Error: Method does not override method from its superclass
A static method cannot be overridden by an instance method (or vice versa). The `@Override` annotation explicitly checks for a valid override, and since this isn't one, it reports an error.
Q1314hardcode error
What error occurs when executing the following Java code?
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> original = new ArrayList<>();
original.add(10);
original.add(20);
List<Integer> unmodifiable = Collections.unmodifiableList(original);
unmodifiable.add(30); // Attempt to modify the unmodifiable list
System.out.println(unmodifiable);
}
}
✅ Correct Answer: C) java.lang.UnsupportedOperationException
`Collections.unmodifiableList()` returns an immutable view of the specified list. Any attempt to modify this unmodifiable list (e.g., by calling `add`, `remove`, `set`) will throw an `UnsupportedOperationException`.
Q1315medium
What is the requirement for objects stored in a `TreeSet` if no custom `Comparator` is provided during its instantiation?
✅ Correct Answer: D) They must implement the `Comparable` interface.
For elements to be sorted naturally, they must implement the `Comparable` interface. Otherwise, a `ClassCastException` will occur when attempting to add elements.
Q1316easy
What characteristic makes String objects unchangeable once created in Java?
✅ Correct Answer: A) Immutable
String objects in Java are immutable, meaning their content cannot be altered after they are created. Any 'modification' results in a new String object.
Q1317easycode error
What will happen when attempting to instantiate `ArrayDeque` with a negative capacity?
java
import java.util.ArrayDeque;
import java.util.Deque;
public class QueueError {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>(-5);
deque.add("Item");
}
}
✅ Correct Answer: B) IllegalArgumentException
The constructor for `ArrayDeque` (and many collection classes that take an initial capacity) throws an `IllegalArgumentException` if the specified initial capacity is negative.
Q1318hard
If an `if` statement's condition calls a method with a side effect (e.g., `if (updateAndCheckStatus())`), and this `if` statement is inside a loop, how often is the `updateAndCheckStatus()` method guaranteed to be called per loop iteration?
✅ Correct Answer: B) It's called exactly once per loop iteration, regardless of its return value.
The condition of an `if` statement is evaluated exactly once each time the `if` statement is reached during execution. Therefore, the method will be called every time the loop iterates and reaches the `if` statement.
Q1319hard
Which of the following scenarios would lead to an `ExceptionInInitializerError` being thrown at runtime?
✅ Correct Answer: C) A static field's initializer expression throwing a checked exception that is not handled.
`ExceptionInInitializerError` is thrown by the JVM to indicate that an unexpected exception occurred during the static initialization of a class. This commonly happens when a checked exception is thrown from a static initializer block or a static field's initializer and is not caught within that context.
Q1320hard
Under what specific circumstances might wrapping a `Writer` with a `BufferedWriter` lead to *reduced* performance or offer no significant advantage?
✅ Correct Answer: C) When performing extremely small, frequent writes, each immediately followed by an explicit `flush()` call.
The primary benefit of `BufferedWriter` is to reduce physical I/O operations by buffering. If every small write is immediately flushed, the buffering advantage is negated, and the overhead of the `BufferedWriter` itself can slightly degrade performance compared to direct, unbuffered writes.