public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Start");
sb.setLength(10);
sb.setCharAt(7, 'X');
sb.setCharAt(9, 'Y');
System.out.println(sb.length() + " [" + sb.toString() + "]");
}
}
✅ Correct Answer: A) 10 [Start X Y]
`setLength(10)` expands the StringBuilder to length 10, filling new positions with null characters (`\u0000`). `setCharAt(7, 'X')` and `setCharAt(9, 'Y')` replace null characters. When `toString()` is called, these null characters are included in the string and `System.out.println` typically renders `\u0000` as an empty space.
Q1062mediumcode error
Consider the following Java code. What type of error will it produce at compile time?
java
public class CustomRunnable implements Runnable {
@Override
public void run(String message) {
System.out.println("Running with: " + message);
}
}
public class Main {
public static void main(String[] args) {
CustomRunnable task = new CustomRunnable();
}
}
✅ Correct Answer: A) Compilation error: Method does not override method from its superclass/interface.
The `run()` method of the `Runnable` interface has the signature `public void run()`. Overriding it with `public void run(String message)` changes its signature, meaning the interface's `run()` method is not actually implemented. This results in a compilation error.
Q1063easy
If no `case` label matches the `switch` expression and there is no `default` label, what happens?
✅ Correct Answer: C) The program continues execution after the `switch` statement, and nothing inside the `switch` block is executed.
If no `case` matches and there is no `default` block, the `switch` statement simply completes without executing any of its code blocks, and execution continues with the statement immediately following the `switch`.
Q1064easycode output
What is the output of this Java program?
java
public class Main {
public static void main(String[] args) {
int m = 5;
int n = ++m;
System.out.println("m=" + m + ", n=" + n);
}
}
✅ Correct Answer: D) m=6, n=6
The pre-increment operator `++m` increments `m` first, making it 6, and then uses this new value for the assignment to `n`. So, both `m` and `n` become 6.
Q1065easycode error
What compile-time error will this code produce?
java
class Worker implements Runnable {
public void run(String message) {
System.out.println(message);
}
}
public class Main {
public static void main(String[] args) {
Worker worker = new Worker();
Thread thread = new Thread(worker);
thread.start();
}
}
✅ Correct Answer: A) Error: Worker is not abstract and does not override abstract method run() in Runnable
The `run()` method required by the `Runnable` interface must have the signature `public void run()`. Providing `public void run(String message)` is not an override, thus the interface's method remains unimplemented.
Q1066hardcode error
What is the runtime error when `main` method is executed?
java
class MyChainedException extends Exception {
public MyChainedException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
MyChainedException exc = new MyChainedException("Primary error");
exc.initCause(new IllegalArgumentException("First cause"));
// Attempting to overwrite the cause after it has been set
exc.initCause(new NullPointerException("Second cause")); // This line causes a runtime error
}
}
✅ Correct Answer: C) java.lang.IllegalStateException: Can't overwrite cause
The `initCause()` method can only be called once on an exception object. If the cause has already been set (either through a constructor or a previous call to `initCause()`), subsequent calls will throw an `IllegalStateException`.
Q1067hardcode error
What compilation error will occur when compiling the following Java code?
java
import java.util.function.IntFunction;
public class RecursiveLambdaError {
public static void main(String[] args) {
IntFunction<Integer> factorial = n -> n == 0 ? 1 : n * factorial.apply(n - 1);
System.out.println(factorial.apply(5));
}
}
✅ Correct Answer: A) Error: variable factorial might not have been initialized
During the initialization of `factorial`, the lambda expression attempts to reference `factorial` itself. At this point, `factorial` has not been fully initialized, leading to a compile-time error that the variable might not have been initialized. To achieve recursive lambdas, a mutable holder (like `AtomicReference`) is typically used.
Q1068medium
When an `ArrayList` is initialized with a specific initial capacity (e.g., `new ArrayList<>(10)`) but no elements are added, what is its `size()` and internal array capacity?
✅ Correct Answer: A) The `size()` is 0, and the internal array capacity is 10.
The `size()` method returns the number of elements actually present in the list, which is 0. The initial capacity refers to the pre-allocated space in the internal array, not the number of elements.
Q1069easycode output
What does this Java code print?
java
public class StringBuilding {
public static void main(String[] args) {
String result = "";
for (int i = 0; i < 2; i++) {
result += i;
}
System.out.println(result);
}
}
✅ Correct Answer: A) 01
In each iteration of the loop, a new String object is created by concatenating the current `result` and the integer `i`. The `result` variable is then reassigned to this new String. So, it effectively builds the string "01".
Q1070mediumcode error
Analyze the given Java code and determine the type of error that occurs when `myMethod(null)` is called.
java
public class OverloadChecker {
public void myMethod(Integer i) {
System.out.println("Integer: " + i);
}
public void myMethod(String s) {
System.out.println("String: " + s);
}
public static void main(String[] args) {
OverloadChecker oc = new OverloadChecker();
oc.myMethod(null); // This line causes the error
}
}
✅ Correct Answer: A) Compile-time error: Reference to 'myMethod' is ambiguous, both 'myMethod(Integer)' and 'myMethod(String)' match.
When `null` is passed as an argument, it can be assigned to any reference type. Since both `Integer` and `String` are valid reference types for `null`, the compiler cannot determine which overloaded method to invoke, leading to an ambiguous method call error.
Q1071easy
If a lambda expression requires multiple statements in its body, how must the body be structured?
✅ Correct Answer: C) It must be enclosed in curly braces `{}`, with statements separated by semicolons.
For a multi-statement lambda body, it must be treated as a code block and enclosed in curly braces `{}`, with each statement ending in a semicolon.
Q1072hardcode output
What is the output of this Java code?
java
import java.util.TreeMap;
import java.util.NoSuchElementException;
public class Test {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
try {
map.firstKey(); // Throws NoSuchElementException on empty map
System.out.println("Should not reach here");
} catch (NoSuchElementException e) {
map.put(1, "One");
map.put(2, "Two");
System.out.println(map.lastKey());
} catch (Exception e) {
System.out.println("Other Exception");
}
}
}
✅ Correct Answer: A) 2
Calling `firstKey()` or `lastKey()` on an empty `TreeMap` throws a `NoSuchElementException`. The `catch` block handles this, populates the map, and then `lastKey()` correctly returns the largest key, which is 2.
Q1073easycode error
What error will occur when compiling the following Java code?
java
public class Main {
public static void main(String[] args) {
int a = 5;
int result = a + ++10;
System.out.println(result);
}
}
✅ Correct Answer: B) Compilation Error: `variable expected`
The increment operator `++` can only be applied to variables, not to literal values or expressions. Trying to increment a literal like `10` results in a 'variable expected' compilation error.
Q1074easy
What kind of type casting occurs when you assign an `int` variable to a `byte` variable?
✅ Correct Answer: C) Narrowing casting
Assigning an `int` to a `byte` is a narrowing conversion because `int` is a larger data type than `byte`, requiring an explicit cast to prevent potential data loss.
Q1075easycode error
What is the primary issue with this Java code snippet?
java
public class LoopError1 {
public static void main(String[] args) {
int i = 0;
while (i < 3); { // Semicolon here
System.out.println("i: " + i);
i++;
}
}
}
✅ Correct Answer: A) Compile-time error: Unreachable code.
The semicolon after the `while` condition creates an empty loop body, making the `while` loop run infinitely without `i` ever being incremented. The subsequent block of code is treated as a separate, unreachable block after the infinite empty loop, leading to a compile-time error.
Q1076easycode output
What is the output of this code?
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<>();
ts.add(1);
ts.add(2);
ts.add(3);
System.out.println(ts.contains(2) + " " + ts.contains(4));
}
}
✅ Correct Answer: B) true false
The contains() method checks if the specified element is present in the set. 2 is present, so it returns true; 4 is not, so it returns false.
Q1077hardcode output
Consider the `User` class is immutable. What is the output of this code snippet, assuming `getName()` and `getAge()` return the values set in the constructor?
java
final class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name; // String is immutable
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
public class Main {
public static void main(String[] args) {
User user1 = new User("Alice", 30);
User user2 = user1; // Reference assignment
user1 = new User("Bob", 35);
System.out.println(user2.getName() + "," + user2.getAge());
}
}
✅ Correct Answer: B) Alice,30
`User` is an immutable class. When `user2 = user1` is executed, `user2` points to the *same* `User` object that `user1` was pointing to (the "Alice", 30 object). The subsequent line `user1 = new User("Bob", 35)` reassigns `user1` to a *new* `User` object. This operation does not affect the object that `user2` is still referencing. Therefore, `user2` still refers to the original "Alice", 30 object.
Q1078medium
What is the primary benefit of using a `try-with-resources` statement in Java?
✅ Correct Answer: B) It ensures that resources implementing `AutoCloseable` are automatically closed, even if exceptions occur.
`try-with-resources` automatically closes any resource declared within its parentheses that implements `AutoCloseable` (or `Closeable`). This prevents resource leaks and simplifies error handling compared to manual `finally` blocks.
Q1079easy
Is `java.util.LinkedList` inherently synchronized?
✅ Correct Answer: B) No, it is not synchronized.
`LinkedList` is not synchronized. For thread-safe operations, it must be explicitly synchronized externally or wrapped using `Collections.synchronizedList()`.
Q1080hardcode output
What is the output of this code? (Assuming Java 17+)
java
public class SwitchTest {
public static void main(String[] args) {
Object data = 12.3; // Double value
String output = switch (data) {
case Integer i -> "Integer: " + i;
case var v when v instanceof Double d -> "Double value: " + d;
case String s -> "String: " + s;
case var v -> "Catch all: " + v.getClass().getSimpleName();
};
System.out.println(output);
}
}
✅ Correct Answer: B) Double value: 12.3
The `data` variable holds a `Double`. The `case var v when v instanceof Double d` pattern is a guarded pattern that matches `Double` values and extracts them into `d`. The `var` type pattern essentially acts as an unconditional type match if no guard is present, or for general type checks with `when`.