What compilation error will occur in the following Java code?
java
abstract class Widget {
abstract void display();
public static void createWidget() {
Widget w = new Widget();
}
}
✅ Correct Answer: B) Error: Cannot instantiate the type Widget
Even within an abstract class itself, you cannot directly instantiate it. The 'new Widget()' call attempts to create an instance of the abstract class, which is forbidden.
Q1202easycode error
What error will this Java code produce during compilation?
java
public class ArrayError {
public static void main(String[] args) {
int[][] matrix = new int[2][2];
int[] singleDimArray = {1, 2};
matrix = singleDimArray;
}
}
✅ Correct Answer: A) Compilation Error: incompatible types: int[] cannot be converted to int[][]
A two-dimensional array (`int[][]`) cannot be assigned directly to a one-dimensional array (`int[]`) variable, or vice-versa. This is a type mismatch detected by the compiler.
Q1203mediumcode output
What does this code print?
java
import java.util.HashSet;
import java.util.Set;
class Product {
int id;
String name;
Product(int id, String name) { this.id = id; this.name = name; }
@Override public int hashCode() { return id; }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return id == product.id;
}
}
public class Main {
public static void main(String[] args) {
Set<Product> products = new HashSet<>();
products.add(new Product(101, "Laptop"));
products.add(new Product(101, "Monitor"));
System.out.println(products.size());
}
}
✅ Correct Answer: A) 1
The `equals()` and `hashCode()` methods are overridden to consider `Product` objects equal if their `id` fields are the same. Since both added products have `id = 101`, the second `add()` operation is treated as a duplicate and ignored. Therefore, the set contains only one element.
Q1204medium
Why is it considered best practice to always close a `FileReader` instance after you are finished reading from it?
✅ Correct Answer: B) To release system resources (like file handles) associated with the file.
Closing a `FileReader` releases the underlying operating system file handle and other associated resources. Failure to close can lead to resource leaks, preventing other processes from accessing the file, or exceeding system limits.
Q1205easy
What is the key difference between a `while` loop and a `do-while` loop?
✅ Correct Answer: B) A `do-while` loop always executes at least once, while a `while` loop may not.
The `do-while` loop executes its body at least once before checking the condition, whereas a `while` loop checks the condition first and might not execute its body at all.
Q1206hard
What is the correct way to declare variables with the same name in different `case` blocks of a single `switch` *statement* without causing a compile-time error?
✅ Correct Answer: B) Enclose each `case` block in its own curly braces `{}` to create a new scope.
All `case` labels within a `switch` statement share the same lexical scope. To declare variables with identical names in different `case` blocks, each `case` block must be enclosed in its own curly braces `{}`, creating a new local scope for those variables.
Q1207hard
Consider a thread that calls `Object.wait()` without holding the monitor for that object. What is the immediate consequence?
✅ Correct Answer: C) An `IllegalMonitorStateException` is thrown immediately by the JVM.
Methods like `wait()`, `notify()`, and `notifyAll()` must be called from within a synchronized block or method that holds the monitor of the object. Failing to do so results in an `IllegalMonitorStateException`.
Q1208mediumcode error
What error occurs when running this code, assuming 'test_input.txt' exists?
✅ Correct Answer: A) The program prints 'Caught NullPointerException: null' and exits.
The `read(char[] cbuf, int off, int len)` method expects a non-null character array as its first argument. Passing `null` will result in a `NullPointerException` during runtime.
Q1209hard
Given `String[] sArr = new String[1];`. Which of the following `instanceof` expressions correctly describes `sArr`'s runtime type or implemented interfaces?
✅ Correct Answer: C) `sArr instanceof Cloneable`
All Java arrays (regardless of component type) directly implement the `Cloneable` and `Serializable` interfaces. `sArr instanceof String` is false (it's an array, not a String). `sArr instanceof Object[]` is true but `sArr instanceof Cloneable` is more specific and less obvious. `sArr instanceof java.io.Serializable[]` is false because the component type is `String`, not `Serializable[]`.
Q1210mediumcode output
What is the output of this Java Stream API code?
java
import java.util.stream.IntStream;
public class StreamTest {
public static void main(String[] args) {
int sum = IntStream.rangeClosed(1, 5)
.filter(n -> n % 2 == 0)
.map(n -> n * 2)
.sum();
System.out.println(sum);
}
}
✅ Correct Answer: A) 12
IntStream.rangeClosed(1, 5) generates [1, 2, 3, 4, 5]. Filtering for even numbers leaves [2, 4]. Mapping `n * 2` transforms it to [4, 8]. The sum of these is 12.
Q1211hard
What is the worst-case time complexity for `put()` and `get()` operations in a `HashMap` if all keys consistently produce the same `hashCode()` and the table capacity is below the `MIN_TREEIFY_CAPACITY` threshold (64)?
✅ Correct Answer: B) O(N) because all entries will be stored in a single linked list, requiring traversal of N elements.
If all keys hash to the same bucket and the capacity is too small for treeification to occur, all entries will form a single linked list. Operations like `put()` and `get()` would then require traversing this entire list, leading to O(N) time complexity.
Q1212easycode error
What compile-time error will occur in the `Child` class?
java
class Parent {
public void printValue() {
System.out.println("Parent value");
}
}
class Child extends Parent {
@Override
public int printValue() {
System.out.println("Child value");
return 1;
}
}
✅ Correct Answer: A) Error: `printValue()` in `Child` cannot override `printValue()` in `Parent`; return type `int` is not compatible with `void`
When overriding a method, the return type in the subclass must be the same as or a covariant return type of the method in the superclass. `int` is not compatible with `void`.
Q1213hard
Given two single-dimensional arrays, `int[] arr1 = {1, 2, 3};` and `int[] arr2 = {1, 2, 3};`. Which statement correctly describes the outcome of their comparison methods?
✅ Correct Answer: B) `arr1.equals(arr2)` is `false` and `Arrays.equals(arr1, arr2)` is `true`.
The `equals()` method inherited from `Object` (and not overridden by arrays) checks for reference equality, so `arr1.equals(arr2)` is `false`. `Arrays.equals()` performs an element-by-element comparison, so it returns `true` for arrays with identical contents.
Q1214mediumcode output
What does this code print?
java
import jakarta.validation.*;
import jakarta.validation.constraints.Min;
import java.util.Set;
public class Test {
static class Item { @Min(1) public int value; public Item(int v) { this.value = v; } }
static class Container {
@Valid public Item[] items; // @Valid on an array
public Container(Item[] i) { this.items = i; }
}
public static void main(String[] args) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Container c = new Container(new Item[]{new Item(5), new Item(0)}); // Second item invalid
Set<ConstraintViolation<Container>> violations = validator.validate(c);
System.out.println("Violations: " + violations.size());
}
}
✅ Correct Answer: A) Violations: 1
The `@Valid` annotation on the `Item[] items` array triggers validation for each element. The first item is valid, but the second item with `value=0` violates the `@Min(1)` constraint, resulting in one violation.
Q1215hardcode error
What is the compilation error in this Java code?
java
class Test {
public static void main(String[] args) {
int x = 0;
do {
System.out.println("Executing...");
return;
} while (x < 1);
int y = 10;
System.out.println(y);
}
}
✅ Correct Answer: A) Unreachable statement
The `return` statement inside the `do` block unconditionally exits the `main` method in its first iteration, making the subsequent declaration and usage of `y` an unreachable statement, which is a compile-time error.
Q1216easycode error
What error will occur when compiling the following Java code?
java
import java.util.HashSet;
import java.util.Set;
public class MyClass {
public static void main(String[] args) {
Set<String> items; // Not initialized
items.add("Laptop"); // This line will cause an error
System.out.println(items.size());
}
}
✅ Correct Answer: B) variable items might not have been initialized
The local variable `items` is declared but not initialized with a `HashSet` instance. Attempting to call a method on an uninitialized variable results in a compile-time error.
Q1217easy
What happens when you use the `reverse()` method on a `StringBuffer` object?
✅ Correct Answer: B) It modifies the `StringBuffer` in place, reversing the order of its characters.
The `reverse()` method modifies the `StringBuffer` object itself, changing the order of its characters to their reverse sequence.
Q1218easycode output
What is the result of compiling and running this Java code?
java
public class OverloadDemo7 {
int getValue(int x) {
return x * 2;
}
double getValue(int x) { // This line causes a compile-time error
return (double)x / 2;
}
public static void main(String[] args) {
OverloadDemo7 obj = new OverloadDemo7();
System.out.println(obj.getValue(7));
}
}
✅ Correct Answer: A) Compile-time error: Method 'getValue(int)' is already defined...
Method overloading relies on distinct parameter lists. The return type alone is not sufficient to differentiate overloaded methods. This code will cause a compile-time error because two methods have the same name and parameter type (`int`).
Q1219mediumcode error
What is the error in this Java code snippet?
java
public class MyClass {
public static void main(String[] args) {
StringBuilder sb;
sb.append("Hello");
System.out.println(sb);
}
}
✅ Correct Answer: B) A compile-time error: variable sb might not have been initialized.
The local variable 'sb' is declared but not initialized. Attempting to call a method on an uninitialized local variable results in a compile-time error.
Q1220hardcode error
What is the output of this code?
java
public class Main {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.println("Worker thread running."));
t.start();
try {
t.join(-100); // Negative timeout
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
}
}
✅ Correct Answer: A) Exception in thread "main" java.lang.IllegalArgumentException: timeout value is negative
The `Thread.join(long millis)` method expects a non-negative timeout value. Passing a negative value will cause an `IllegalArgumentException`.