When resizing a `HashMap`, how are existing entries redistributed to new buckets in the larger internal array?
✅ Correct Answer: C) Entries are either kept in their current bucket (newIndex = oldIndex) or moved to a new bucket (newIndex = oldIndex + oldCapacity), determined by an additional bit in their hash.
During resizing, Java 8+ HashMap efficiently redistributes entries. For each entry, it checks a specific bit in its hash code (corresponding to the old capacity). If this bit is 0, the entry stays in its current bucket index; if it's 1, it moves to `oldIndex + oldCapacity`.
Q282easy
Which of the following is a primitive data type in Java?
✅ Correct Answer: C) int
`int` is one of Java's eight primitive data types. `String`, `Array`, and `Object` are reference types.
Q283mediumcode error
What compilation error will occur when compiling the `TestClass`?
java
public class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
public class TestClass {
public static void processData(int value) {
if (value < 0) {
throw new MyCustomException("Value cannot be negative.");
}
System.out.println("Processing: " + value);
}
public static void main(String[] args) {
processData(-5);
}
}
✅ Correct Answer: A) Unhandled exception: MyCustomException
`MyCustomException` extends `Exception`, making it a checked exception. The `processData` method throws `MyCustomException` but does not declare `throws MyCustomException` in its signature, leading to a compile-time error.
Q284medium
What is the key characteristic that distinguishes a mutable object from an immutable object in Java?
✅ Correct Answer: B) A mutable object's internal state can be changed after it has been created, unlike an immutable object.
The fundamental difference is that a mutable object's state can be altered after construction, whereas an immutable object's state remains fixed throughout its lifetime.
Q285easy
In which Java package is the `ArrayList` class located?
✅ Correct Answer: C) `java.util`
The `ArrayList` class is part of the Java Collections Framework and is found in the `java.util` package, which contains utility classes for data structures and algorithms.
Q286easy
Which of the following statements about the `finally` block is true?
✅ Correct Answer: C) It executes after the `try` block and any matching `catch` blocks, regardless of whether an exception occurred (unless the JVM exits).
The `finally` block is designed to execute its code after the `try` block completes, or after any `catch` block that handles an exception, ensuring execution in most scenarios.
Q287hard
In a Java class, which of the following statements accurately describes the order of variable initialization when an instance of the class is created?
✅ Correct Answer: B) Static variables and static blocks are initialized once when the class is loaded, followed by instance variables and instance blocks (in declaration order) before the constructor for each new object.
Static members are initialized when the class is loaded. For each object creation, instance variable initializers and instance blocks run in order before the constructor executes.
Q288easy
If no exception occurs within a `try` block, which blocks will execute?
✅ Correct Answer: C) The `try` block and then the `finally` block.
If no exception is thrown in the `try` block, the `catch` block is skipped, and execution proceeds directly to the `finally` block.
Q289mediumcode error
What error occurs when compiling this Java code?
java
import java.io.IOException;
public class BroadExceptionCatch {
public static void riskyOperation() throws Exception {
System.out.println("Executing risky operation...");
throw new Exception("Something went wrong!");
}
public static void main(String[] args) {
try {
riskyOperation();
} catch (IOException e) { // Catching a specific exception
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Compilation error: Unhandled exception type java.lang.Exception
The `riskyOperation` method declares `throws Exception`. The `main` method attempts to catch only `IOException`, which is more specific than `Exception`. Since `IOException` does not cover all possible `Exception` types, the broader `Exception` remains unhandled, leading to a compilation error.
Q290easycode output
What is the output of this code?
java
class StaticCounter {
private static int count = 0;
public static synchronized void increment() {
count++;
System.out.print(count);
}
}
public class MyProgram {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> StaticCounter.increment());
Thread t2 = new Thread(() -> StaticCounter.increment());
t1.start();
t2.start();
t1.join();
t2.join();
}
}
✅ Correct Answer: C) Either '12' or '21'
A `static synchronized` method locks on the class's intrinsic lock (`StaticCounter.class`). This ensures only one thread can execute `increment` at a time, even if there are multiple instances or none. The output order '12' or '21' depends on scheduling, but the increments are atomic.
Q291mediumcode output
What is the output of this Java code?
java
public class TryCatchExample {
public static void main(String[] args) {
try {
System.out.println("Inside try block");
int result = 10 / 0;
System.out.println("This won't be printed");
} catch (ArithmeticException e) {
System.out.println("Inside catch block: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Inside try block
Inside catch block: / by zero
The code enters the try block, prints the first line, then encounters an `ArithmeticException` (division by zero). The exception is caught by the `catch` block, which then prints its message. The line after the exception in the `try` block is not executed.
Q292medium
What is the fundamental difference in the return type between the `list()` method and the `listFiles()` method of the `File` class when used on a directory?
✅ Correct Answer: A) `list()` returns `String[]` (names), while `listFiles()` returns `File[]` (abstract pathnames).
`list()` returns an array of strings representing the names of files and directories. `listFiles()` returns an array of `File` objects, providing full abstract pathnames that can be further queried.
Q293easycode error
Identify the exception that will be thrown by the following Java code.
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class IteratorError {
public static void main(String[] args) {
ArrayList<String> items = new ArrayList<>(Arrays.asList("First", "Second", "Third"));
Iterator<String> it = items.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.equals("Second")) {
items.remove(item); // Directly removing from the original list
}
}
}
}
✅ Correct Answer: A) java.util.ConcurrentModificationException
Directly modifying the collection (`items.remove(item)`) while iterating over it using a standard `Iterator` (obtained via `iterator()`) will lead to a `ConcurrentModificationException`.
Q294hardcode error
What is the compile-time error in this Java code snippet?
java
public class DuplicateCaseLabelError {
public static void main(String[] args) {
final int STATUS_ACTIVE = 1;
final int STATUS_OPEN = 1;
int status = 1;
String message = "";
switch (status) { // Error expected here
case STATUS_ACTIVE:
message = "Active";
break;
case STATUS_OPEN:
message = "Open";
break;
default:
message = "Unknown";
}
System.out.println(message);
}
}
✅ Correct Answer: A) Compile-time error: 'duplicate case label'
All `case` labels within a `switch` statement must be unique constant expressions. Since `STATUS_ACTIVE` and `STATUS_OPEN` both resolve to the same compile-time constant value `1`, having both as `case` labels results in a 'duplicate case label' compile-time error.
Q295easycode output
What is the output of the following Java code?
java
public class Task {
private String description;
public void setDescription(String description) {
this.description = description.trim(); // Trim whitespace
}
public String getDescription() {
return description;
}
public static void main(String[] args) {
Task task = new Task();
task.setDescription(" Buy Groceries ");
System.out.println("[" + task.getDescription() + "]");
}
}
✅ Correct Answer: A) [Buy Groceries]
The 'setDescription' method uses 'trim()' to remove leading and trailing whitespace from the input string. Therefore, 'getDescription()' returns the string without the extra spaces, enclosed in brackets for printing.
Q296easycode error
What compilation error will occur when compiling this Java code?
java
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class MyClass {
public static void main(String[] args) {
BufferedReader br;
try (br = new BufferedReader(new StringReader("test"))) {
String line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: A) resource not allowed in a try-with-resources statement
In a `try-with-resources` statement, the resource variable must be declared *within* the parentheses. It cannot be an already declared variable that is merely assigned inside.
Q297medium
If an exception occurs within the `try` block and is successfully caught by a matching `catch` block, what is the execution order?
✅ Correct Answer: A) The `try` block executes partially, then the `catch` block executes, then the `finally` block executes.
Upon an exception in the `try` block, execution immediately transfers to the `catch` block. After the `catch` block completes, the `finally` block is executed.
Q298hardcode error
What compile-time error occurs when attempting to compile this Java code?
java
class SuperClass {
public static void greet() {
System.out.println("Hello from SuperClass!");
}
}
class SubClass extends SuperClass {
@Override
public static void greet() {
System.out.println("Hello from SubClass!");
}
}
✅ Correct Answer: A) Error: method does not override or implement a method from a supertype
Static methods cannot be overridden; they are hidden. The `@Override` annotation is specifically for instance method overriding and will cause a compile-time error if used on a hidden static method, as the compiler expects an actual override.
Q299mediumcode error
What is the reason for the compilation failure in the following Java code?
java
public class Test {
public static void main(String[] args) {
myOuterLabel:;
for (int i = 0; i < 3; i++) {
if (i == 1) {
continue myOuterLabel;
}
System.out.print(i);
}
}
}
✅ Correct Answer: A) Compile-time error: label 'myOuterLabel' does not enclose the loop for 'continue'.
The label `myOuterLabel` is associated with an empty statement (`;`). The `continue myOuterLabel` attempts to affect the `for` loop, but the label does not directly precede and enclose the loop. `continue` can only target a label associated with an enclosing loop, causing a compile-time error.
Q300easy
How are multi-dimensional arrays in Java fundamentally structured?
✅ Correct Answer: B) As an array of arrays.
In Java, a multi-dimensional array (like a 2D array) is an array whose elements are themselves arrays. It is an array of 1D arrays.