What is the error in the execution of this Java code snippet?
java
public class BuilderError {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Data");
sb.delete(-1, 2);
System.out.println(sb);
}
}
✅ Correct Answer: A) IndexOutOfBoundsException
The `delete` method, like many index-based `StringBuilder` methods, expects non-negative start and end indices. Passing a negative `start` index, such as -1, results in an `IndexOutOfBoundsException` at runtime.
Q122easycode output
What is the output of this Java code?
java
public class WhileLoopDemo {
public static void main(String[] args) {
int count = 0;
while (count < 2) {
System.out.print("Hello ");
count++;
}
}
}
✅ Correct Answer: A) Hello Hello
The loop runs twice: once when `count` is 0 and once when `count` is 1. In each iteration, 'Hello ' is printed. When `count` becomes 2, the condition `count < 2` is false, and the loop terminates.
Q123easy
What is the root class of all classes in Java?
✅ Correct Answer: D) Object
Every class in Java implicitly or explicitly inherits from the `java.lang.Object` class, making it the root of the class hierarchy.
Q124hardcode output
What is the output of this Java code involving an inner class and field shadowing?
java
class Outer {
private String message = "Hello from Outer";
String shadowVar = "Outer Shadow";
class Inner {
String shadowVar = "Inner Shadow";
public void printMessages() {
System.out.println("Inner's: " + this.shadowVar);
System.out.println("Outer's msg: " + Outer.this.message);
System.out.println("Outer's var: " + Outer.this.shadowVar);
}
}
}
public class Main {
public static void main(String[] args) {
new Outer().new Inner().printMessages();
}
}
✅ Correct Answer: A) Inner's: Inner Shadow
Outer's msg: Hello from Outer
Outer's var: Outer Shadow
An inner class has a special relationship with its outer class, allowing direct access to its private members. When a field is shadowed (e.g., `shadowVar`), `this.fieldName` refers to the inner class's field, while `Outer.this.fieldName` explicitly refers to the outer class's field.
Q125easy
What happens if you try to put a new value into a HashMap using an existing key?
✅ Correct Answer: C) The old value associated with the key is overwritten by the new value.
If a key already exists in the HashMap, calling `put()` with the same key will replace the old value with the new one.
Q126hard
Which statement about the `instanceof` operator in relation to type casting is most accurate?
✅ Correct Answer: B) `instanceof` checks if an object is an instance of a specific class *or an interface it implements*, allowing a safe explicit cast if it returns `true` (and the object is not `null`).
The `instanceof` operator checks if an object is an instance of a given class or an interface it implements. If it returns `true` for a non-null object, a subsequent explicit cast to that type (or a supertype of the object's actual class) is guaranteed to succeed at runtime, preventing a `ClassCastException`. It returns `false` for `null` and cannot be used with primitives.
Q127mediumcode error
What error will occur when compiling this Java code?
java
public class ConditionCheck {
public static void main(String[] args) {
int score = 75;
System.out.println("Processing score");
else {
System.out.println("No score processed yet.");
}
}
}
✅ Correct Answer: A) error: 'else' without 'if'
An `else` statement must always follow an `if` statement. Here, the `else` block is used without a preceding `if`, which is a syntax error.
Q128easy
Which characteristic best describes the type of elements a Java single-dimensional array can store?
✅ Correct Answer: A) Homogeneous (all of the same type)
Java arrays are homogeneous, meaning all elements in a single array must be of the same data type or a compatible subtype.
Q129hardcode output
What does this code print?
java
public class JaggedArrayNulls {
public static void main(String[] args) {
int[][] matrix = new int[3][];
matrix[0] = new int[]{1, 2};
matrix[2] = new int[]{3, 4, 5};
try {
System.out.println(matrix[1][0]);
} catch (NullPointerException e) {
System.out.println("NPE caught!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("AIOOBE caught!");
}
}
}
✅ Correct Answer: A) NPE caught!
When a jagged array is initialized with `new int[3][]`, only the outer array is created, and its elements (which are references to inner arrays) are initialized to `null`. `matrix[1]` remains `null`, so attempting to access `matrix[1][0]` results in a `NullPointerException`.
Q130hardcode error
What is the compilation error, if any, for the provided Java code snippet?
java
import java.io.Serializable;
class Overloader {
public void store(Object o) {}
public void store(Serializable s) {}
public static void main(String[] args) {
Overloader o = new Overloader();
o.store(null); // Line X
}
}
✅ Correct Answer: B) error: reference to store is ambiguous
`null` can be assigned to both `Object` and `Serializable`. While `Object` is the superclass of all classes, `Serializable` is an interface. Neither method signature is more specific than the other when `null` is passed, leading to an ambiguous method call.
Q131easy
For method overloading, what must differ between methods with the same name?
✅ Correct Answer: C) Their parameter list (number, type, or order of parameters)
Method overloading requires methods to have the same name but different parameter lists. A change in return type or access modifier alone is not sufficient for overloading.
Q132mediumcode error
What error will occur when running the following Java code?
java
public class DoubleStartThread {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("Thread running");
});
t.start();
t.start(); // Attempt to start the thread again
}
}
✅ Correct Answer: A) java.lang.IllegalThreadStateException
Once a thread has been started, it cannot be started again. Calling `start()` on an already started thread will result in an `IllegalThreadStateException` at runtime.
Q133hard
If a superclass declares a `static` method and a subclass declares its own `static` method with the exact same signature, what is the relationship between these two methods in Java?
✅ Correct Answer: B) The subclass method hides (shadows) the superclass method.
Static methods belong to the class, not an instance, and thus cannot be overridden. If a subclass defines a static method with the same signature, it hides (shadows) the superclass's static method, and polymorphism does not apply.
Q134easy
In an `if-else` statement, if the `if` condition evaluates to `false`, which block of code will be executed?
✅ Correct Answer: C) The `else` block.
The `if-else` statement is designed to execute the `else` block only when the `if` condition evaluates to false, providing an alternative path.
Q135hardcode output
What is the output of this code?
java
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
int result = callMethod();
System.out.print("Result: " + result);
} catch (Exception e) {
System.out.print("Caught: " + e.getMessage());
if (e.getSuppressed().length > 0) {
System.out.print(" Suppressed: " + e.getSuppressed()[0].getMessage());
}
}
}
public static int callMethod() throws Exception {
try {
System.out.print("In callMethod try ");
throw new RuntimeException("Try Exception");
} finally {
System.out.print("In callMethod finally ");
throw new IOException("Finally Exception");
}
}
}
✅ Correct Answer: A) In callMethod try In callMethod finally Caught: Finally Exception Suppressed: Try Exception
Similar to try-with-resources, if an exception is thrown in `try` and then another in `finally`, the `finally` exception is propagated, and the `try` exception is suppressed. The outer `catch` block catches the `IOException` from `finally`.
Q136hardcode output
What is the output of this code?
java
public class DataTypeChallenge {
public static void main(String[] args) {
Integer i = null;
Integer j = 10;
try {
System.out.println(i == j);
} catch (Exception e) {
System.out.println("NPE Caught");
}
}
}
✅ Correct Answer: C) NPE Caught
When comparing an `Integer` wrapper object to an `int` primitive (or another `Integer` that needs unboxing), Java attempts to unbox the `Integer` objects. If an `Integer` object is `null`, unboxing it results in a `NullPointerException`.
Q137medium
When an unlabeled `break` statement is used within a `do-while` loop, what happens?
✅ Correct Answer: C) The `do-while` loop is terminated, and execution continues with the statement following the loop.
The `break` statement works consistently across all loop types. When encountered in a `do-while` loop, it terminates the loop, and program execution proceeds to the statement immediately after the loop.
Q138mediumcode error
What is the compilation error in the following Java code?
java
public class StaticAccess {
int instanceVar = 10;
public static void main(String[] args) {
System.out.println(instanceVar);
}
}
✅ Correct Answer: A) Non-static field 'instanceVar' cannot be referenced from a static context
A `static` method belongs to the class itself, not to a specific object instance. Therefore, it cannot directly access non-`static` (instance) variables, which require an object instance for their existence.
Q139hardcode error
What is the result of executing this Java code snippet?
java
class MyClass {}
public class InstanceofConfusion {
public static void main(String[] args) {
Object obj = "Hello";
if (obj instanceof String) {
MyClass mc = (MyClass) obj;
System.out.println("Cast successful");
} else {
System.out.println("Not a String");
}
}
}
✅ Correct Answer: A) A ClassCastException occurs at runtime on the line with the cast to MyClass.
The `instanceof` check correctly identifies that `obj` is an instance of `String`. However, `String` and `MyClass` are entirely unrelated classes in the inheritance hierarchy. Even though the `if` condition is true, attempting to cast a `String` object to `MyClass` at runtime results in a `ClassCastException`.
Q140medium
In the `read(char[] cbuf, int off, int len)` method of `FileReader`, what does the `off` parameter specify?
✅ Correct Answer: D) The starting offset in the destination character array `cbuf` to store the characters.
The `off` parameter determines the starting position within the `cbuf` array where the characters read from the file will be stored. `len` specifies the maximum number of characters to read.