✅ Correct Answer: A) The code prints "Serialization Error: java.util.TreeMapError7$$Lambda$1/0 not serializable".
For a `TreeMap` to be successfully serialized, its `Comparator` (if provided) must also be `Serializable`. A lambda expression or an anonymous inner class is typically not `Serializable` by default unless explicitly made so, leading to a `NotSerializableException`.
Q1922medium
How can you instantiate a `FileWriter` to append data to an existing file instead of overwriting its content?
✅ Correct Answer: B) `new FileWriter("file.txt", true);`
The `FileWriter` constructor `FileWriter(String fileName, boolean append)` allows specifying `true` for the `append` parameter to add data to the end of the file.
Q1923easycode error
What will happen when this Java code is compiled and executed?
java
class MyClass {
public void invalidThrow() {
throw "This is not an exception";
}
}
✅ Correct Answer: A) Compilation Error
The `throw` keyword in Java can only be used with objects that are instances of `java.lang.Throwable` or its subclasses. A `String` object is not a `Throwable`, so the compiler reports an incompatible types error.
Q1924easycode error
What is the error in the following Java code?
java
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
java
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
Cat c = (Cat) a;
System.out.println(c);
}
}
✅ Correct Answer: A) Runtime error: java.lang.ClassCastException
Even though 'a' is declared as an Animal, it refers to a Dog object. You cannot cast a Dog object to a Cat object because they are siblings in the inheritance hierarchy, not parent-child, leading to a ClassCastException at runtime.
Q1925mediumcode error
What is the compilation error in the following code?
java
abstract class Shape {
abstract void draw();
void getArea() {
System.out.println("Calculating area...");
}
}
class Circle extends Shape {
// Missing implementation of draw()
}
✅ Correct Answer: A) Error: Circle is not abstract and does not override abstract method draw() in Shape
A concrete class (non-abstract) that extends an abstract class must provide implementations for all inherited abstract methods. 'Circle' fails to implement 'draw()', causing a compilation error.
Q1926hardcode output
What is the output of this code?
java
public class ThreadLocalIsolation {
private static ThreadLocal<String> userSession = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
userSession.set("MainUser");
Thread t1 = new Thread(() -> {
userSession.set("User1");
System.out.println("T1: " + userSession.get());
});
Thread t2 = new Thread(() -> {
userSession.set("User2");
System.out.println("T2: " + userSession.get());
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Main: " + userSession.get());
}
}
✅ Correct Answer: A) T1: User1
T2: User2
Main: MainUser
Each `ThreadLocal` variable maintains a separate, independent value for each thread that accesses it. Therefore, `userSession.get()` in the main thread will return the value set by the main thread, and similarly for T1 and T2.
Q1927hard
Regarding `java.util.PriorityQueue`, which statement is true concerning its behavior and properties?
✅ Correct Answer: C) `PriorityQueue` orders elements based on their natural ordering or by a provided `Comparator`, but it does not guarantee FIFO order for elements with equal priority.
PriorityQueue is not thread-safe, does not permit null elements (even with a custom comparator due to internal usage of `compareTo`), and while it orders by priority, it does not guarantee FIFO for elements with the same priority. `peek()` only retrieves, it does not remove the element.
Q1928mediumcode output
What is the output of this code?
java
import java.io.File;
import java.io.IOException;
public class FileCreation {
public static void main(String[] args) throws IOException {
File file = new File("myFile.txt");
boolean createdFirst = file.createNewFile();
boolean createdSecond = file.createNewFile(); // Attempt to create again
file.delete(); // Clean up
System.out.println(createdFirst + ", " + createdSecond);
}
}
✅ Correct Answer: A) true, false
`createNewFile()` returns `true` if the file was created and `false` if the file already exists. The second call finds the file already existing.
Q1929easycode error
What is the compile-time error in this Java code snippet?
java
public class ArrayTest {
public static void main(String[] args) {
int arr[5];
arr[0] = 1;
}
}
✅ Correct Answer: A) Compile-time error: illegal start of expression
The declaration `int arr[5];` is C/C++ style and not valid Java syntax. In Java, array brackets are typically placed after the type, like `int[] arr;` or `int arr[];`.
Q1930easycode error
What is the outcome when compiling and running this Java code?
java
import java.util.ArrayList;
import java.util.List;
public class FinalVarListReassignment {
public static void main(String[] args) {
final var list = new ArrayList<String>();
list.add("Item1");
list = new ArrayList<String>();
System.out.println(list.size());
}
}
✅ Correct Answer: A) Compile-time error: "The final local variable list cannot be assigned."
Declaring a variable with `final var` means the reference itself cannot be reassigned after its initial declaration. While the `ArrayList` object it refers to is mutable, `final` prevents the `list` variable from pointing to a different `ArrayList` instance.
Q1931hard
Why is `Thread.stop()` considered inherently unsafe and deprecated?
✅ Correct Answer: B) It releases all monitors (locks) held by the target thread, potentially leaving shared objects in an inconsistent, corrupt state.
`Thread.stop()` causes the target thread to release all acquired monitors (locks) immediately. This can leave shared data in an inconsistent state, leading to data corruption that other threads might then observe.
Q1932hardcode output
What is the output of this code?
java
import java.util.TreeSet;
public class App {
static class MutableElement implements Comparable<MutableElement> {
int value;
public MutableElement(int value) { this.value = value; }
public void setValue(int value) { this.value = value; }
@Override public int compareTo(MutableElement other) { return Integer.compare(this.value, other.value); }
@Override public String toString() { return String.valueOf(value); }
}
public static void main(String[] args) {
TreeSet<MutableElement> set = new TreeSet<>();
MutableElement e1 = new MutableElement(10);
MutableElement e2 = new MutableElement(20);
set.add(e1);
set.add(e2);
e1.setValue(30); // Mutate e1, changing its ordering
System.out.println(set.first().value);
System.out.println(set.last().value);
}
}
✅ Correct Answer: A) 30
20
When 'e1' is added, it's placed as the first element due to its initial value (10). Mutating 'e1' to 30 after insertion does not re-order the set. 'set.first()' still returns the original 'e1' object, whose value is now 30. 'set.last()' still returns 'e2' which holds value 20. This demonstrates the broken invariant of the TreeSet when mutable elements are changed after insertion.
Q1933hard
How does declaring a `private` field as `final` contribute to encapsulation, especially when dealing with mutable object references?
✅ Correct Answer: A) It ensures that the reference itself cannot be changed after initialization, but the object it points to can still be modified, potentially weakening encapsulation if the object is mutable.
Declaring a `private final` field ensures the reference cannot be reassigned after construction, which is a form of encapsulation for the reference itself. However, if the referenced object is mutable, its internal state can still be changed, meaning `final` only protects the reference, not the object's state.
Q1934easycode error
What is the compilation error in the `Main` class?
java
class MyClass {
private String name = "Test";
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println(obj.name);
}
}
✅ Correct Answer: A) `name` has private access in `MyClass`
The `name` field is declared as `private` in `MyClass`, meaning it cannot be accessed directly from outside the class where it's defined.
Q1935easy
What is the underlying data structure used by `java.util.HashSet` for storing its elements?
✅ Correct Answer: C) A HashMap
`HashSet` internally uses a `HashMap` to store its elements. Each element added to the `HashSet` becomes a key in the internal `HashMap`, with a dummy value associated with it.
Q1936mediumcode error
What is the compilation error in the provided Java code?
java
abstract class Shape {
public abstract void draw();
}
public class Main {
public static void main(String[] args) {
Shape s = new Shape();
s.draw();
}
}
✅ Correct Answer: A) Cannot instantiate the type Shape
Abstract classes cannot be instantiated directly. To use an abstract class, you must create a concrete subclass that implements its abstract methods, and then instantiate the subclass.
Q1937easy
What happens if you call the `run()` method directly on a `Thread` object instead of `start()`?
✅ Correct Answer: B) The code runs in the current thread, not a new thread.
Calling `run()` directly executes the code in the calling thread, behaving like a regular method call, without creating a new thread of execution.
Q1938easy
When using an `if-else if-else` ladder, what is true about the execution of its blocks?
✅ Correct Answer: B) Only the first `true` condition's block is executed, and the rest are skipped.
In an `if-else if-else` structure, once a condition evaluates to true and its corresponding block is executed, the entire `if` statement structure is exited, preventing further checks.
Q1939easycode error
What is the error in the following Java code?
java
public class Main {
public static void main(String[] args) {
String str = "123";
Integer num = (Integer) str;
System.out.println(num);
}
}
✅ Correct Answer: A) Compile-time error: Inconvertible types: cannot cast java.lang.String to java.lang.Integer.
You cannot directly cast a String object to an Integer object in Java. These are unrelated types in the class hierarchy, leading to a compile-time error.
Q1940hard
What is "false sharing" in the context of multi-threaded programming and how can it impact performance?
✅ Correct Answer: B) It describes a scenario where threads attempt to read and write to different, unrelated variables that reside on the same CPU cache line, causing cache invalidations.
False sharing occurs when two or more threads operate on distinct variables that, coincidentally, reside on the same CPU cache line. Even though the variables are logically independent, the cache coherence protocol invalidates and re-synchronizes the entire cache line across CPU cores whenever one of the variables is modified, leading to significant performance degradation.