public class Main {
private static final Object lock = new Object();
public static void main(String[] args) {
Thread notifier = new Thread(() -> {
System.out.println("Notifier thread attempting to notify...");
lock.notify(); // Calling notify() without owning the monitor
System.out.println("Notifier thread finished.");
});
notifier.start();
}
}
✅ Correct Answer: A) Notifier thread attempting to notify...
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
The `notify()` method, like `wait()`, can only be called by a thread that holds the object's monitor (i.e., within a `synchronized` block on that object). Failing to do so results in an `IllegalMonitorStateException`.
Q2342easycode error
What will be the result of attempting to compile this Java code?
java
class Point {
private final int x;
public Point(int x) { this.x = x; }
public int getX() { return x; }
}
public class ImmutableFieldAccess {
public static void main(String[] args) {
Point p = new Point(5);
p.x = 10;
System.out.println(p.getX());
}
}
✅ Correct Answer: A) Compile-time error: "The field Point.x is not visible"
The `x` field is declared as `private`, meaning it cannot be accessed or modified directly from outside the `Point` class. Even if it were accessible, being `final` would prevent reassignment after construction.
Q2343hardcode output
What is the output of this code?
java
class MyGenericException extends Exception { public MyGenericException(String m, Throwable c) { super(m, c); } public MyGenericException(String m) { super(m); } }
class MySpecificException extends MyGenericException { public MySpecificException(String m) { super(m); } }
public class Main {
public static void process() throws MyGenericException {
try { throw new MySpecificException("Specific issue occurred"); }
catch (MySpecificException e) { throw new MyGenericException("Generic error wrapper", e); }
}
public static void main(String[] args) {
try { process(); }
catch (MyGenericException e) {
System.out.println("Caught: " + e.getMessage());
System.out.println("Cause: " + e.getCause().getMessage());
}
}
}
✅ Correct Answer: A) Caught: Generic error wrapper
Cause: Specific issue occurred
The `process` method catches `MySpecificException` and re-throws it wrapped in `MyGenericException` using the original exception as the cause. The `main` method then catches `MyGenericException` and prints its message and the message of its underlying cause.
Q2344easy
In which scenario would `java.util.LinkedList` typically be preferred over `java.util.ArrayList`?
✅ Correct Answer: C) When frequent insertions or deletions occur in the middle of the list.
`LinkedList` offers better performance (O(1) after finding the position) for insertions and deletions in the middle of the list compared to `ArrayList` (O(n) due to element shifting).
Q2345easycode error
What kind of error will occur when this Java code is executed?
java
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abcdef");
sb.setLength("3");
System.out.println(sb);
}
}
✅ Correct Answer: B) Compilation Error: Incompatible types: String cannot be converted to int
The `setLength()` method of `StringBuilder` expects an `int` argument, not a `String`. Passing a `String` literal causes a compile-time type mismatch error.
Q2346easycode error
What is the result of running this Java code?
java
public class StringError {
public static void main(String[] args) {
final String name = "Alice";
name = "Bob";
System.out.println(name);
}
}
✅ Correct Answer: D) Compilation Error: cannot assign a value to final variable name
A 'final' variable can only be assigned once. Attempting to reassign 'name' after its initial declaration causes a compilation error.
Q2347mediumcode output
What is the output of this code?
java
public class ThreadStateDemo3 {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
synchronized (lock) {
System.out.println("T1 holding lock.");
try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
});
Thread t2 = new Thread(() -> {
System.out.println("T2 trying to acquire lock.");
synchronized (lock) { System.out.println("T2 acquired lock."); }
});
t1.start();
Thread.sleep(50); // Ensure t1 gets the lock first
t2.start();
Thread.sleep(50); // Give t2 time to try and get the lock
System.out.println("T2 state: " + t2.getState());
}
}
✅ Correct Answer: A) T1 holding lock.
T2 trying to acquire lock.
T2 state: BLOCKED
When `t1` holds the lock, `t2` attempts to enter the `synchronized (lock)` block but cannot acquire the monitor. It then enters the BLOCKED state.
Q2348easycode output
What is the output of this code?
java
class Printer {
void print(String s) {
System.out.println("Printing String: " + s);
}
}
class LaserPrinter extends Printer {
void print(int i) {
System.out.println("Printing Integer: " + i);
}
}
public class Main {
public static void main(String[] args) {
LaserPrinter lp = new LaserPrinter();
lp.print("Document");
}
}
✅ Correct Answer: A) Printing String: Document
The `LaserPrinter` class overloads the `print` method by adding a version that takes an `int`. It does not override the `print(String s)` method from `Printer`. When `lp.print("Document")` is called, the `print(String s)` method inherited from `Printer` is executed.
Q2349hard
When an `ArrayList` instance is serialized, how does it manage to correctly reconstruct its state, given that its internal element array (`elementData`) is marked `transient`?
✅ Correct Answer: B) The `ArrayList` class provides custom serialization logic via `writeObject()` and `readObject()` methods.
Since the `elementData` array can contain nulls and be larger than the actual size, `ArrayList` implements custom serialization methods (`writeObject` and `readObject`) to only serialize the actual elements stored (up to `size`) and reconstruct the array to the correct size upon deserialization, optimizing the serialized form.
Q2350easycode error
What is the expected error when compiling and running the following Java code?
java
import java.util.LinkedList;
public class MyClass {
public static void main(String[] args) {
LinkedList<Integer> stack = new LinkedList<>();
stack.pop(); // Tries to remove and return the head of the list (stack behavior)
}
}
✅ Correct Answer: C) NoSuchElementException
Similar to `remove()`, calling `pop()` on an empty `LinkedList` (when used as a stack) will throw a `NoSuchElementException` because there are no elements to pop.
Q2351easycode output
What is the output of this Java code?
java
public class StringMethodTest {
public static void main(String[] args) {
String original = "Programming";
String changed = original.toUpperCase();
System.out.println(original);
}
}
✅ Correct Answer: A) Programming
String methods like `toUpperCase()` return a new String object with the modified content. They do not alter the original String object, demonstrating String's immutability.
Q2352hard
When using `FileWriter` to write text, how should one ensure platform-independent newline characters are written, and does `FileWriter` handle this translation automatically?
✅ Correct Answer: B) `FileWriter` does not automatically handle platform-specific newlines; one must explicitly write `System.getProperty("line.separator")` or use `String.format("%n")`.
`FileWriter` writes characters exactly as provided. It does not perform automatic newline translation. To achieve platform-independent newlines, you must explicitly include `System.getProperty("line.separator")` or use methods like `PrintWriter.println()`.
Q2353hardcode output
What will be the output of this code?
java
public class MultiArrayQ9 {
public static void main(String[] args) {
Object[][] mixed = new Object[2][2];
mixed[0][0] = 5; // Autoboxes to Integer
mixed[0][1] = "Java";
mixed[1][0] = new Double(3.14);
int val = (Integer)mixed[0][0];
try {
String s = (String)mixed[1][0];
System.out.println(s);
} catch (ClassCastException e) {
System.out.println("CCE caught");
}
System.out.println(val);
}
}
✅ Correct Answer: A) CCE caught
5
`mixed[1][0]` holds a `Double` object. Attempting to cast a `Double` to a `String` at runtime will result in a `ClassCastException`, which is caught and prints 'CCE caught'. Then `val` is correctly assigned `5` from the `Integer` object at `mixed[0][0]`.
Q2354hardcode output
What is the output of this code?
java
abstract class Greeter { abstract String getMsg(); }
public class Outer {
private String lang = "English";
public static void main(String[] args) {
Greeter g = new Greeter() {
@Override String getMsg() {
return "Hello " + lang; // Problematic line
}
};
// System.out.println(g.getMsg()); // This line would cause the compile error
}
}
✅ Correct Answer: A) Compile-time error
The anonymous inner class is defined within a `static` method (`main`) and tries to access `lang`, a non-static instance variable of the `Outer` class. Without an explicit instance of `Outer` (e.g., `new Outer().lang`), `Outer.this` is unavailable in a static context, resulting in a compile-time error.
Q2355easy
Which of the following is a valid way to declare and initialize a `float` variable in Java?
✅ Correct Answer: C) float num = 10.0f;
A `float` literal requires an `f` or `F` suffix because decimal numbers without a suffix are treated as `double` by default.
Q2356medium
An interface contains one abstract method and several `default` methods. Is it considered a functional interface?
✅ Correct Answer: A) Yes, because default methods are concrete implementations and do not count as abstract methods.
Default and static methods in an interface provide concrete implementations and do not count towards the number of abstract methods. An interface with exactly one abstract method, regardless of default or static methods, is functional.
Q2357easy
Which operator is used for simple assignment of a value to a variable in Java?
✅ Correct Answer: B) =
The assignment operator (=) is used to assign the value on its right to the variable on its left.
Q2358medium
Consider a class `Car` and a subclass `SportsCar`. If you declare `Car myCar = new SportsCar();`, what type of polymorphism is primarily demonstrated by `myCar` when its methods are invoked?
✅ Correct Answer: B) Runtime polymorphism
When a superclass reference points to a subclass object (upcasting), the actual method invoked at runtime depends on the type of the object, not the reference. This behavior is the essence of runtime polymorphism (dynamic method dispatch).
Q2359easy
What is the primary benefit of using `BufferedReader` in Java?
✅ Correct Answer: B) To read character data line by line more efficiently.
`BufferedReader` adds buffering capabilities to an underlying `Reader`, allowing for more efficient reading of characters, arrays, and lines of text.
Q2360mediumcode error
Consider the following Java code. What type of error will occur at compile time?
java
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
File someFile = new File("data.txt");
BufferedWriter writer = new BufferedWriter(someFile);
try {
writer.write("Info");
writer.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
✅ Correct Answer: B) A compile-time error due to incompatible types in the BufferedWriter constructor.
The `BufferedWriter` constructor expects an object of type `Writer` (or a subclass). Passing a `File` object directly is an incompatible type, resulting in a compile-time error.