import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(2);
list.add(4);
list.removeFirstOccurrence(2); // Removes the first '2'
list.add(5);
list.removeLastOccurrence(2); // Removes the remaining '2'
System.out.println(list);
}
}
✅ Correct Answer: B) [1, 3, 4, 5]
Initially, the list is `[1, 2, 3, 2, 4]`. `removeFirstOccurrence(2)` removes the `2` at index 1, resulting in `[1, 3, 2, 4]`. Then `add(5)` makes it `[1, 3, 2, 4, 5]`. Finally, `removeLastOccurrence(2)` removes the `2` at index 2, leaving `[1, 3, 4, 5]`.
✅ Correct Answer: A) Task 1 Started
Executor Shutdown Called
`shutdownNow()` attempts to stop all actively executing tasks and halts the processing of waiting tasks. Task 1 is likely started but interrupted by `shutdownNow()` before finishing its sleep, and Task 2 is not executed. The order of 'Executor Shutdown Called' can vary depending on precise timing relative to Task 1's `println` and `sleep`.
Q2103hard
Which of the following is a key difference or characteristic when comparing `System.arraycopy()` and `Arrays.copyOf()`?
✅ Correct Answer: C) `System.arraycopy()` can be more efficient for copying portions of an array to another *existing* array, whereas `Arrays.copyOf()` is designed to create a *new* array of a specified length with copied elements.
`System.arraycopy()` copies between existing source and destination arrays, offering fine-grained control over start/end indices. `Arrays.copyOf()` always creates a new array of a specified length and copies elements into it, useful for resizing or creating a complete copy.
Q2104hard
In the context of `FileWriter`, what is the primary difference in effect between calling `flush()` and `close()` regarding data persistence to the file system?
✅ Correct Answer: B) `flush()` ensures that any buffered characters are written to the underlying `OutputStream` (and potentially the OS file buffer), keeping the stream open; `close()` does this and additionally releases all associated system resources, preventing further writes.
`flush()` forces any buffered data to be written to the underlying stream (and eventually the OS buffer), but the `Writer` remains open. `close()` performs a flush and then releases all system resources, making the `Writer` unusable for further operations.
Q2105hard
Consider a scenario where `Object[] objArr = new String[5];`. Which of the following statements about casting this array is true?
✅ Correct Answer: C) `objArr` can be safely cast back to `String[]` without any runtime exceptions.
The initialization `Object[] objArr = new String[5];` is valid due to array covariance, meaning `objArr` actually refers to a `String[]` object. Therefore, casting `objArr` back to `String[]` is safe and will not throw a `ClassCastException`. Assigning an `Integer` to an element would cause an `ArrayStoreException`.
If a file does not exist, it inherently cannot be read, written, or executed. Therefore, `exists()`, `canRead()`, `canWrite()`, and `canExecute()` will all return `false` for a non-existent file.
Q2107easy
What is the effect of using the `transient` keyword on a field during serialization?
✅ Correct Answer: B) It prevents the field from being serialized.
The `transient` keyword marks a field to indicate that it should not be included in the default serialization process, meaning its value will not be saved.
Q2108mediumcode error
What error will occur when compiling and running this Java code?
java
import java.io.*;
import java.util.HashSet;
import java.util.Set;
class NonSerializableItem { // Does not implement Serializable
String data;
public NonSerializableItem(String data) {
this.data = data;
}
}
public class HashSetError10 {
public static void main(String[] args) {
Set<NonSerializableItem> items = new HashSet<>();
items.add(new NonSerializableItem("Test"));
try {
FileOutputStream fos = new FileOutputStream("set.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(items); // ERROR line
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: B) Runtime Error: java.io.NotSerializableException.
A `HashSet` itself is `Serializable`, but if it contains elements that are not `Serializable`, attempting to serialize the `HashSet` will result in a `java.io.NotSerializableException` at runtime for the non-serializable elements.
Q2109hard
A `TreeSet` is initialized with a custom `Comparator<String>` that does not explicitly handle null inputs. If an attempt is made to add `null` to this `TreeSet`, what is the most likely outcome?
✅ Correct Answer: B) A `NullPointerException` is thrown when the `Comparator.compare()` method is invoked with a `null` argument.
If a custom `Comparator` is provided and does not explicitly handle nulls, attempting to add `null` to the `TreeSet` will typically result in a `NullPointerException` when the `Comparator.compare()` method is invoked with a null reference.
Q2110mediumcode error
What will be the compilation error in this code?
java
class Logger {
public static void logMessage(String msg) {
System.out.println("Log: " + msg);
}
}
class FileLogger extends Logger {
@Override
public void logMessage(String msg) {
System.out.println("File Log: " + msg);
}
}
✅ Correct Answer: A) Error: Method does not override method from its superclass
A static method cannot be overridden by a non-static method (nor vice-versa). Static methods are resolved at compile time based on the reference type, not at runtime. The '@Override' annotation indicates an intention to override, which is not possible here.
Q2111easy
What is the primary purpose of method overriding in Java?
✅ Correct Answer: A) To provide a new, specific implementation for a method already defined in the superclass.
Method overriding allows a subclass to provide its own specific implementation for a method that is already defined in its superclass, tailoring its behavior.
Q2112easycode output
What is the output of this code?
java
class ReentrantLockTest {
public synchronized void methodA() {
System.out.print("A");
methodB();
}
public synchronized void methodB() {
System.out.print("B");
}
}
public class MyProgram {
public static void main(String[] args) throws InterruptedException {
ReentrantLockTest obj = new ReentrantLockTest();
Thread t1 = new Thread(() -> obj.methodA());
Thread t2 = new Thread(() -> obj.methodB());
t1.start();
t2.start();
t1.join();
t2.join();
}
}
✅ Correct Answer: C) ABB
Java's intrinsic locks are reentrant. `t1` acquires the lock for `obj`, executes `methodA`, and then re-acquires the same lock to call `methodB`. It prints 'A' then 'B'. While `t1` holds the lock, `t2` attempts to call `methodB` but must wait for `t1` to release the lock. After `t1` completes, `t2` acquires the lock, executes `methodB`, and prints 'B'. The final output is 'ABB'.
Q2113hardcode error
What kind of runtime error or unexpected behavior will occur when running this Java code, primarily related to thread lifecycle?
java
public class ThreadBomb {
public static void main(String[] args) {
int i = 0;
while (true) {
new Thread(() -> {
try {
Thread.sleep(Long.MAX_VALUE); // Keep threads alive indefinitely
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "Thread-" + i++).start();
System.out.println("Created thread: " + (i-1));
}
}
}
✅ Correct Answer: B) An `OutOfMemoryError` will be thrown because the JVM runs out of resources to create new native threads.
Each `java.lang.Thread` requires a certain amount of native memory (stack space, etc.). Continuously creating new threads that stay alive indefinitely without releasing resources will eventually exhaust the JVM's ability to allocate more native memory for new threads, leading to an `OutOfMemoryError` (specifically, 'unable to create new native thread').
Q2114hardcode error
What will be the result of compiling this Java code?
java
class Parent {
public static void greet() {
System.out.println("Hello from Parent");
}
}
class Child extends Parent {
public static void greet() {
super.greet(); // Problematic line
System.out.println("Hello from Child");
}
public static void main(String[] args) {
Child.greet();
}
}
✅ Correct Answer: A) Compile-time error: Cannot use 'super' in a static context.
The `super` keyword is used to refer to members of the immediate superclass for the current *instance*. Static methods belong to the class, not an instance, so `super` cannot be used within a static context, leading to a compile-time error.
Q2115medium
What is the primary mechanism that enables runtime polymorphism in Java?
✅ Correct Answer: C) Method overriding
Method overriding allows a subclass to provide a specific implementation for a method that is already defined in its superclass, enabling different behaviors at runtime based on the actual object type.
Q2116hard
Given `class Animal {} class Dog extends Animal {} class Poodle extends Dog {}`. If you have `Animal a = new Dog();` and attempt `Poodle p = (Poodle) a;`, what is the most likely outcome at runtime?
✅ Correct Answer: C) A `ClassCastException` because the actual object type (`Dog`) is not a `Poodle` or a supertype of `Poodle`.
The actual object `a` refers to is a `Dog`. While `Poodle` extends `Dog`, a `Dog` object is not necessarily a `Poodle` object. Downcasting to a type that the actual object is not (and is not a supertype of) will result in a `ClassCastException`.
Q2117easy
What is necessary to ensure a `while` loop eventually terminates?
✅ Correct Answer: C) The loop body must modify a variable that eventually makes the condition `false`.
For a `while` loop to terminate, something inside its body must change the state such that the loop's boolean condition eventually evaluates to `false`.
Q2118medium
What is the primary requirement for an object to be eligible for standard Java serialization?
✅ Correct Answer: A) Implement `java.io.Serializable` interface.
The `Serializable` interface is a marker interface that signals the JVM that objects of this class can be serialized by the default serialization mechanism.
Q2119mediumcode output
What is the output of this Java program?
java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
boolean removed = numbers.remove(Integer.valueOf(2));
System.out.println(removed + " " + numbers);
}
}
✅ Correct Answer: A) true [1, 3]
When `remove()` is called with an `Integer` object (explicitly or via autoboxing), it attempts to remove the *object* equal to the value, not the element at the *index*. `Integer.valueOf(2)` removes the first occurrence of the value 2, returning `true`.
Q2120hardcode output
What is the output of this code?
java
public class Q8_DaemonThreadTermination {
public static void main(String[] args) throws InterruptedException {
Thread daemonThread = new Thread(() -> {
try {
int count = 0;
while (true) {
System.out.println("Daemon running: " + count++);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Daemon interrupted.");
} finally {
System.out.println("Daemon finally block.");
}
});
daemonThread.setDaemon(true);
daemonThread.start();
Thread.sleep(250);
System.out.println("Main thread exiting.");
}
}
✅ Correct Answer: B) Daemon running: 0
Daemon running: 1
Daemon running: 2
Main thread exiting.
Daemon threads are abruptly terminated by the JVM when all non-daemon threads finish. Consequently, the `finally` block of a daemon thread is generally not guaranteed to execute if the JVM exits due to the termination of the last non-daemon thread (in this case, `main`). The daemon prints a few messages then the main thread exits, stopping the JVM.