Which exception will be thrown when executing this Java code?
java
public class StringError10 {
public static void main(String[] args) {
String input = "hello";
String[] parts = input.split("x"); // results in {"hello"}
System.out.println(parts[1]);
}
}
✅ Correct Answer: C) java.lang.ArrayIndexOutOfBoundsException
The `split("x")` method divides the string 'hello' by 'x', which doesn't exist. This results in an array `{"hello"}` with a single element at index 0. Attempting to access `parts[1]` causes an ArrayIndexOutOfBoundsException.
Q3562easy
Which method checks if a string begins with a specified prefix?
✅ Correct Answer: B) startsWith(String prefix)
The `startsWith()` method returns true if the string sequence matches the specified prefix at the beginning of the string.
Q3563mediumcode error
What is the compile-time error in the following Java code?
java
class ConfigManager {
private String configName;
private ConfigManager(String name) {
this.configName = name;
System.out.println("ConfigManager for: " + name);
}
}
public class ConstructorError9 {
public static void main(String[] args) {
ConfigManager manager = new ConfigManager(); // Attempting to use default constructor
}
}
✅ Correct Answer: A) Error: no suitable constructor found for ConfigManager()
If a class explicitly defines any constructor (even a private one like `ConfigManager(String name)`), the Java compiler will *not* automatically generate the default no-argument public constructor. Therefore, when `new ConfigManager()` is called, no matching constructor is found, leading to a 'no suitable constructor found' compile-time error.
Q3564mediumcode error
What is the error in this Java code snippet?
java
public class MyClass {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.insert(6, " World");
System.out.println(sb);
}
}
✅ Correct Answer: C) A runtime error: StringIndexOutOfBoundsException.
The StringBuilder 'sb' has a length of 5. Valid insertion points are from 0 to 5 (inclusive). Trying to insert at index 6 (which is past the end of the current sequence) will throw a StringIndexOutOfBoundsException at runtime.
Q3565hardcode output
What is the output of this code?
java
class Base {
public final void print() {
System.out.println("Base Print");
}
}
class Derived extends Base {
// Uncommenting the next lines would cause a compile-time error
// @Override
// public void print() {
// System.out.println("Derived Print");
// }
public void callPrint() {
System.out.println("Derived calls Base's final method:");
super.print();
}
}
public class Main {
public static void main(String[] args) {
Derived d = new Derived();
d.callPrint();
}
}
✅ Correct Answer: C) Derived calls Base's final method:\nBase Print
A `final` method cannot be overridden. The `Derived` class correctly does not attempt to override `print()`. Instead, `callPrint()` explicitly invokes the `final` `print()` method from its `Base` class using `super`, resulting in its execution.
Q3566medium
What is the primary implication of Java's `String` class being immutable?
✅ Correct Answer: B) Its sequence of characters (content) cannot be modified after creation.
Immutability means that once a String object is created, its internal character array and hash code cannot be altered. Any operation that seems to modify a String actually creates a new String object.
Q3567hardcode error
What runtime error will this Java code snippet throw?
java
public class Test {
public static void main(String[] args) {
int[][] matrix = new int[2][];
matrix[0] = new int[3];
matrix[1] = new int[1];
System.out.println(matrix[0][3]);
}
}
✅ Correct Answer: A) java.lang.ArrayIndexOutOfBoundsException
The array `matrix[0]` is initialized with a length of 3, meaning its valid indices are 0, 1, and 2. Attempting to access `matrix[0][3]` goes beyond these bounds, leading to an `ArrayIndexOutOfBoundsException`.
Q3568mediumcode output
What is the output of this Java code snippet?
java
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> words = new HashSet<>();
words.add("apple");
words.add(null);
words.add("banana");
words.add(null);
System.out.println(words.size());
}
}
✅ Correct Answer: B) 3
A HashSet can store exactly one null element. Subsequent attempts to add null are ignored, similar to adding any duplicate element. The set will contain "apple", "banana", and null.
Q3569hard
What is the correct approach to handling a checked exception thrown within a static initializer block in Java?
✅ Correct Answer: C) Catch the checked exception, and the JVM automatically wraps it in an `ExceptionInInitializerError`.
Static initializer blocks cannot declare `throws`. If a checked exception occurs within a static initializer and is not caught, the JVM catches it and wraps it in an `ExceptionInInitializerError`, which is then thrown.
Q3570easycode output
What will be the content of the file 'output.txt' after this code executes?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterTest {
public static void main(String[] args) {
char[] suffix = {'X', 'Y', 'Z'};
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Prefix");
writer.write(suffix);
} catch (IOException e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: A) PrefixXYZ
The `FileWriter` first writes the string 'Prefix', then immediately appends the characters from the `suffix` array, resulting in 'PrefixXYZ' being written to the file.
Q3571mediumcode output
What does this code print?
java
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(null, "Zero");
map.put(2, null);
System.out.println(map.get(null));
}
}
✅ Correct Answer: A) Zero
HashMap allows one null key and multiple null values. Accessing the map with the null key retrieves its associated value, which is 'Zero'.
Q3572hard
Consider a symbolic link `link.txt` pointing to `/absolute/path/to/target.txt`. If `new File("link.txt").getCanonicalPath()` is called from `/current/directory`, what will be the likely outcome compared to `getAbsolutePath()`?
✅ Correct Answer: A) `getCanonicalPath()` resolves symbolic links to their ultimate target, returning `/absolute/path/to/target.txt`. `getAbsolutePath()` only resolves relative path components (`.` and `..`) against the current working directory, returning `/current/directory/link.txt`.
`getCanonicalPath()` returns the unique absolute path by resolving all symlinks, `.` and `..` components. `getAbsolutePath()` only resolves `.` and `..` relative to the current directory, leaving symbolic link names unresolved in the path string.
Q3573easycode error
What error will this code produce?
java
public class LoopError {
public static void main(String[] args) {
for (final int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
✅ Correct Answer: A) Compile-time error: cannot assign a value to final variable i
The loop variable 'i' is declared as 'final', meaning its value cannot be changed after initialization. The increment operation 'i++' attempts to modify 'i', which is forbidden for a final variable, resulting in a compile-time error.
Q3574mediumcode error
What error will prevent the `Calculator` class from compiling?
java
class Calculator {
int operand = 10;
static void printOperand() {
System.out.println(this.operand);
}
}
public class Main {
public static void main(String[] args) {
Calculator.printOperand();
}
}
✅ Correct Answer: B) Compile-time error: 'non-static variable this cannot be referenced from a static context'.
The `this` keyword refers to the current instance of an object. Static methods are associated with the class, not a specific instance, so `this` cannot be used inside a static method.
Q3575hardcode error
What is the compilation error, if any, for the provided Java code snippet?
java
import java.util.List;
class Overloader {
public void add(List<String> list) {}
public void add(List<Integer> list) {} // Line X
public static void main(String[] args) {
Overloader o = new Overloader();
}
}
✅ Correct Answer: B) error: name clash: add(List<String>) and add(List<Integer>) have the same erasure
Due to type erasure in Java, generic type parameters (`<String>`, `<Integer>`) are removed at compile time. Both methods erase to `add(List list)`. The compiler sees these as two methods with identical signatures, leading to a 'name clash' error as neither method overrides the other.
Q3576easy
Which core Java interface does HashMap implement?
✅ Correct Answer: C) Map
HashMap is a concrete implementation of the `java.util.Map` interface, providing a way to store key-value pairs.
Q3577mediumcode error
Consider the following Java code snippet. What will prevent it from compiling successfully?
java
public class ArrayMutationExample {
public static void main(String[] args) {
final int[] numbers = {1, 2, 3};
numbers[0] = 10; // This is allowed as array contents are mutable
numbers = new int[]{4, 5, 6}; // This line causes an error
}
}
✅ Correct Answer: A) Cannot assign a value to final variable 'numbers'
The 'final' keyword on the 'numbers' array reference means the reference itself cannot be reassigned to a different array object. While the contents of the array can be modified, changing the reference is a compilation error.
Q3578easycode output
What is the output of this Java code snippet?
java
public class Main {
public static void main(String[] args) {
int num = 0;
if (num > 0) {
System.out.println("Positive");
} else if (num < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
}
}
✅ Correct Answer: C) Zero
The first condition `num > 0` (0 > 0) is false. The second condition `num < 0` (0 < 0) is also false. Therefore, the `else` block is executed, printing 'Zero'.
Q3579hardcode error
What is the compilation error in the `MyGenericException` class definition?
java
class MyGenericException<T> extends Exception { // This line causes the compilation error
public MyGenericException(T data) {
super(data.toString());
}
}
public class Main {
public static void main(String[] args) {
// MyGenericException<String> e = new MyGenericException<>("Error");
}
}
✅ Correct Answer: C) error: generic class MyGenericException<T> may not directly or indirectly extend java.lang.Throwable
Java's type erasure mechanism for generics makes it impossible to check for specific exception types at runtime. Therefore, generic classes are prohibited from extending `java.lang.Throwable` or any of its subclasses.
Q3580mediumcode output
What will be the output when this Java program is run?
java
class Shape {
void draw() {
System.out.println("Drawing a generic shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a Square");
}
}
public class Main {
public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Square();
s1.draw();
s2.draw();
}
}
✅ Correct Answer: A) Drawing a Circle
Drawing a Square
This demonstrates polymorphism. Even though `s1` and `s2` are declared as `Shape` references, they point to `Circle` and `Square` objects, respectively. Dynamic method dispatch ensures that the overridden `draw()` method of the actual object type is called at runtime.