When using instances of a mutable class as elements in a `HashSet`, what is the most robust design principle regarding the `equals()` and `hashCode()` methods to prevent unexpected behavior and maintain the integrity of the set?
✅ Correct Answer: B) The `equals()` and `hashCode()` methods should only rely on fields that are declared `final` or are effectively immutable after the object's initial construction.
For mutable objects in a `HashSet`, if fields used in `hashCode()` or `equals()` change after the object is added, the set's ability to locate or recognize that object will be compromised. Basing these methods only on immutable fields ensures consistent identity.
Q2902easycode output
What is the output of this code?
java
public class MyClass {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: System.out.print("Monday"); break;
case 2: System.out.print("Tuesday"); break;
case 3: System.out.print("Wednesday"); break;
default: System.out.print("Unknown");
}
}
}
✅ Correct Answer: C) Wednesday
The value of 'day' is 3, which matches 'case 3'. The code inside this case block is executed, printing 'Wednesday', and then 'break' prevents fall-through.
Q2903easycode output
What does this code print?
java
interface Playable {
void play();
}
class Song implements Playable {
@Override
public void play() {
System.out.println("Playing music.");
}
}
public class Main {
public static void main(String[] args) {
Song mySong = new Song();
mySong.play();
}
}
✅ Correct Answer: A) Playing music.
The `Song` class correctly implements the `play()` method defined in the `Playable` interface. Calling `mySong.play()` executes this implementation.
Q2904easy
Which method is used to retrieve and remove the head of a Queue, returning null if the queue is empty?
✅ Correct Answer: C) poll()
The `poll()` method retrieves and removes the head of the queue. It returns `null` if the queue is empty, making it a safer option for bounded queues.
Q2905easy
Which of the following describes the type of inheritance Java supports directly?
✅ Correct Answer: C) Single inheritance
Java supports single inheritance directly, meaning a class can only extend one other class at a time. Multilevel inheritance is a sequence of single inheritances.
Q2906easy
If the specified file does not exist when a `FileWriter` is instantiated, what happens by default?
✅ Correct Answer: B) It creates a new, empty file.
If the specified file does not exist, `FileWriter` will automatically create a new empty file at that path before writing.
Q2907easycode error
What is the compilation error in the `Main` class?
java
class Book {
String title;
public Book(String t) {
this.title = t;
}
}
public class Main {
public static void main(String[] args) {
Book myBook = new Book();
System.out.println(myBook.title);
}
}
✅ Correct Answer: A) The constructor `Book()` is undefined
When a custom constructor with arguments is defined, Java no longer automatically provides the default no-argument constructor. You must call an explicitly defined constructor.
Q2908hard
A `Serializable` singleton class implements `private Object readResolve()` method. What is the primary purpose of this method in this context?
✅ Correct Answer: A) To prevent multiple instances from being created during deserialization, ensuring the singleton property.
`readResolve()` is invoked when an object is deserialized and allows the class to substitute a different object for the one that was serialized, commonly used to maintain the singleton pattern.
Q2909medium
What does the `ceilingKey(K key)` method of `TreeMap` return?
✅ Correct Answer: C) The least key greater than or equal to `key`.
The `ceilingKey(K key)` method returns the least key in this map that is greater than or equal to the given `key`, or `null` if there is no such key.
Q2910easycode error
What kind of error will occur when compiling this Java code?
java
public class Main {
public static void main(String[] args) {
int value = 5;
if (value > 0) {
System.out.println("Positive");
else {
System.out.println("Non-positive");
}
}
}
✅ Correct Answer: D) Syntax Error: Missing closing curly brace for the 'if' block.
The 'if' block starts with an opening brace `{` but is missing its corresponding closing brace `}` before the 'else' keyword. This makes the 'else' appear outside of a valid 'if' structure, resulting in a syntax error for the unclosed 'if' block.
Q2911medium
What is the primary purpose of using a labeled `continue` statement in Java?
✅ Correct Answer: C) To skip the remainder of the current iteration of a specific outer loop and proceed to its next iteration.
A labeled `continue` statement is used to skip the remainder of the current iteration of a specific labeled outer loop and proceed to its next iteration. This provides fine-grained control over nested loop flow.
Q2912hardcode output
What does this code print?
java
import java.util.TreeSet;
import java.util.Comparator;
public class App {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
if (s1 == null && s2 == null) return 0;
if (s1 == null) return -1;
if (s2 == null) return 1;
return s1.compareTo(s2.toLowerCase()); // Case-insensitive comparison
}
});
set.add("Apple");
set.add(null);
set.add("banana");
set.add("apple"); // Case-insensitive duplicate
System.out.println(set);
}
}
✅ Correct Answer: A) [null, Apple, banana]
The custom Comparator handles nulls by placing them first. It also performs a case-insensitive comparison (s1.compareTo(s2.toLowerCase())). Thus, 'Apple' and 'apple' are considered the same, and only one is kept. The final order is null, then 'Apple', then 'banana'.
Q2913easycode error
What kind of error will occur when compiling the following Java code snippet?
java
import java.io.File;
import java.io.FileReader;
public class FileError4 {
public static void main(String[] args) {
File file = new File("input.txt");
FileReader reader = new FileReader(file);
System.out.println("Reader created.");
}
}
✅ Correct Answer: B) A compilation error: `unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown`.
The `FileReader` constructor can throw a `FileNotFoundException` (a subclass of `IOException`), which is a checked exception. It must either be caught using a `try-catch` block or declared in the method signature using `throws IOException`.
Q2914mediumcode error
What is the compilation error in the following Java code?
java
public class DoubleToInt {
public static void main(String[] args) {
double decimalValue = 123.45;
int wholeNumber = decimalValue;
System.out.println(wholeNumber);
}
}
✅ Correct Answer: A) Incompatible types: possible lossy conversion from double to int
Assigning a `double` (a wider data type) to an `int` (a narrower data type) without an explicit cast is a 'lossy conversion' because it might result in loss of precision, leading to a compilation error.
Q2915easycode error
What compile-time error will this code produce?
java
class MyProcessor implements Runnable {
protected void run() {
System.out.println("Processing data...");
}
}
public class Main {
public static void main(String[] args) {
MyProcessor processor = new MyProcessor();
new Thread(processor).start();
}
}
✅ Correct Answer: A) Error: MyProcessor is not abstract and does not override abstract method run() in Runnable
The `run()` method in the `Runnable` interface is `public`. Overriding methods cannot reduce the visibility of the method. By declaring `run()` as `protected`, it does not correctly override the `public run()` method, leading to a compile error about the missing `run()` implementation.
Q2916mediumcode output
What does this Java code print?
java
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
TreeSet set = new TreeSet<>();
set.add(10);
try {
set.add("hello");
System.out.println(set);
} catch (ClassCastException e) {
System.out.println("ClassCastException caught!");
}
}
}
✅ Correct Answer: A) ClassCastException caught!
A `TreeSet` without a specified `Comparator` uses the natural ordering of its elements. If elements of incompatible types (like `Integer` and `String`) are added, the `TreeSet` attempts to compare them, resulting in a `ClassCastException` at runtime.
Q2917easy
Which part of a method signature MUST differ for method overloading to be valid in Java?
✅ Correct Answer: C) The parameter list.
For methods to be overloaded, they must have the same name but their parameter lists must be unique. The return type and access modifier are not considered part of the method signature for overloading purposes.
Q2918hard
Consider a `TreeSet` populated with custom objects where the `Comparator` used to order them returns 0 for two objects, `A` and `B`, even though `A.equals(B)` evaluates to `false`. What is the consequence of this `Comparator`'s behavior within the `TreeSet`?
✅ Correct Answer: B) The `TreeSet` will treat `A` and `B` as equal, and only one of them (the first one added) will be present in the set.
The `TreeSet` relies solely on the `compareTo()` or `compare()` method for determining uniqueness. If a `Comparator` returns 0 for two objects, the `TreeSet` considers them equal and will only store one instance, even if their `equals()` method returns false.
Q2919easycode error
What is wrong with this Java code?
java
import java.util.function.Runnable;
public class Test {
public static void main(String[] args) {
Runnable r = () ->
System.out.println("Line 1");
System.out.println("Line 2");
}
}
✅ Correct Answer: B) When a lambda expression's body contains multiple statements, it must be enclosed in curly braces `{}`.
If a lambda expression's body consists of more than one statement, those statements must be enclosed within curly braces `{}` to form a statement block. Without them, only the first statement is considered part of the lambda.
Q2920hardcode 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 ForEachRemainingCME {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> iterator = list.iterator();
list.add("D"); // External modification
iterator.forEachRemaining(System.out::print);
}
}
✅ Correct Answer: A) java.util.ConcurrentModificationException
Modifying the list structurally (list.add("D")) after getting its iterator, and then attempting to use that iterator with forEachRemaining, triggers the fail-fast mechanism of ArrayList's iterator, resulting in a ConcurrentModificationException.