What is the runtime error when executing the provided Java code snippet?
java
public class NullSwitchError {
public static void main(String[] args) {
Integer value = null;
String result = switch (value) { // Error expected at runtime
case 1 -> "One";
case 2 -> "Two";
default -> "Other";
};
System.out.println(result);
}
}
✅ Correct Answer: B) Runtime error: 'java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "value" is null'
When the selector expression of a `switch` expression evaluates to `null` and there is no explicit `case null` label, a `NullPointerException` is thrown at runtime. For an `Integer` selector matching `int` constants, it attempts to unbox the `Integer`, leading to the NPE.
Q2easy
Which of the following correctly declares and initializes a single-dimensional array named `colors` with values "Red", "Green", and "Blue"?
✅ Correct Answer: A) String[] colors = {"Red", "Green", "Blue"};
This syntax allows direct initialization of an array with a list of values enclosed in curly braces, where the size is inferred automatically.
Q3hard
When a class with mutable `private` fields is serialized and deserialized using default mechanisms, what is a key encapsulation concern?
✅ Correct Answer: B) The deserialized object might not uphold the original object's invariants if the default deserialization bypasses constructor validation.
Default deserialization recreates an object by directly assigning values to its fields, bypassing constructors and any validation logic within them. This can lead to a deserialized object having an invalid state, thereby breaking encapsulation by failing to maintain its invariants.
Q4easycode error
What will be the outcome when compiling and running this Java code?
java
public class StringModification {
public static void main(String[] args) {
String myString = "Java";
myString.charAt(0) = 'j';
System.out.println(myString);
}
}
✅ Correct Answer: A) Compile-time error: "The left-hand side of an assignment must be a variable"
`String.charAt(index)` returns a `char` primitive value, not a reference to a modifiable character within the string. Strings are immutable in Java, so their internal character sequence cannot be changed after creation.
Q5hardcode output
What does this code print?
java
abstract class Shape {
abstract void draw();
protected void display() { System.out.println("Shape display"); }
}
class Circle extends Shape {
@Override
public void draw() { System.out.println("Drawing Circle"); }
@Override
public void display() { System.out.println("Circle display"); }
}
public class Test {
public static void main(String[] args) {
Shape s = new Circle();
s.draw();
s.display();
}
}
✅ Correct Answer: A) Drawing Circle
Circle display
Overridden methods can widen their access modifier (e.g., from `protected` to `public`). Both `draw()` and `display()` are overridden in `Circle`. Dynamic method dispatch ensures that the `Circle` class implementations are called when `s` points to a `Circle` object.
Q6hardcode error
What is the result of compiling and running the following Java code snippet?
java
public class StringError {
public static void main(String[] args) {
String text = "hello";
System.out.println(text.codePointAt(10));
}
}
✅ Correct Answer: B) Throws StringIndexOutOfBoundsException
The codePointAt() method accesses a character by index. Since the string 'hello' has a length of 5 (indices 0-4), attempting to access index 10 results in a StringIndexOutOfBoundsException at runtime.
Q7easycode error
What is the output or error of the following Java code?
java
public class ExceptionTest {
public static void main(String[] args) {
try (Object obj = new Object()) {
System.out.println("Inside try-with-resources");
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
✅ Correct Answer: C) Compilation Error: Resource variable obj must be of a type that implements java.lang.AutoCloseable.
In a try-with-resources statement, the resource declared in the parentheses must be of a type that implements the `java.lang.AutoCloseable` interface. `Object` does not implement this, leading to a compilation error.
Q8hardcode output
What is the output of this code?
java
import java.util.Date;
final class MyImmutableDate {
private final Date value;
public MyImmutableDate(Date value) {
this.value = new Date(value.getTime()); // Defensive copy
}
public Date getValue() {
return new Date(value.getTime()); // Defensive copy
}
}
public class Main {
public static void main(String[] args) {
Date originalDate = new Date(0);
MyImmutableDate immutableDate = new MyImmutableDate(originalDate);
originalDate.setYear(120); // Modify original
immutableDate.getValue().setYear(121); // Modify obtained copy
System.out.println(immutableDate.getValue().getYear());
}
}
✅ Correct Answer: A) 70
The `MyImmutableDate` class correctly implements defensive copying in both its constructor and getter for the mutable `Date` field. Therefore, modifications to the `originalDate` or the `Date` object returned by `getValue()` do not affect the internal state of `immutableDate`. `new Date(0)` represents Jan 1, 1970, 00:00:00 GMT, so `getYear()` returns 70 (1970 - 1900).
Q9mediumcode error
What is the error in this Java code?
java
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
List<String> inventory = null;
inventory.add("Sword"); // Attempt to add to a null list
System.out.println(inventory.size());
}
}
✅ Correct Answer: B) Runtime Error: `NullPointerException`.
The `inventory` list is explicitly initialized to `null`. Attempting to call any method (like `add()`) on a `null` object will result in a `NullPointerException` at runtime.
Q10hard
Which statement accurately describes the time complexity characteristics of `java.util.LinkedList` for a list containing N elements?
✅ Correct Answer: B) Adding or removing an element at either end of the list (e.g., addFirst(), removeLast()) is O(1), but retrieving an element by index (get(int index)) is O(N).
LinkedList's doubly linked nature allows O(1) additions/removals at its ends. However, indexed access (get(int index)) or insertions/deletions in the middle require O(N) traversal from either end.
Q11mediumcode output
What is the output of the following Java code?
java
public class SpecificNullOverload {
void execute(Object o) {
System.out.println("Object arg");
}
void execute(Integer i) {
System.out.println("Integer arg");
}
public static void main(String[] args) {
SpecificNullOverload sno = new SpecificNullOverload();
sno.execute(null);
}
}
✅ Correct Answer: A) Integer arg
When `null` can be assigned to multiple reference types, the compiler chooses the most specific one. `Integer` is a subclass of `Object`, making `Integer` more specific than `Object` for a `null` argument.
Q12hard
Which specific method of its internal `HashMap` does `HashSet.add(E e)` primarily invoke to store an element, considering `HashSet` only stores keys and uses a dummy value?
✅ Correct Answer: C) `map.put(e, PRESENT)` (where `PRESENT` is a static dummy `Object`)
`HashSet` is a wrapper around a `HashMap`. Its `add(E e)` method calls `map.put(e, PRESENT)`, using a static final dummy `Object` as the value for all entries, effectively using the `HashMap`'s keyset as the `HashSet` elements.
Q13hard
Given a `TreeMap<Integer, String> map = new TreeMap<>(); map.put(10, "Ten"); map.put(20, "Twenty"); map.put(30, "Thirty");`. What will `map.lowerEntry(10)` return?
✅ Correct Answer: C) `null`.
The `lowerEntry(key)` method returns the entry associated with the greatest key *strictly less than* the given key. Since there is no key strictly less than `10` in the map, it returns `null`.
Q14mediumcode error
What is the output of this Java code?
java
public class ExceptionFlow1 {
public static void main(String[] args) {
System.out.println(testMethod());
}
public static String testMethod() {
try {
System.out.println("In try");
return "Success";
} catch (Exception e) {
System.out.println("In catch");
return "Failure";
} finally {
System.out.println("In finally");
}
}
}
✅ Correct Answer: A) In try
In finally
Success
The 'try' block executes first. Since no exception occurs, the 'return' statement is processed. However, the 'finally' block always executes before the method actually returns, hence 'In finally' prints after 'In try' but before 'Success' is returned.
Q15medium
Which of the following statements about `java.util.LinkedList` memory usage compared to `java.util.ArrayList` is generally true?
✅ Correct Answer: B) `LinkedList` generally uses more memory per element due to the overhead of storing pointers in each node.
Each node in a LinkedList stores the data element itself, plus two references (pointers) to the previous and next nodes. This overhead per element typically makes LinkedList use more memory than an ArrayList for the same number of elements.
Q16easycode output
What is the output of this code?
java
class CharacterPrinter {
public void printChar(char c) {
System.out.print(c);
}
}
public class MyProgram {
public static void main(String[] args) throws InterruptedException {
CharacterPrinter cp = new CharacterPrinter();
Thread t1 = new Thread(() -> {
cp.printChar('A');
cp.printChar('B');
});
Thread t2 = new Thread(() -> {
cp.printChar('C');
cp.printChar('D');
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
✅ Correct Answer: C) The output can be any interleaving of 'ABCD'
Neither the `printChar` method nor the calls to it are synchronized. This means the scheduler can switch between `t1` and `t2` at any point, resulting in various possible interleavings of the characters 'A', 'B', 'C', and 'D'. For example, 'ACBD', 'CABD', 'ABCD', 'CDAB', etc., are all valid outputs.
Q17hardcode error
What compilation error will occur when compiling the following Java code?
java
import java.util.function.Function;
public class LambdaVoidReturn {
public static void main(String[] args) {
Function<String, Integer> stringToInt = s -> System.out.println(s);
}
}
✅ Correct Answer: A) Error: incompatible types: bad return type in lambda expression; void cannot be converted to Integer
The `Function<String, Integer>` functional interface expects its `apply` method to return an `Integer`. However, the lambda expression `s -> System.out.println(s)` calls `System.out.println(s)`, which has a `void` return type. This creates a type mismatch, as `void` cannot be converted to `Integer`.
Q18easycode error
What kind of error will occur when this Java code is executed?
java
public class Test {
public static void main(String[] args) {
StringBuilder sb = null;
sb.append("Hello");
System.out.println(sb);
}
}
✅ Correct Answer: A) Runtime Error: java.lang.NullPointerException
Attempting to invoke a method (`append()`) on a `StringBuilder` reference that is `null` will lead to a `NullPointerException` at runtime.
Q19easy
What is considered a best practice for managing system resources after using a `FileReader`?
✅ Correct Answer: C) Call the `close()` method.
It is crucial to call the `close()` method on a `FileReader` to release associated system resources and prevent resource leaks.
Q20hardcode error
What kind of runtime error or unexpected behavior will occur when running this Java code, primarily related to thread lifecycle?
java
public class ReStartThread implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + " running.");
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new ReStartThread(), "TestThread");
t.start();
t.join(); // Wait for the thread to terminate
System.out.println("TestThread state after join: " + t.getState());
t.start(); // Problem line
}
}
✅ Correct Answer: B) An `IllegalThreadStateException` will be thrown at runtime.
A `java.lang.Thread` instance can only be started once. Attempting to call `start()` on a thread that has already completed its execution (is in the `TERMINATED` state) will result in an `IllegalThreadStateException`.