Consider a `switch` statement nested within a `for` loop. If an unlabeled `break` statement is executed within a `case` block of this `switch` statement, what is the immediate effect on the execution flow?
✅ Correct Answer: C) Only the `switch` statement is exited, and execution continues with the statement immediately following the `switch` within the current loop iteration.
An unlabeled `break` statement, when used within a `switch` block, only exits the `switch` statement itself. It does not affect any enclosing loops. Execution will resume immediately after the `switch` block, within the current iteration of the `for` loop.
Q222hard
Consider a scenario where a constructor passes the `this` reference to another object before the current object's construction is complete. What is a primary encapsulation risk?
✅ Correct Answer: B) The external object might access the partially constructed object's state, leading to inconsistencies or unexpected behavior.
Passing `this` out of a constructor before the object is fully initialized ('this escaping') breaks encapsulation because another object could access the partially constructed state, leading to data races, inconsistencies, or even `NullPointerExceptions`.
Q223easy
What is the primary reason to use `StringBuilder` in Java?
✅ Correct Answer: B) To efficiently modify string content without creating new objects repeatedly.
`StringBuilder` is designed for efficient modification of string content. It avoids creating multiple intermediate String objects during operations like concatenation.
Q224easycode output
What is the output of this Java code snippet?
java
public class ArrayTest {
public static void main(String[] args) {
boolean[] flags = new boolean[2];
flags[0] = true;
System.out.println(flags[1]);
}
}
✅ Correct Answer: A) false
When an array of `boolean` primitives is declared but not explicitly initialized, its elements are automatically set to their default value, which is `false`. Only `flags[0]` was assigned `true`.
Q225easy
What kind of underlying data structure does `TreeMap` use to maintain its sorted order?
✅ Correct Answer: C) Red-Black Tree
Internally, `TreeMap` uses a Red-Black Tree data structure, which is a self-balancing binary search tree, to efficiently store and retrieve its elements in sorted order.
Q226medium
For custom objects to be correctly stored and uniquely identified within a `HashSet`, which methods must be properly overridden in the custom class?
✅ Correct Answer: C) `hashCode()` and `equals()`
`HashSet` uses the `hashCode()` method to determine the bucket for an object and the `equals()` method to compare objects within that bucket to ensure uniqueness and correct retrieval.
Q227hard
Consider a Java construct using `do { ... } while (false);`. What is the primary and most common idiomatic use case for this specific `do-while` pattern?
✅ Correct Answer: B) To ensure a block of code executes exactly once, often for scope management or handling early exits via `break` within a `switch` context.
This idiom guarantees that the code block within `do` executes exactly once. It's often used to create a block scope where `break` can exit the block (similar to a `switch` statement without falling through) or to contain a sequence of operations where early exit is desired.
Q228medium
The `renameTo()` method of the `File` class can fail for several reasons. Which of the following is NOT a common reason for `renameTo()` to return `false`?
✅ Correct Answer: A) The destination path refers to an existing, empty file.
`renameTo()` is generally designed to overwrite existing files, especially if they are empty. If the destination is an existing, empty file, `renameTo()` will typically succeed by overwriting it, thus it's not a reason for the method to return `false`.
Q229easycode error
What will be the outcome of attempting to compile this Java code?
java
class Constants {
private static String API_KEY = "my_secret_key";
}
public class Config {
public static void main(String[] args) {
System.out.println(Constants.API_KEY);
}
}
✅ Correct Answer: A) Compile-time error: 'API_KEY' has private access in 'Constants'
Even static fields obey access modifiers. Since 'API_KEY' is private, it cannot be accessed directly from outside the 'Constants' class, leading to a compile-time error.
Q230hardcode error
What is the compile-time error when trying to instantiate the Inner class from a static context?
java
class Outer {
class Inner {
Inner() {}
}
static class Nested {
void createInnerInstance() {
// Attempt to instantiate non-static inner class
Inner inner = new Inner();
}
}
}
✅ Correct Answer: A) Error: `non-static variable this cannot be referenced from a static context`
A non-static inner class requires an enclosing instance of its outer class to be created. Instantiating it directly from a static context (like `Nested.createInnerInstance()`) without an `Outer` instance is not allowed, as it implicitly attempts to access `Outer.this`.
Q231hard
Under what specific conditions does a HashMap bucket (linked list) transition into a Red-Black Tree in Java 8 and later?
✅ Correct Answer: A) When a bucket's linked list size reaches 8, AND the total table capacity is at least 64.
Treeification occurs when a bucket's linked list size reaches `TREEIFY_THRESHOLD` (8), but only if the table's capacity is at least `MIN_TREEIFY_CAPACITY` (64). Otherwise, the table is resized.
Q232hardcode output
What is the output of this code?
java
public class Q5_LostNotify {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
synchronized (lock) {
try {
System.out.println("T: Attempting to wait.");
lock.wait();
System.out.println("T: Notified.");
} catch (InterruptedException e) {
System.out.println("T: Interrupted.");
}
}
System.out.println("T: Finished its synchronized block.");
});
synchronized (lock) {
System.out.println("Main: Notifying lock (no one waiting yet).");
lock.notify(); // This notify is lost
System.out.println("Main: Notify finished.");
}
t.start();
Thread.sleep(200); // Give t time to enter WAITING
System.out.println("Main: T state after some time: " + t.getState());
// The program will hang unless interrupted or notified again.
t.interrupt(); // To ensure termination for output
Thread.sleep(50);
System.out.println("Main: T state after interrupt: " + t.getState());
}
}
✅ Correct Answer: A) Main: Notifying lock (no one waiting yet).
Main: Notify finished.
T: Attempting to wait.
Main: T state after some time: WAITING
T: Interrupted.
T: Finished its synchronized block.
Main: T state after interrupt: TERMINATED
The `lock.notify()` call happens before thread `t` enters the `WAITING` state, so the notification is lost. `t` then calls `lock.wait()` and gets stuck in the `WAITING` state. To ensure the program terminates for the output, `t` is later interrupted, causing it to print `T: Interrupted.` and then `T: Finished...`, finally becoming `TERMINATED`.
Q233mediumcode output
What is the output of this Java code snippet?
java
public class StringBufferTest {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Programming");
sb.delete(3, 7);
sb.deleteCharAt(2);
System.out.print(sb);
}
}
✅ Correct Answer: A) Prgming
Initially, `sb` is 'Programming'. `sb.delete(3, 7)` removes characters from index 3 (inclusive) to 7 (exclusive), deleting 'gram'. The buffer becomes 'Pr oming'. Then `sb.deleteCharAt(2)` removes the character at index 2, which is 'o'. The final string is 'Prgming'.
Q234hardcode error
What exception is thrown when the `ois.readObject()` line is executed during deserialization?
java
import java.io.*;
class NullPointerInReadObject implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private transient String transientField; // Marked transient, so not serialized by default
public NullPointerInReadObject(String name) {
this.name = name;
this.transientField = "Initialized";
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject(); // Reads 'name'. 'transientField' is not automatically read.
// Attempting to use transientField, which is null after defaultReadObject,
// as it was not part of the default serialization and no custom logic initialized it.
System.out.println("Transient field length: " + transientField.length()); // Error occurs here
}
public String getName() { return name; }
public String getTransientField() { return transientField; }
}
public class SerializationError10 {
public static void main(String[] args) throws Exception {
NullPointerInReadObject obj = new NullPointerInReadObject("Test Object");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
byte[] serializedData = bos.toByteArray();
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(serializedData);
ObjectInputStream ois = new ObjectInputStream(bis);
NullPointerInReadObject deserialized = (NullPointerInReadObject) ois.readObject(); // Error occurs during readObject
ois.close();
System.out.println("Deserialized: " + deserialized.getName());
}
}
✅ Correct Answer: A) java.lang.NullPointerException
Fields marked `transient` are not serialized by the default serialization mechanism. When `readObject` is called, `ois.defaultReadObject()` initializes non-transient fields but leaves `transientField` as `null`. Subsequently, attempting to call `length()` on `transientField` results in a `NullPointerException`.
Q235easycode error
What happens when you try to compile and run this Java code?
java
public class FinalArrayReassignment {
public static void main(String[] args) {
final int[] numbers = {1, 2, 3};
numbers[0] = 10;
numbers = new int[]{4, 5, 6};
System.out.println(numbers[0]);
}
}
✅ Correct Answer: A) Compile-time error: "The final local variable numbers cannot be assigned."
While the contents of the array referred to by `numbers` can be modified (arrays are mutable), the `final` keyword prevents the `numbers` reference itself from being reassigned to a new array object.
Q236hardcode error
Does this Java code compile? If not, what is the compile-time error?
java
import java.io.IOException;
class Parent {
public void perform() throws IOException {}
}
class Child extends Parent {
@Override
public void perform() throws Exception {}
}
public class Main {
public static void main(String[] args) {}
}
✅ Correct Answer: D) Error: 'perform()' in 'Child' cannot override 'perform()' in 'Parent'; attempting to throw a broader checked exception.
When overriding a method, the subclass's method cannot declare checked exceptions that are broader than those declared by the superclass method. `Exception` is a broader checked exception than `IOException`.
Q237mediumcode output
What is the output of this Java code snippet?
java
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
if (it.next() == 20) {
it.remove();
}
}
System.out.println(numbers);
}
}
✅ Correct Answer: A) [10, 30]
Using the `Iterator`'s `remove()` method is the safe way to modify a collection during iteration. When `it.next()` returns 20, `it.remove()` successfully removes it from the list.
Q238easycode error
What is the error in this Java code?
java
public class FileWriterError3 {
public static void main(String[] args) {
// Missing import statement for FileWriter
java.io.FileWriter writer = null;
try {
writer = new java.io.FileWriter("log.txt");
writer.write("Log message.");
} catch (java.io.IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
}
}
✅ Correct Answer: A) Missing `import java.io.FileWriter;` statement.
Without `import java.io.FileWriter;` or using the fully qualified name `java.io.FileWriter` (which is present in the provided snippet but the question implies the import is missing), the compiler would not be able to find the `FileWriter` class. The question is designed to highlight the import requirement.
Q239medium
Which statement accurately describes a Java functional interface?
✅ Correct Answer: A) An interface with exactly one abstract method.
A functional interface is defined as an interface that has exactly one abstract method. This is often referred to as a Single Abstract Method (SAM) interface.
Q240hardcode error
What compile-time error occurs when attempting to compile this Java code?
java
abstract class Vehicle {
public abstract void start();
}
class Car extends Vehicle {
@Override
protected void start() {
System.out.println("Car starting...");
}
}
✅ Correct Answer: B) Error: cannot reduce the visibility of the inherited method from Vehicle
When overriding a method, the access modifier of the overriding method cannot be more restrictive (weaker) than the overridden method. `public` is stronger than `protected`, so reducing visibility results in a compile-time error.