import java.io.*;
class Initializable implements Serializable {
private String data;
public Initializable() {
System.out.println("Constructor called!");
this.data = "Default";
}
public void setData(String data) {
this.data = data;
}
public String getData() {
return data;
}
}
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Initializable obj = new Initializable();
obj.setData("Hello");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Initializable deserializedObj = (Initializable) ois.readObject();
ois.close();
System.out.println("Deserialized Data: " + deserializedObj.getData());
}
}
✅ Correct Answer: A) Constructor called!
Deserialized Data: Hello
The constructor is only called when an object is initially created using `new`. Deserialization creates an object directly from the serialized byte stream without invoking its constructor.
Q2682easycode output
What does this code print?
java
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
boolean addedFirst = fruits.add("Mango");
boolean addedSecond = fruits.add("Mango"); // Duplicate
System.out.println(addedFirst);
System.out.println(addedSecond);
}
}
✅ Correct Answer: A) true
false
The `add()` method returns `true` if the element was added successfully (i.e., it was not already present) and `false` if the element was already present (a duplicate). 'Mango' is added first, then the second attempt finds it already present.
Q2683mediumcode output
What is the output of this code?
java
class MyCheckedException extends Exception {
public MyCheckedException(String msg) {
super(msg);
}
}
class MyUncheckedException extends RuntimeException {
public MyUncheckedException(String msg) {
super(msg);
}
}
public class Main {
public static void main(String[] args) {
try {
throw new MyUncheckedException("Unchecked!");
} catch (MyCheckedException e) {
System.out.println("Caught Checked: " + e.getMessage());
} catch (MyUncheckedException e) {
System.out.println("Caught Unchecked: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Caught Unchecked: Unchecked!
The code throws a `MyUncheckedException`. The control flows to the second `catch` block, which specifically handles `MyUncheckedException`, printing its message.
Q2684hard
What happens if a thread T1 calls `T2.join()` and T1 itself is interrupted while waiting for T2 to finish?
✅ Correct Answer: A) T1's interrupted status is set, and it throws an `InterruptedException`, ceasing its wait for T2.
`Thread.join()` is an interruptible method. If the calling thread is interrupted while waiting, it will throw an `InterruptedException` and clear its interrupted status.
Q2685medium
In the context of method overriding, what is the primary use of the `super` keyword inside an overriding method?
✅ Correct Answer: B) To call the superclass's overridden method within the subclass's overriding method.
The `super` keyword in an overriding method is used to explicitly invoke the implementation of the method from its superclass. This allows the subclass to extend or modify the superclass's behavior while still utilizing it.
Q2686hard
What are the most critical consequences if `FileWriter.close()` is consistently omitted after all write operations are complete and before the program exits?
✅ Correct Answer: B) Data written to the stream may remain in internal buffers and never be persisted to the file, and underlying system resources (like file handles) might not be released, potentially leading to resource exhaustion.
`close()` is crucial for `FileWriter` as it flushes any buffered data to the underlying file and releases system resources associated with the file handle. Omitting it can lead to data loss (unwritten buffered data) and resource leaks.
Q2687easycode error
What is the primary compile-time error in this code?
java
class DataObject {
private String info;
public DataObject(String info) { this.info = info; }
}
public class Main {
public static void main(String[] args) {
DataObject obj = new DataObject("Invalid data");
throw obj; // Attempt to throw an object that is not a Throwable
}
}
✅ Correct Answer: A) error: incompatible types: DataObject cannot be converted to java.lang.Throwable
The `throw` statement in Java can only be used with objects that are instances of `java.lang.Throwable` or its subclasses. `DataObject` does not extend `Throwable`, so it cannot be thrown.
Q2688hard
A thread `T` uses `java.util.concurrent.locks.ReentrantLock` and calls `Condition.await()` within a `try-finally` block. What state does `T` enter, and what monitor operation occurs?
✅ Correct Answer: A) Enters `WAITING` state and releases the `ReentrantLock`.
`Condition.await()` causes the thread to enter the `WAITING` state and atomically releases the `ReentrantLock` associated with the condition, allowing other threads to acquire the lock.
Q2689medium
If you have a 2D array `String[][] names = new String[3][5];`, which index combination correctly refers to an element in the second row and third column?
✅ Correct Answer: B) names[1][2]
Array indices in Java are 0-based. The second row is at index 1, and the third column is at index 2.
Q2690easy
Which of the following can be used as the monitor object for a `synchronized` block in Java?
✅ Correct Answer: C) Any non-null object.
Any non-null object can serve as the monitor for a `synchronized` block, allowing threads to acquire its intrinsic lock to protect a critical section.
Q2691mediumcode error
What is the compilation error in the provided Java code?
java
class ParentService {
private void internalLogic() {
System.out.println("Parent internal logic");
}
}
class ChildService extends ParentService {
@Override // ERROR: @Override on private method
public void internalLogic() {
System.out.println("Child internal logic");
}
}
public class Main {
public static void main(String[] args) {
// ChildService cs = new ChildService();
}
}
✅ Correct Answer: A) ChildService.java:9: error: method does not override or implement a method from a supertype
Private methods are not inherited by subclasses and are therefore not visible for overriding. Using the `@Override` annotation on a method that does not override a superclass method will result in a compile-time error.
Q2692easycode output
What is the output of this Java code?
java
public class Product {
private double price;
public void setPrice(double newPrice) {
if (newPrice > 0) {
this.price = newPrice;
} else {
this.price = 0.0;
}
}
public double getPrice() {
return price;
}
public static void main(String[] args) {
Product p = new Product();
p.setPrice(-10.0);
p.setPrice(25.5);
System.out.println(p.getPrice());
}
}
✅ Correct Answer: A) 25.5
The 'setPrice' method validates input, setting price to 0.0 for negative values. However, the last valid call 'setPrice(25.5)' overwrites any previous value, so 'getPrice()' returns 25.5.
Q2693mediumcode error
What type of error will occur when compiling the following Java code?
java
public class Main {
public static void main(String[] args) {
int x = 10.5;
System.out.println(x);
}
}
✅ Correct Answer: A) Compile-time error
Assigning a double literal (10.5) to an int variable without an explicit cast is a narrowing conversion and results in a compile-time error due to incompatible types.
Q2694easy
Where is the loop condition evaluated in a do-while loop?
✅ Correct Answer: A) At the end of each iteration, after the loop body has executed.
In a do-while loop, the 'do' block executes first, and then the 'while' condition is checked at the end to decide whether to continue the loop.
Q2695hardcode error
What error will this Java code produce when compiled and run?
java
public class ArrayDeclarationSyntax {
public static void main(String[] args) {
// This declares 'x' as an int array, but 'y' as a single int variable.
int x[], y;
x = new int[5];
// Attempt to access 'y' as if it were an array
y[0] = 10;
System.out.println(x.length);
}
}
✅ Correct Answer: A) Compile-time error: "array required, but int found"
In the declaration `int x[], y;`, `x` is declared as an `int` array (due to `[]` attached to `x`), but `y` is declared as a single `int` primitive. Attempting to access `y` with an index (e.g., `y[0]`) treats it as an array, which is an illegal operation for a primitive `int` variable, resulting in a compile-time error.
Q2696medium
A class `Child` implements `Serializable`, but its immediate superclass `Parent` does not. During the serialization of a `Child` object, what happens regarding the fields inherited from `Parent`?
✅ Correct Answer: C) `Parent`'s fields are not serialized; they are initialized to their default values by `Parent`'s no-argument constructor upon deserialization.
If a superclass is not serializable, its fields are not part of the serialized stream. Upon deserialization, these fields are initialized by invoking the superclass's no-argument constructor.
Q2697hardcode output
What is the output of this code?
java
import java.util.ArrayList;
class MyObject {
int value;
public MyObject(int value) { this.value = value; }
public String toString() { return "O:" + value; }
}
public class Test {
public static void main(String[] args) {
ArrayList<MyObject> originalList = new ArrayList<>();
originalList.add(new MyObject(1));
originalList.add(new MyObject(2));
ArrayList<MyObject> clonedList = (ArrayList<MyObject>) originalList.clone();
originalList.get(0).value = 10;
originalList.add(new MyObject(3));
System.out.println("Original: " + originalList);
System.out.println("Cloned: " + clonedList);
}
}
`ArrayList.clone()` performs a shallow copy. This means it creates a new `ArrayList` object, but the elements within it are still references to the same `MyObject` instances as in the original list. Modifying `originalList.get(0).value` changes the object referenced by both lists, but adding a new object to `originalList` only affects the original.
Q2698medium
What is the primary characteristic of the `delete()` method when attempting to delete a directory using a `File` object?
✅ Correct Answer: C) It returns `false` if the directory is not empty, failing to delete it.
The `delete()` method can only delete empty directories. If the directory contains files or other subdirectories, it will fail and return `false`, requiring manual recursive deletion.
Q2699medium
`java.util.TreeMap` primarily implements which set of interfaces, reflecting its sorted and navigable nature?
✅ Correct Answer: C) `Map`, `SortedMap`, `NavigableMap`
`TreeMap` is a `Map` that stores its entries in a sorted order, thus implementing `SortedMap`. Furthermore, it provides methods for navigating the map, making it implement `NavigableMap`.
Q2700easycode error
What is the error in this Java code?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterError7 {
public static void main(String[] args) throws IOException {
FileWriter writer = FileWriter("another.txt"); // Missing 'new' keyword
writer.write("Sample text.");
writer.close();
}
}
✅ Correct Answer: A) The `new` keyword is missing when instantiating `FileWriter`.
To create an instance of a class, the `new` keyword must be used before the constructor call. `FileWriter("another.txt")` without `new` is not a valid statement for object creation.