class MyThread extends Thread {
public void run() {
System.out.println("Thread running.");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join(); // Wait for thread to complete
System.out.println("Thread finished.");
t.start(); // Attempt to restart
}
}
✅ Correct Answer: A) Thread running.
Thread finished.
Exception in thread "main" java.lang.IllegalThreadStateException
A thread can only be started once. Calling `start()` on a thread that is already running or has completed will result in an `IllegalThreadStateException`.
Q1662easy
Which of the following interfaces does `java.util.LinkedList` implement?
✅ Correct Answer: C) `List` and `Deque`
`LinkedList` implements both the `List` interface for ordered collection functionalities and the `Deque` interface for double-ended queue operations.
Q1663easycode output
What is the output of this code?
java
public class StringTest {
public static void main(String[] args) {
String s = "Java";
System.out.println(s.charAt(1));
}
}
✅ Correct Answer: B) a
The `charAt(int index)` method returns the character at the specified index. String indices are 0-based, so index 1 corresponds to the second character, 'a'.
Q1664mediumcode error
What is the compilation error in the following Java code (Java 10+)?
java
public class VarNull {
public static void main(String[] args) {
var data = null;
System.out.println(data);
}
}
✅ Correct Answer: A) Cannot infer type for local variable initialized to 'null'
`var` cannot be used with a `null` initializer because `null` does not provide sufficient type information for the compiler to infer the variable's specific type.
Q1665hardcode error
What is the most likely error message(s) printed when executing this Java code snippet?
java
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.IOException;
class DualFaultWriter extends Writer {
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
throw new IOException("Write operation failed!");
}
@Override
public void flush() throws IOException { /* Do nothing */ }
@Override
public void close() throws IOException {
throw new IOException("Close operation failed!");
}
}
public class Test {
public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new DualFaultWriter())) {
bw.write("Important data."); // This throws the first exception
} catch (IOException e) {
System.err.println("Primary error: " + e.getMessage());
for (Throwable t : e.getSuppressed()) {
System.err.println("Suppressed error: " + t.getMessage());
}
}
}
}
✅ Correct Answer: A) Primary error: Write operation failed!
Suppressed error: Close operation failed!
In a `try-with-resources` block, if an exception is thrown in the `try` block and another exception is thrown during the implicit `close()` call, the exception from the `try` block is the primary exception, and the `close()` exception is added to its suppressed exceptions. The `DualFaultWriter` throws during `write` (primary) and `close` (suppressed).
Q1666hardcode output
What is the output of this Java code, demonstrating a common encapsulation breach?
java
import java.util.ArrayList;
import java.util.List;
class Wallet {
private final List<String> transactions;
public Wallet(List<String> initialTransactions) {
this.transactions = initialTransactions;
}
public List<String> getTransactions() {
return transactions;
}
}
public class Main {
public static void main(String[] args) {
List<String> txList = new ArrayList<>();
txList.add("Deposit");
Wallet myWallet = new Wallet(txList);
List<String> retrievedTx = myWallet.getTransactions();
retrievedTx.add("Withdrawal");
System.out.println(myWallet.getTransactions());
}
}
✅ Correct Answer: B) [Deposit, Withdrawal]
The `getTransactions()` method returns a direct reference to the internal `transactions` list. Because `List` is a mutable object, external code can modify the list, thereby changing the internal state of the `Wallet` object and breaking its encapsulation, even though the `transactions` field itself is `final`.
Q1667mediumcode error
What error will occur when compiling and running this Java code?
java
import java.util.HashSet;
import java.util.Set;
public class HashSetError5 {
public static void main(String[] args) {
Set<String> data = new HashSet<>();
data.add("Hello");
data.add(null);
data.add("World");
for (String s : data) {
if (s.equals("Hello")) { // ERROR if s is null
System.out.println("Found Hello");
}
}
}
}
✅ Correct Answer: B) Runtime Error: java.lang.NullPointerException.
A `HashSet` allows one `null` element. When iterating over the set, if the `null` element is encountered and a method (like `equals()`) is called on it, a `NullPointerException` will be thrown.
Q1668mediumcode error
What is the primary exception thrown at runtime when executing the following Java code snippet?
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"))) {
writer.close();
writer.write("Data");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
✅ Correct Answer: C) IOException: Stream closed
The `writer.close()` method is called prematurely, closing the stream. Subsequent attempts to write to a closed `BufferedWriter` using `writer.write("Data")` will result in an `IOException` with the message 'Stream closed'.
Q1669easy
In Java, can different rows in a two-dimensional array have different numbers of columns?
✅ Correct Answer: A) Yes, this is known as a jagged array.
Java allows for jagged (or ragged) arrays, where each row can be an array of a different length.
Q1670hard
What is the primary difference between a *compact constructor* and a *canonical constructor* in a Java record?
✅ Correct Answer: B) A compact constructor implicitly declares its parameters and automatically performs field assignments, primarily for adding validation or normalization logic.
The canonical constructor fully declares all record components as parameters and performs their assignments. A compact constructor is an abbreviated form that implicitly has the same parameters and automatically performs the component assignments, making it ideal for adding validation or normalization code.
Q1671easycode error
What type of error will occur when running this Java code?
java
public class MyTask {
private final Object lock = new Object();
public void performWait() throws InterruptedException {
// Missing synchronized(lock)
lock.wait();
System.out.println("Waited!");
}
public static void main(String[] args) throws InterruptedException {
MyTask task = new MyTask();
task.performWait();
}
}
✅ Correct Answer: A) java.lang.IllegalMonitorStateException
`wait()` must be called from within a synchronized block or method that holds the monitor lock on the object it is called on. Failing to do so results in an `IllegalMonitorStateException` at runtime.
Q1672hard
What is the typical time complexity for the `insert(int offset, String str)` method in `StringBuffer` when `str` is large and `offset` is in the middle of a very long existing sequence?
✅ Correct Answer: C) O(N)
`insert()` operations in `StringBuffer` (and `StringBuilder`) involve shifting characters in the underlying `char` array to make space for the new content. In the worst case (inserting in the middle), this requires shifting roughly half of the existing characters, leading to a time complexity of O(N), where N is the current length of the sequence.
Q1673easy
Can a Java HashMap store null keys and null values?
✅ Correct Answer: B) Yes, it can store one null key and multiple null values.
A HashMap allows one null key and multiple null values to be stored.
Q1674hardcode error
What kind of error will occur when compiling or running the following Java code?
java
public class SBError {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Mutable"); // Length 7
// Attempt to get substring from 0 to length + 1
String sub = sb.substring(0, sb.length() + 1);
System.out.println(sub);
}
}
✅ Correct Answer: A) java.lang.StringIndexOutOfBoundsException
The `substring(int start, int end)` method throws a `StringIndexOutOfBoundsException` if `end` is greater than `length()`. Here, `sb.length() + 1` (which is 8) exceeds the buffer's length (7).
Q1675hardcode output
What does this code print?
java
class Super {
int value = 10;
public void show() { System.out.println("Super show: " + value); }
}
class Sub extends Super {
int value = 20;
public void show() { System.out.println("Sub show: " + value); }
}
public class Test {
public static void main(String[] args) {
Super obj = new Sub();
System.out.println(obj.value);
obj.show();
}
}
✅ Correct Answer: A) 10
Sub show: 20
Instance variables are resolved at compile time based on the reference type (Super), hence `obj.value` accesses `Super.value`. Instance methods are resolved at runtime based on the actual object type (Sub), so `obj.show()` calls `Sub.show()` which uses `Sub`'s `value`.
Q1676hard
When a Java object is deserialized from a byte stream, how are its constructors typically handled?
✅ Correct Answer: C) No constructors of the class are invoked during standard deserialization (unless `Externalizable` is used).
By default, Java's serialization mechanism constructs an object by allocating memory and restoring field values without invoking any constructors of the class being deserialized. Constructors of non-serializable superclasses *might* be invoked, but not for the serializable class itself, unless it implements `Externalizable`.
Q1677easy
Which type of loop is most commonly used for explicit iteration with an `Iterator` object?
✅ Correct Answer: C) `while` loop
An explicit `Iterator` is typically used with a `while` loop, checking `hasNext()` as the loop condition and calling `next()` inside the loop body.
Q1678mediumcode error
What is the reason for the compilation error in this Java class, intended to be immutable?
java
public class ConditionalImmutable {
private final String data;
public ConditionalImmutable(boolean condition) {
if (condition) {
this.data = "Initialized";
}
// 'data' might not be initialized if condition is false
}
}
✅ Correct Answer: A) Variable 'data' might not have been initialized
A 'final' field must be initialized exactly once, either in its declaration or in the constructor. If its initialization is conditional and not guaranteed by all constructor paths, the compiler will report that the variable might not have been initialized.
Q1679hard
Consider the declaration: `final int[] myNumbers = {1, 2, 3};`. Which of the following operations is *not* permitted?
✅ Correct Answer: B) `myNumbers = new int[]{4, 5, 6};`
The `final` keyword on an array reference means the reference itself cannot be reassigned to point to a different array object. It does not make the array's contents immutable; individual elements can still be modified.
Q1680easycode error
Which error will occur when running this Java code?
java
import java.io.FileReader;
import java.io.IOException;
public class FileReaderIssue {
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader(""); // Empty string filename
int data = reader.read();
reader.close();
}
}
✅ Correct Answer: B) java.io.FileNotFoundException at runtime.
An empty string `""` as a filename typically refers to a non-existent file or an invalid path in most operating systems, leading to a `FileNotFoundException` at runtime.