Does this Java code compile? If not, what is the compile-time error?
java
import java.io.IOException;
public class UnreachableThrow {
public String execute() throws IOException {
System.out.println("Executing...");
if (true) {
return "Success";
}
throw new IOException("Should not reach here");
}
public static void main(String[] args) {
// new UnreachableThrow().execute();
}
}
✅ Correct Answer: B) Error: Unreachable statement at `throw new IOException(...)`.
The `if (true)` block ensures that `return "Success";` is always executed. Code after an unconditional `return` statement (or `throw` statement) is considered unreachable by the Java compiler, leading to a compile-time error.
Q3402mediumcode output
What is the content of 'output.txt' after this code executes?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterTest {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Hello, Java!");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: B) Hello, Java!
The FileWriter creates 'output.txt' if it doesn't exist and writes the string 'Hello, Java!' to it. The try-with-resources statement ensures the writer is closed, flushing the content.
Q3403easy
Every Java application has at least one thread of execution. What is this initial thread commonly called?
✅ Correct Answer: C) The main thread
The `main` method where a Java application starts execution runs within a thread known as the 'main thread'.
Q3404easy
Can a Java class have more than one constructor?
✅ Correct Answer: B) Yes, if they have different parameter lists (constructor overloading).
Java supports constructor overloading, allowing a class to have multiple constructors as long as each has a unique parameter list.
Q3405mediumcode error
What is the error in this Java code snippet?
java
public class MyClass {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Start");
sb.insert("World");
System.out.println(sb);
}
}
✅ Correct Answer: C) A compile-time error: No suitable method found for insert(java.lang.String).
The 'insert' method of StringBuilder requires an index as its first argument (e.g., `insert(int offset, String str)`). Calling it with only a String argument results in a compile-time error as no matching method signature is found.
Q3406easycode output
What is the output of this Java code?
java
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> isEven = num -> num % 2 == 0;
System.out.println(isEven.test(10));
}
}
✅ Correct Answer: A) true
The Predicate `isEven` checks if a number is even. Since 10 is even, `isEven.test(10)` returns true.
Q3407hard
A thread is in the `TIMED_WAITING` state due to `Thread.sleep(long milliseconds)`. If another thread calls `interrupt()` on it, what is the primary consequence for the sleeping thread?
✅ Correct Answer: B) It immediately transitions to `RUNNABLE`, throws `InterruptedException`, and clears its interrupt status.
When a thread sleeping via `Thread.sleep()` is interrupted, it immediately transitions to `RUNNABLE`, throws an `InterruptedException`, and clears its interrupted status.
Q3408hardcode error
What is the compilation error in the following Java code snippet?
java
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier<String> valueSupplier = () -> {
if (System.currentTimeMillis() % 2 == 0) {
return "Even time";
} else {
return 123; // This line will cause an error
}
};
System.out.println(valueSupplier.get());
}
}
✅ Correct Answer: A) Incompatible types: bad return type in lambda expression: int cannot be converted to String
The functional interface `Supplier<String>` expects the lambda expression to return a `String`. However, one branch of the lambda's conditional statement returns an `int` literal (123), which is incompatible with `String`, leading to a compilation error.
Q3409hardcode error
What is the compilation or runtime error when executing this Java code snippet?
java
import java.util.TreeSet;
class Person {
String name;
Person(String name) { this.name = name; }
}
public class Main {
public static void main(String[] args) {
TreeSet<Person> people = new TreeSet<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));
System.out.println(people.size());
}
}
✅ Correct Answer: A) java.lang.ClassCastException: class Person cannot be cast to class java.lang.Comparable
TreeSet requires elements to be naturally comparable (implement Comparable) or a Comparator must be provided in the constructor. Since Person does neither, a ClassCastException occurs at runtime when the first element is added and TreeSet attempts to compare it.
Q3410hard
A `HashSet` contains a mutable object `M`. After `M` is added, a field within `M` that is used in its `hashCode()` calculation is modified. What is the most likely consequence when attempting to retrieve or remove `M` from the `HashSet` using `contains(M)` or `remove(M)`?
✅ Correct Answer: A) The operations will fail to find `M` correctly, potentially returning `false` or behaving unexpectedly, because its hash bucket has changed.
When `M`'s `hashCode()` changes after insertion, `HashSet` will look for it in the original hash bucket (calculated at insertion), not the new one, leading to `contains()` returning `false` or `remove()` failing.
Q3411hardcode error
What error will this code produce at compile time?
java
public class MultiInitForLoopError {
public static void main(String[] args) {
int x = 10;
for (int i = 0, x = 20; i < 5; i++) {
System.out.println(i + x);
}
}
}
✅ Correct Answer: A) variable x is already defined in method main(java.lang.String[])
The loop initializer `int i = 0, x = 20;` attempts to declare a new variable `x` within the scope of the `for` loop, but a variable `x` is already declared in the `main` method's scope, leading to a duplicate variable declaration error.
Q3412hard
Which statement accurately describes the behavior of Java daemon threads upon JVM shutdown?
✅ Correct Answer: B) Daemon threads are abruptly terminated by the JVM without any finally blocks being guaranteed to execute, as soon as the last non-daemon thread finishes.
Daemon threads do not prevent the JVM from exiting. When the last non-daemon thread terminates, the JVM exits, abruptly terminating any running daemon threads without guarantees of resource cleanup.
Q3413mediumcode error
What error occurs when running this code?
java
import java.io.FileReader;
import java.io.IOException;
public class MyClass {
public static void main(String[] args) {
try (FileReader reader = new FileReader(null)) { // Passing null
System.out.println("Reader created.");
} catch (IOException e) {
System.err.println("Caught an IOException: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Runtime error: java.lang.NullPointerException
The `FileReader` constructor, when invoked with a `null` string or `File` object, immediately throws a `NullPointerException` because it cannot resolve a valid file path.
Q3414easy
How many bytes does the `byte` primitive data type occupy in Java?
✅ Correct Answer: A) 1 byte
A `byte` in Java is an 8-bit signed two's complement integer, which equates to 1 byte.
Q3415hardcode output
What does this code print?
java
public class Q3_InterruptSleep {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
try {
Thread.sleep(500);
System.out.println("Slept normally.");
} catch (InterruptedException e) {
System.out.println("Interrupted during sleep.");
Thread.currentThread().interrupt();
}
System.out.println("Thread finished.");
});
t.start();
Thread.sleep(50);
t.interrupt();
Thread.sleep(50);
System.out.println("Main: " + t.getState());
}
}
✅ Correct Answer: B) Interrupted during sleep.
Thread finished.
Main: TERMINATED
The main thread interrupts `t` while it's in `Thread.sleep(500)`. This causes `InterruptedException` to be thrown in `t`, clearing its interrupted status. The `catch` block is executed, then the thread continues to print "Thread finished." and terminates, resulting in `TERMINATED` state for `t`.
Q3416hard
In a multi-threaded Java application, a `while` loop's condition depends on a boolean flag updated by another thread. What is the most robust mechanism to ensure visibility of the flag's updates to the `while` loop and prevent potential indefinite spinning due to memory visibility issues?
✅ Correct Answer: A) Declaring the boolean flag as `volatile`.
`volatile` ensures that changes to the flag are immediately visible across threads by preventing instruction reordering and ensuring reads/writes go to main memory, thus avoiding stale cached values. Without it, the JIT compiler might optimize reads of the flag, leading to an infinite loop.
Q3417easy
Which of the following best describes the nature of `StringBuffer` objects in Java?
✅ Correct Answer: B) They are mutable, meaning their content can be changed after creation.
`StringBuffer` objects are mutable, allowing their character sequences to be modified (appended, inserted, deleted, etc.) without creating new objects.
Q3418mediumcode output
What does this code print?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(10);
list.addFirst(5);
list.addLast(20);
list.removeFirst();
list.add(15);
System.out.println(list);
}
}
✅ Correct Answer: B) [10, 20, 15]
The list starts with [10]. `addFirst(5)` makes it [5, 10]. `addLast(20)` makes it [5, 10, 20]. `removeFirst()` removes 5, leaving [10, 20]. Finally, `add(15)` appends to the end, resulting in [10, 20, 15].
Q3419mediumcode error
What is the outcome when this Java code is executed?
java
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
String element = list.remove();
System.out.println(element);
}
}
✅ Correct Answer: B) NoSuchElementException
The `remove()` method of `LinkedList` (without an index) attempts to remove and return the head of the list. If the list is empty, it throws a `NoSuchElementException`.
Q3420hard
Given the following Java class:
java
class Solver {
void solve(long l, Integer i) { System.out.println("long, Integer"); }
void solve(Integer i, long l) { System.out.println("Integer, long"); }
}
What is the result of compiling and running the following code?
`new Solver().solve(5, 5);`
✅ Correct Answer: C) Compilation Error: Ambiguous method call
Both methods are applicable: `int` can widen to `long` and autobox to `Integer`. Neither method is more specific than the other, as the transformations (widening and autoboxing) are performed on different arguments, leading to an ambiguous call.