What is one key capability that `ListIterator` offers but `Iterator` does not?
✅ Correct Answer: C) The ability to add new elements to the collection.
`ListIterator` extends `Iterator` and adds methods like `add()`, `set()`, `hasPrevious()`, and `previous()` to allow for bidirectional traversal and element modification/addition during iteration.
Q2462medium
Which of the following represents the correct syntax for a lambda expression that takes no arguments and performs an action (returns nothing), for example, implementing `Runnable`?
✅ Correct Answer: A) `() -> {}`
For lambda expressions with no arguments, an empty pair of parentheses `()` is used to represent the argument list, followed by the arrow `->` and the body.
Q2463hard
In a design where multiple implementations share common state initialization logic and some non-abstract methods, but require distinct implementations for other methods, which Java construct is generally preferred for achieving this abstraction?
✅ Correct Answer: A) An `abstract` class
An abstract class can define instance variables and a constructor to manage shared state initialization, and include concrete non-abstract methods alongside abstract ones, which interfaces cannot do with instance state.
Q2464medium
Which of the following operations is NOT directly supported by the standard `java.util.Iterator` interface?
✅ Correct Answer: D) Adding new elements to the collection during iteration.
The standard `Iterator` provides methods for checking, retrieving, and removing elements. Adding elements is a feature of `ListIterator`, not the basic `Iterator`.
Q2465medium
If a custom exception `MyCheckedException` extends `java.lang.Exception`, what is the implication for a method `foo()` that might throw it?
✅ Correct Answer: A) Method `foo()` must explicitly declare `throws MyCheckedException` or handle it with a `try-catch` block.
Checked exceptions, like those extending `java.lang.Exception`, mandate that calling methods either declare them using `throws` or enclose the throwing code in a `try-catch` block.
Q2466medium
What is a key advantage of implementing the `Externalizable` interface over `Serializable`?
✅ Correct Answer: C) `Externalizable` gives the developer complete control over the serialization format and process.
`Externalizable` requires implementing `writeExternal()` and `readExternal()`, granting explicit control over the entire serialization and deserialization process, which can lead to better performance or custom formats.
Q2467easy
What happens if a `break` statement is omitted from a `case` block in a Java `switch` statement?
✅ Correct Answer: C) Execution continues to the next `case` block, regardless of whether it matches (fall-through).
Without a `break` statement, the execution 'falls through' to the next `case` block, executing its statements until a `break` is encountered or the `switch` statement ends.
Q2468mediumcode error
What is the compilation error in the following Java record definition?
java
public record Person(String name, int age) {
public void setName(String newName) {
this.name = newName; // Attempt to modify a record component
}
}
✅ Correct Answer: A) Cannot assign a value to final variable 'name'
Record components are implicitly final, meaning they cannot be modified after object construction. Attempting to assign a new value to 'this.name' within a method will result in a compile-time error.
Q2469medium
How can you initialize a `TreeMap` to store its keys in a custom, non-natural order (e.g., descending order for `Integer` keys)?
✅ Correct Answer: B) By passing a `Comparator` instance to the `TreeMap` constructor.
To enforce a custom ordering in `TreeMap`, a `Comparator` object must be provided as an argument to one of the `TreeMap` constructors. This `Comparator` will then be used for all key comparisons.
Q2470easy
Which keyword is used to create a new object (instantiate a class) in Java?
✅ Correct Answer: C) `new`
The `new` keyword is essential for creating an instance of a class, which allocates memory for the new object and calls its constructor.
Q2471mediumcode error
What error occurs when compiling this code?
java
import java.io.IOException;
public class MyClass {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("mydata.txt"); // Missing import for FileReader
int data = fr.read();
System.out.println(data);
fr.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Compile-time error: cannot find symbol class FileReader
The code fails to compile because the `FileReader` class is not explicitly imported from the `java.io` package. The compiler cannot resolve the symbol `FileReader` without its fully qualified name or an import statement.
Q2472easy
What does the `continue` keyword do when encountered inside a loop in Java?
✅ Correct Answer: B) It skips the current iteration and proceeds to the next iteration of the loop.
The `continue` keyword is used to skip the rest of the current iteration of a loop and proceed to the beginning of the next iteration.
Q2473mediumcode output
What is the output of this code?
java
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class BufferedReaderTest {
public static void main(String[] args) {
String data = "Hello";
BufferedReader br = new BufferedReader(new StringReader(data));
try {
System.out.println(br.readLine());
br.close();
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Hello
Caught: Stream closed
The first `readLine()` successfully prints 'Hello'. After `br.close()`, attempting to read again from the closed stream throws an `IOException` with the message "Stream closed".
Q2474easycode error
What compilation error will occur in the following Java code?
java
abstract class LivingThing {
public static abstract void breathe();
}
✅ Correct Answer: C) Error: Illegal combination of modifiers: 'abstract' and 'static'
Abstract methods are meant to be overridden by instances of subclasses, so they cannot be declared as static. Static methods belong to the class, not an instance.
Q2475medium
Which of the following is true regarding `String` objects in Java?
✅ Correct Answer: C) They are thread-safe due to their immutability.
Due to their immutability, `String` objects are inherently thread-safe because their internal state cannot be modified after creation, eliminating concerns about concurrent modifications. The hash code is typically cached after the first calculation, and `replace()` returns a new `String` object, not modifies the original.
Q2476hardcode error
What does this code print?
java
import java.io.*;
public class BufferMarkTest {
public static void main(String[] args) {
String data = "Hello, World!";
try (StringReader sr = new StringReader(data);
BufferedReader br = new BufferedReader(sr)) {
br.mark(5); // Mark at 5 characters
for (int i = 0; i < 7; i++) { // Read more than 5 characters
br.read();
}
br.reset(); // Should fail
System.out.println((char)br.read());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Error: Resetting to an invalid mark
The `reset()` method is called after more characters than the `readlimit` (5) have been read since `mark()`. This invalidates the mark, causing an `IOException` with a message indicating an invalid reset.
Q2477medium
Which method should be used to retrieve, but not remove, the head of the queue, returning `null` if the queue is empty?
✅ Correct Answer: C) peek()
`peek()` retrieves, but does not remove, the head of the queue, returning `null` if the queue is empty. `element()` does the same but throws `NoSuchElementException` if empty.
Q2478mediumcode output
What does this Java program output?
java
import java.util.function.Supplier;
public class Test {
public static void main(String[] args) {
String greeting = "Hello";
Supplier<String> lazyGreeting = () -> {
System.out.println("Generating greeting...");
return greeting + " World!";
};
System.out.println("Before get()");
String message = lazyGreeting.get();
System.out.println(message);
}
}
✅ Correct Answer: A) Before get()
Generating greeting...
Hello World!
The lambda expression for the `Supplier` is only executed when `get()` is called. Therefore, "Before get()" prints first, followed by the message from inside the lambda, and then the returned value.
Q2479hard
How does the execution of a `finally` block interact with control flow statements like `break` or `continue` that might be present in the `try` or `catch` blocks?
✅ Correct Answer: C) The `finally` block will always execute before the `break` or `continue` statement's control transfer takes effect.
Regardless of whether control leaves the `try` or `catch` block via normal completion, an exception, or a control flow statement like `break` or `continue`, the `finally` block is guaranteed to execute first.
Q2480hard
When designing a custom collection class that implements the `java.lang.Iterable` interface, what is the most crucial consideration for the `iterator()` method's implementation to ensure robust and predictable behavior, especially in scenarios involving concurrent access or resource management?
✅ Correct Answer: D) Designing the `Iterator` to either be fail-fast or fail-safe, depending on the desired consistency model, and clearly documenting its behavior.
The most crucial consideration is to explicitly design the iterator's behavior regarding concurrent modifications. Whether it's fail-fast or fail-safe dictates its consistency model and error handling, which must be clearly defined and implemented to ensure robust and predictable behavior.