First, `performAction(false)` executes successfully. Then, `performAction(true)` throws an `IOException`. This exception is caught by the `catch` block, printing the error message. The line 'This line is unreachable.' is indeed not executed.
Q422medium
Why can a `private` method in a superclass not be overridden in a subclass?
✅ Correct Answer: B) `private` methods are not inherited by subclasses.
Private methods are not inherited by subclasses because they are only accessible within their own class. Since they are not inherited, they cannot be overridden.
Q423mediumcode output
What does this code print?
java
import jakarta.validation.*;
import jakarta.validation.constraints.NotNull;
import java.util.Set;
public class Test {
static class Address {
@NotNull public String street;
public Address(String street) { this.street = street; }
}
static class User {
// No @Valid here!
public Address address;
public User(Address address) { this.address = address; }
}
public static void main(String[] args) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
User user = new User(new Address(null)); // Invalid street
Set<ConstraintViolation<User>> violations = validator.validate(user);
System.out.println("Violations: " + violations.size());
}
}
✅ Correct Answer: A) Violations: 0
Without the `@Valid` annotation on the `User.address` field, the validator does not cascade validation to the `Address` object's fields. Therefore, no violations are found for `Address.street`.
Q424hardcode error
What error occurs when running this Java code?
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class IteratorDoubleRemove {
public static void main(String[] args) {
List<String> words = new ArrayList<>(Arrays.asList("hello", "world", "java"));
Iterator<String> it = words.iterator();
it.next(); // "hello"
it.remove(); // Removes "hello"
it.remove(); // Attempt to remove again without next() or previous()
}
}
✅ Correct Answer: C) java.lang.IllegalStateException
The remove() method of an Iterator can only be called once per call to next(). Calling remove() consecutively without an intervening next() or previous() (for ListIterator) results in an IllegalStateException.
Q425hard
Which statement accurately describes a key advantage of `ConcurrentLinkedQueue` over `LinkedBlockingQueue` in a highly concurrent, unbound scenario where elements are frequently added and removed?
✅ Correct Answer: A) `ConcurrentLinkedQueue` typically offers higher throughput under high contention due to its lock-free, CAS-based algorithms, avoiding explicit locks.
ConcurrentLinkedQueue uses a non-blocking, lock-free algorithm based on Compare-And-Swap (CAS) operations, which can provide better scalability and lower overhead than lock-based queues like LinkedBlockingQueue under high contention, especially when capacity is not an issue.
Q426hard
When calling `super.someMethod()` from within an overridden method in a subclass, how does this interaction subtly relate to polymorphism?
✅ Correct Answer: B) `super.someMethod()` explicitly invokes the superclass's implementation of `someMethod`, but the `this` reference within that superclass method still points to the `Derived` instance, allowing polymorphic behavior for other methods called from within `someMethod`.
While `super.someMethod()` explicitly calls the superclass's implementation, the `this` reference inside that superclass method still refers to the actual `Derived` object. This means any further polymorphic calls made using `this` from within the superclass method will correctly dispatch to the most specific override in the `Derived` object's class.
Q427easycode error
Which compilation error will occur in the given Java code?
java
import java.util.function.Consumer;
@FunctionalInterface
interface MyLogger {
default void log(String message) {
System.out.println("[LOG]: " + message);
}
static void info(String message) {
System.out.println("[INFO]: " + message);
}
}
public class Main {
public static void main(String[] args) {
// Attempt to use MyLogger
}
}
✅ Correct Answer: C) Invalid '@FunctionalInterface' annotation; MyLogger does not have an abstract method
A functional interface must contain exactly one abstract method. `MyLogger` only contains `default` and `static` methods, which are not abstract, hence it's not a functional interface.
Q428hard
How does the `BufferedWriter.newLine()` method determine the platform-specific line separator character sequence to write?
✅ Correct Answer: C) It uses the `System.lineSeparator()` method, which provides the platform's line separator, often cached from the `line.separator` system property.
`BufferedWriter.newLine()` delegates to `System.lineSeparator()`, which efficiently retrieves the platform-dependent line separator (e.g., `\n` for Unix-like, `\r\n` for Windows) from the `line.separator` system property, typically caching the value.
Q429hard
A `while` loop's condition depends on a non-`volatile` boolean flag `running` which is set to `false` by another thread. Why might the loop `while(running)` unexpectedly continue spinning indefinitely, even after the other thread sets `running` to `false`, in a heavily optimized JVM environment?
✅ Correct Answer: A) The JIT compiler might optimize the `running` variable read, effectively hoisting it out of the loop and caching its initial value.
Without the `volatile` keyword, the JIT compiler is free to cache the value of `running` in a CPU register or local cache, preventing the loop from seeing the updated value written by another thread. This optimization effectively turns `while(running)` into `while(true)` from the loop's perspective.
Q430hardcode output
What is the output of this Java code?
java
import java.util.Comparator;
import java.util.TreeMap;
class ReverseIntegerComparator implements Comparator<Integer> {
@Override
public int compare(Integer i1, Integer i2) {
return i2.compareTo(i1); // Descending order
}
}
public class Test {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>(new ReverseIntegerComparator());
map.put(1, "A");
map.put(5, "E");
map.put(3, "C");
map.put(2, "B");
map.put(4, "D");
System.out.println(map.firstKey() + ", " + map.lastKey());
}
}
✅ Correct Answer: A) 5, 1
The `TreeMap` is initialized with `ReverseIntegerComparator`, which sorts keys in descending order. Therefore, `firstKey()` returns the largest integer (5), and `lastKey()` returns the smallest integer (1) according to this custom order.
Q431mediumcode output
What is the output of this Java code?
java
class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) { this.name = name; }
public void run() {
System.out.println(name + " started.");
try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
System.out.println(name + " finished.");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new MyRunnable("Worker"));
t.start();
t.join();
System.out.println("Main thread done.");
}
}
✅ Correct Answer: A) Worker started.
Worker finished.
Main thread done.
The `t.join()` call in the main thread ensures that the main thread waits for the `Worker` thread to complete its execution before proceeding. Therefore, the 'Main thread done.' message will always be printed last.
Q432hardcode error
What exception is thrown when the `ois.readObject()` line is executed during deserialization?
java
import java.io.*;
class Singleton implements Serializable {
private static final long serialVersionUID = 1L;
private static Singleton INSTANCE = new Singleton();
private String data = "Initial Data";
private Singleton() {
// Constructor logic
}
public static Singleton getInstance() {
return INSTANCE;
}
// Incorrect readResolve implementation
protected Object readResolve() {
return new Object(); // Should return INSTANCE to maintain singleton property
}
public String getData() { return data; }
public void setData(String data) { this.data = data; }
}
public class SerializationError6 {
public static void main(String[] args) throws Exception {
Singleton s1 = Singleton.getInstance();
s1.setData("Modified Data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(s1);
byte[] serializedData = bos.toByteArray();
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(serializedData);
ObjectInputStream ois = new ObjectInputStream(bis);
Singleton s2 = (Singleton) ois.readObject(); // Error occurs here
ois.close();
System.out.println("Are they same instance? " + (s1 == s2));
System.out.println("s1 data: " + s1.getData());
System.out.println("s2 data: " + s2.getData());
}
}
✅ Correct Answer: A) java.lang.ClassCastException: java.lang.Object cannot be cast to Singleton
The `readResolve()` method is called during deserialization to allow a class to substitute a replacement object for the deserialized object. Here, it incorrectly returns a new `java.lang.Object()` instead of the singleton instance. The subsequent cast to `Singleton` then fails with a `ClassCastException`.
Q433easy
What is the primary function of the `break` keyword in Java?
✅ Correct Answer: A) To terminate the current loop or switch statement immediately.
The `break` keyword is used to abruptly terminate the enclosing loop (for, while, do-while) or switch statement.
Q434medium
What is the key distinction between the `mkdir()` and `mkdirs()` methods of the `File` class?
✅ Correct Answer: C) `mkdir()` creates only the directory specified by the `File` object if its parent exists, while `mkdirs()` creates all necessary but nonexistent parent directories as well.
`mkdir()` creates only the directory specified by the abstract pathname, failing if the parent directory does not exist. `mkdirs()` creates both the target directory and any necessary nonexistent parent directories.
Q435easy
When `Thread.sleep(long millis)` is called, what state does the current thread transition to?
✅ Correct Answer: C) TIMED_WAITING
The `Thread.sleep()` method puts the current thread into the TIMED_WAITING state for a specified duration. After the time elapses, it returns to the RUNNABLE state.
Q436easy
What happens if you try to access an element at an invalid index (e.g., negative or beyond the array's length) in a Java array?
✅ Correct Answer: A) An `ArrayIndexOutOfBoundsException` is thrown.
Accessing an array with an index that is out of its valid range (0 to length - 1) results in an `ArrayIndexOutOfBoundsException` at runtime.
Q437easy
Consider a `java.util.Date` object. Is it mutable or immutable?
✅ Correct Answer: C) Mutable, because its internal state (time) can be changed using methods like `setTime()`.
`java.util.Date` is a mutable class, meaning its internal time value can be altered after creation using methods like `setTime()`, which is a common source of bugs in concurrent environments.
Q438easycode error
What is the error in this Java code?
java
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<>();
myMap.put("fruit", "apple");
String item = myMap["fruit"];
System.out.println(item);
}
}
✅ Correct Answer: C) A compile-time error because Java does not support array-like access for Maps.
Java's Map interface uses methods like 'get()' and 'put()' for accessing elements, unlike some other languages (e.g., Python) that allow array-like bracket notation. This syntax is a compile-time error in Java.
Q439easy
What does the `this` keyword refer to inside a lambda expression?
✅ Correct Answer: C) The enclosing instance of the class where the lambda is defined.
Unlike anonymous inner classes, lambdas do not introduce a new scope for `this`. The `this` keyword inside a lambda refers to the enclosing instance of the class.
Q440hard
When `Object.notifyAll()` is called on an object where multiple threads are currently in the `WAITING` state, what is the state transition for *all* these waiting threads *before* they can potentially resume execution in the `RUNNABLE` state?
✅ Correct Answer: B) They all transition to `BLOCKED` to re-contend for the object's monitor.
Threads awakened by `notifyAll()` do not directly become `RUNNABLE`. They must first re-acquire the object's monitor, entering the `BLOCKED` state to contend for it.