public class Main {
public static void main(String[] args) {
int temp = 25;
if (temp > 30) {
System.out.println("It's hot!");
} else {
System.out.println("It's pleasant.");
}
}
}
✅ Correct Answer: B) It's pleasant.
The condition `temp > 30` (25 > 30) is false, so the `else` block is executed, printing 'It's pleasant.'.
Q1022medium
Which statement correctly describes a Java abstract class?
✅ Correct Answer: C) A class that extends an abstract class must implement all inherited abstract methods, or be declared abstract itself.
If a concrete class extends an abstract class, it must provide implementations for all inherited abstract methods. Otherwise, it must also be declared abstract. An abstract class can have zero abstract methods and cannot be instantiated.
Q1023mediumcode error
What is the compile-time or runtime error in the following Java code snippet when `main` method is executed?
java
import java.io.*;
class Logger implements Serializable {
private String logName;
// FileInputStream is not serializable
private FileInputStream fis;
public Logger(String name, String filePath) throws FileNotFoundException {
this.logName = name;
this.fis = new FileInputStream(filePath);
}
}
public class SerializationQuestion10 {
public static void main(String[] args) throws IOException {
// Create a dummy file for FileInputStream to exist
try (FileOutputStream tempFos = new FileOutputStream("dummy.txt")) {
tempFos.write("temp data".getBytes());
}
Logger logger = new Logger("AppLog", "dummy.txt");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("logger.ser"))) {
oos.writeObject(logger);
}
}
}
✅ Correct Answer: A) java.io.NotSerializableException: java.io.FileInputStream
For an object to be serializable, all its non-transient and non-static fields must also be serializable. `java.io.FileInputStream` is a stream class and does not implement the `Serializable` interface. Therefore, attempting to serialize an instance of `Logger` which holds a `FileInputStream` field will result in a `NotSerializableException` for `FileInputStream`.
Q1024medium
Given the String `input = "one,,two,three"`, what would be the length of the array returned by `input.split(",")`?
✅ Correct Answer: B) 4
The `split()` method handles consecutive delimiters by inserting empty strings into the resulting array. For `"one,,two,three"`, the array would be `["one", "", "two", "three"]`, which has a length of 4.
Q1025medium
Which of the following Java Collection API methods commonly accepts a lambda expression, typically an instance of `Comparator`, for custom sorting behavior?
✅ Correct Answer: C) `List.sort(Comparator c)`
The `List.sort()` method takes a `Comparator` functional interface as an argument, which can be elegantly implemented using a lambda expression to define custom sorting logic.
Q1026hardcode output
What does this code print?
java
interface Calculator {
static int add(int a, int b) {
return a + b;
}
default int subtract(int a, int b) {
return a - b;
}
}
class BasicCalculator implements Calculator {}
public class StaticInterfaceTest {
public static void main(String[] args) {
System.out.println(Calculator.add(10, 5));
}
}
✅ Correct Answer: A) 15
Static methods in an interface can be called directly using the interface name. `Calculator.add(10, 5)` invokes the static `add` method, returning the sum 15.
Q1027easycode output
What does this code print?
java
interface Drivable {
void drive();
}
class Truck implements Drivable {
@Override
public void drive() {
System.out.println("Driving a truck.");
}
}
public class Main {
public static void main(String[] args) {
Drivable d = new Truck();
d.drive();
}
}
✅ Correct Answer: B) Driving a truck.
Polymorphism allows an interface reference (`Drivable`) to hold an object of a class that implements it (`Truck`). Calling `drive()` on the interface reference executes the `Truck` class's implementation.
Q1028hard
Given an `ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));` and a `ListIterator<String> lit = list.listIterator();`. After calling `lit.next();` and then `lit.set("Z");`, what is the effect on the list's `modCount` and how does this affect subsequent `next()` or `previous()` calls by `lit`?
✅ Correct Answer: C) `modCount` is not incremented, as `set()` is a non-structural modification, and the `ListIterator` remains valid.
The `ListIterator.set()` method replaces the last element returned by `next()` or `previous()`. This is considered a non-structural modification as it doesn't change the list's size or element order. Therefore, it does not increment the `modCount` of the underlying `ArrayList`, and the `ListIterator` remains valid for subsequent operations.
Q1029medium
If you declare `String[][] names = new String[2][];` but do not initialize the inner arrays (e.g., `names[0] = new String[3];`), what will be the value of `names[0]`?
✅ Correct Answer: B) `null`.
When only the outer array's dimension is specified, each element of the outer array (which should hold a reference to an inner array) is initialized to `null` by default until explicitly assigned a new array.
Q1030hardcode output
What does this code print?
java
import java.util.Arrays;
public class ArrayFillObjectReference {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
StringBuilder[] sbs = new StringBuilder[3];
Arrays.fill(sbs, sb);
sbs[0].append(" World");
for (StringBuilder s : sbs) {
System.out.println(s);
}
}
}
✅ Correct Answer: A) Hello World
Hello World
Hello World
`Arrays.fill(sbs, sb)` populates all elements of the `sbs` array with the *same reference* to the single `StringBuilder` object `sb`. Therefore, when `sbs[0].append(" World")` modifies that `StringBuilder` object, the change is reflected through all references in the array.
Q1031easycode output
What does this code print?
java
public class Main {
public static void main(String[] args) {
int value = 0;
try {
value = 10;
int x = 1 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
value = 30;
} finally {
value = 40;
}
System.out.println(value);
}
}
✅ Correct Answer: A) 40
The 'try' block sets 'value' to 10, then throws an ArithmeticException. The 'catch' block sets 'value' to 30. Finally, the 'finally' block executes, setting 'value' to 40, which is then printed.
Q1032easycode error
What kind of error will this Java code produce?
java
public class LoopError3 {
public static void main(String[] args) {
int value; // Not initialized
while (value < 10) { // Error here
System.out.println("Value is: " + value);
value++;
}
}
}
✅ Correct Answer: A) Compile-time error: Variable `value` might not have been initialized.
Local variables in Java must be explicitly initialized before they are used. The compiler will catch that `value` might not have been initialized before being used in the `while` loop condition, resulting in a compile-time error.
Q1033mediumcode error
What error occurs when running this Java code?
java
public class MyClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.deleteCharAt(4);
System.out.println(sb);
}
}
✅ Correct Answer: A) IndexOutOfBoundsException
The `deleteCharAt(int index)` method requires the index to be valid (0 to length-1). For "Java" (length 4), valid indices are 0-3. Index 4 is out of bounds, leading to an `IndexOutOfBoundsException`.
`base + ext` involves variables, so it's a runtime operation creating a new `String` object on the heap, thus `fullLiteral == concatenated1` is `false`. `"base" + "ext"` is a compile-time constant, so it resolves to `"baseext"` in the string pool, making `fullLiteral == concatenated2` `true`. `(base + ext).intern()` explicitly fetches the `"baseext"` from the string pool (or adds it if not present), making `fullLiteral == interned` `true`.
Q1035easycode error
What compile-time error will occur in the `Child` class?
java
class Parent {
public final void greeting() {
System.out.println("Hello from Parent");
}
}
class Child extends Parent {
@Override
public void greeting() {
System.out.println("Hello from Child");
}
}
✅ Correct Answer: A) Error: `greeting()` in `Child` cannot override `greeting()` in `Parent`; overridden method is final
Methods declared as `final` cannot be overridden by subclasses. Attempting to do so results in a compile-time error.
Q1036mediumcode error
Identify the runtime error in the following Java code snippet.
java
import java.util.TreeMap;
class CustomKey {
int id;
public CustomKey(int id) { this.id = id; }
}
public class Main {
public static void main(String[] args) {
TreeMap<CustomKey, String> map = new TreeMap<>();
map.put(new CustomKey(1), "One");
map.put(new CustomKey(2), "Two");
}
}
✅ Correct Answer: B) java.lang.ClassCastException
CustomKey does not implement the Comparable interface, and no custom Comparator is provided to the TreeMap constructor. TreeMap attempts to cast CustomKey objects to Comparable to perform sorting, leading to a ClassCastException at runtime.
Q1037mediumcode error
What kind of error will occur when compiling the following Java code, assuming 'existing.txt' exists?
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TestClass {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("existing.txt"));
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
} finally {
if (br != null) {
br.close();
}
}
}
}
✅ Correct Answer: C) Compile-time error: unhandled exception type IOException on `br.close()`.
The `close()` method of `BufferedReader` can throw an `IOException`. Even within a `finally` block, this checked exception must be handled explicitly with its own `try-catch` or by declaring `throws IOException` on the enclosing method.
Q1038hard
Consider a class `Wallet` with a `private List<String> notes;` field. To properly encapsulate `notes` when returned via a public getter, which approach is crucial?
✅ Correct Answer: B) `return new ArrayList<>(notes);` (returning a defensive copy)
Returning a defensive copy ensures that the internal mutable list `notes` cannot be modified by external code holding the returned reference, thus preserving encapsulation. While `Collections.unmodifiableList` provides a read-only view, it doesn't prevent internal modifications if the original list is still accessible and mutable within the class.
Q1039hard
A thread `T` is in the `TIMED_WAITING` state after calling `Thread.sleep(1000)`. If another thread calls `T.interrupt()` immediately, what state will `T` enter after the interruption?
✅ Correct Answer: A) `RUNNABLE`, and it will throw an `InterruptedException` when it wakes up.
`Thread.sleep()` is an interruptible method. If a thread is interrupted while sleeping, it will wake up early, throw an `InterruptedException`, and transition to the `RUNNABLE` state.
Q1040mediumcode error
What error will this Java code produce?
java
public class ArrayError {
public static void main(String[] args) {
int[][] matrix = new { {1,2}, {3,4} };
System.out.println(matrix[0][0]);
}
}
✅ Correct Answer: A) Compile-time error: illegal start of expression
When using the `new` keyword with an array initializer, you must specify the array's type. For example, `new int[][]{ {1,2}, {3,4} }`. Omitting `int[][]` after `new` is a syntax error.