Which of the following statements about the `throw` keyword is true?
✅ Correct Answer: C) It must be followed by an instance of `Throwable`.
The `throw` keyword is always followed by an object that is an instance of `Throwable` (e.g., `new IOException()`). It is used to throw an actual exception object.
Q2302easy
What is a key advantage of using the `Runnable` interface over extending the `Thread` class for creating threads?
✅ Correct Answer: C) It allows a class to extend another class while still defining a thread's execution logic.
Since Java does not support multiple inheritance of classes, implementing `Runnable` allows a class to inherit from another class while still providing a thread's execution behavior.
Q2303medium
What is the default initial value for elements in an array of `String` objects when it is first created, e.g., `String[] names = new String[5];`?
✅ Correct Answer: C) The value `null`
When an array of reference types (like `String` or any object) is created, all its elements are automatically initialized to `null` by default.
Q2304hard
In a `try-with-resources` statement, if an exception occurs within the `try` block, and another exception occurs during the implicit closing of a resource, how are these exceptions typically handled?
✅ Correct Answer: C) The exception from the `try` block is propagated, and the exception from resource closing is added to it as a 'suppressed' exception.
With `try-with-resources`, the primary exception (from the `try` block) is propagated, and any exceptions thrown during resource closing are added to it as suppressed exceptions, accessible via `Throwable.getSuppressed()`.
Q2305hard
Given the limitation of creating generic arrays directly, what is the primary role of `java.lang.reflect.Array.newInstance(Class<?> componentType, int length)`?
✅ Correct Answer: B) It provides a way to create arrays dynamically at runtime when the exact component type is not known until runtime.
`Array.newInstance()` is a reflective method that allows arrays to be created dynamically at runtime by providing a `Class` object for the component type, bypassing the compile-time restriction on generic array instantiation.
Q2306hardcode error
What is the runtime error when executing this Java code snippet?
java
import java.util.TreeSet;
import java.util.Comparator;
class CustomKey {
int id;
String name;
CustomKey(int id, String name) { this.id = id; this.name = name; }
}
public class Main {
public static void main(String[] args) {
TreeSet rawSet = new TreeSet(); // Using raw type
rawSet.add(new CustomKey(1, "One"));
rawSet.add("Two"); // Adding a String, which will be ignored by the error
rawSet.add(new CustomKey(3, "Three"));
System.out.println(rawSet.size());
}
}
✅ Correct Answer: C) java.lang.ClassCastException: class CustomKey cannot be cast to class java.lang.Comparable
Since a raw TreeSet is used and no Comparator is provided, it relies on natural ordering. CustomKey does not implement Comparable, so when TreeSet attempts to compare the elements, it throws a ClassCastException because CustomKey cannot be cast to Comparable.
Q2307hard
Consider `int[] original = {10, 20, 30};`. What happens when `Arrays.copyOfRange(original, 1, 5)` is executed?
✅ Correct Answer: B) A new array `{20, 30, 0, 0}` is returned, where `0`s are the default values for `int`.
The `Arrays.copyOfRange()` method handles cases where the 'to' index extends beyond the original array's length by creating a new array of the specified size and filling the extra elements with the default value for the array's component type (0 for `int`). It does not throw an `ArrayIndexOutOfBoundsException` in this scenario.
Q2308easycode output
What is the output of this code?
java
abstract class Shape {
abstract void draw();
}
public class Test {
public static void main(String[] args) {
Shape s = new Shape(); // This line will cause a compile-time error
System.out.println("Program continues.");
}
}
✅ Correct Answer: C) Compile-time error
Abstract classes cannot be instantiated directly. An attempt to create an object of an abstract class will result in a compile-time error.
Q2309medium
Consider the `createNewFile()` method of the `File` class. If the file specified by the `File` object already exists, what is the behavior of this method?
✅ Correct Answer: C) It does nothing to the existing file and returns `false`.
`createNewFile()` atomically creates a new, empty file only if it does not already exist. If the file already exists, the method returns `false` and does not modify the existing file.
Q2310hardcode output
What is the output of this code?
java
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing Circle");
}
}
class Square extends Shape {
// No draw() method implemented
}
public class Main {
public static void main(String[] args) {
// Shape s = new Circle(); // This would work
// s.draw();
Shape s2 = new Square(); // This line
}
}
✅ Correct Answer: C) Compile-time error
A concrete class that extends an abstract class must implement all inherited abstract methods. `Square` fails to implement the abstract `draw()` method from `Shape`, which causes a compile-time error because `Square` would also need to be declared abstract.
Q2311medium
Can `java.util.LinkedList` store `null` elements?
✅ Correct Answer: B) Yes, it can store `null` elements.
Like most general-purpose collections in Java (except for those with specific constraints like `ConcurrentHashMap` or `TreeSet` without a null-safe comparator), `java.util.LinkedList` permits `null` elements.
Q2312mediumcode error
What compilation error will this Java code produce? (Assume Java 8 environment)
java
public class SwitchError {
public static void main(String[] args) {
String data = null;
switch (data) {
case "test":
System.out.println("Test");
break;
case null:
System.out.println("Null data");
break;
default:
System.out.println("Other");
}
}
}
✅ Correct Answer: B) Error: case label cannot be 'null' in this language level
Prior to Java 17, `case null` was not a valid construct in a switch statement, leading to a compilation error. Handling null values directly in a switch statement was not supported.
Q2313mediumcode error
What error does this Java code produce when executed?
java
public class Main {
public static void main(String[] args) {
String s1 = null;
String s2 = "test";
System.out.println(s1.equals(s2));
}
}
✅ Correct Answer: A) java.lang.NullPointerException
When comparing two strings using 'equals()', if the calling object (s1 in this case) is null, a NullPointerException occurs. To safely compare, ensure the calling object is not null, or call 's2.equals(s1)'.
Q2314hardcode error
What compile-time error will occur in this Java record definition with a compact constructor?
java
record Product(String name, double price) {
Product {
// Compact constructor implicitly assigns name and price.
// Explicit assignment here is redundant and causes an error.
this.name = name.trim();
if (price < 0) {
throw new IllegalArgumentException("Price cannot be negative");
}
}
}
✅ Correct Answer: A) Error: `cannot assign a value to final variable name`
In a Java record's compact constructor, the record components (e.g., `name`, `price`) are implicitly assigned after the constructor body executes. Attempting to explicitly assign values to these `final` components (like `this.name = name.trim();`) within the compact constructor body is redundant and results in a compile-time error because they are treated as final variables that are already scheduled for initialization.
Q2315medium
Is it possible to overload constructors in Java?
✅ Correct Answer: C) Yes, just like regular methods, by having different parameter lists.
Constructors can be overloaded in Java, allowing a class to have multiple constructors with the same name (the class name) but different parameter lists, similar to how methods are overloaded.
Q2316mediumcode output
What does this code print?
java
interface MyFunction {
void apply();
}
public class LambdaVariableCapture {
public static void main(String[] args) {
int x = 10;
MyFunction func = () -> System.out.println(x * 2);
// x = 20; // Uncommenting this line would cause a compile error
func.apply();
}
}
✅ Correct Answer: A) 20
Lambda expressions can capture effectively final local variables. The variable 'x' is effectively final (its value doesn't change after initialization), so it can be used within the lambda. The lambda prints `10 * 2`, which is 20.
Q2317hardcode output
What does this code print?
java
import java.util.LinkedList;
public class Test {
static class MyObject {
int id;
MyObject(int id) { this.id = id; }
}
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
list.add(null);
list.add(new MyObject(1));
list.add(new MyObject(2));
System.out.print(list.contains(null) + " ");
System.out.print(list.contains(new MyObject(1)) + " ");
System.out.print(list.contains(new MyObject(3)));
}
}
✅ Correct Answer: B) true false false
LinkedList's `contains()` method handles `null` correctly. For objects, it uses `equals()`. Since `MyObject` does not override `equals()`, `new MyObject(1)` is a different object instance than the one added to the list, so `contains()` returns `false`.
Q2318mediumcode error
What will be the compilation error in this code?
java
class Super {
public void display() {
System.out.println("Super display");
}
}
class Sub extends Super {
@Override
protected void display() {
System.out.println("Sub display");
}
}
✅ Correct Answer: A) Error: display() in Sub cannot override display() in Super; attempting to assign weaker access privileges; was public
When overriding a method, the access modifier in the subclass cannot be more restrictive than in the superclass. Changing from 'public' to 'protected' is a reduction in visibility, which is not allowed.
Q2319easy
Which of the following statements about `case` labels in a Java `switch` statement is true?
✅ Correct Answer: B) They must be unique constant values.
Each `case` label in a Java `switch` statement must be a unique, compile-time constant value. Duplicate `case` labels or runtime expressions are not allowed.
Q2320easycode error
What is the compilation or runtime error in the following Java code?
java
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
greeting[0] = 'J';
System.out.println(greeting);
}
}
✅ Correct Answer: C) Compilation error: array required, but String found
Strings in Java are immutable and cannot be modified using array-like indexing (`[0]`). This syntax is invalid for `String` objects and results in a compilation error.