Under what conditions can a lambda expression be serialized in Java?
✅ Correct Answer: D) If the target functional interface is serializable, and the lambda body does not capture any non-serializable objects or depend on non-serializable state.
For a lambda to be serializable, its target functional interface must extend `Serializable`, and all objects captured by the lambda (e.g., effectively final local variables) must also be serializable.
Q1702hardcode output
What is the output of this code?
java
import java.io.PrintStream;
class MyCustomException extends Exception {
public MyCustomException(String message) { super(message); }
@Override
public void printStackTrace(PrintStream s) {
s.println("--- Custom Stack Trace Start ---");
super.printStackTrace(s);
s.println("--- Custom Stack Trace End ---");
}
}
public class Main {
public static void thrower() throws MyCustomException { throw new MyCustomException("Something went wrong!"); }
public static void main(String[] args) {
try { thrower(); }
catch (MyCustomException e) { e.printStackTrace(System.out); }
}
}
✅ Correct Answer: A) --- Custom Stack Trace Start ---
MyCustomException: Something went wrong!
at Main.thrower(Main.java:...)
at Main.main(Main.java:...)
--- Custom Stack Trace End ---
The `MyCustomException` overrides `printStackTrace(PrintStream s)` to add custom header and footer messages. When `e.printStackTrace(System.out)` is called, it will print these custom lines along with the standard stack trace provided by `super.printStackTrace(s)`.
Q1703mediumcode 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 Engine {
String type = "V8";
}
class Car implements Serializable {
private String model = "Ferrari";
private Engine engine = new Engine(); // Engine is not Serializable
}
public class SerializationQuestion1 {
public static void main(String[] args) throws IOException {
Car myCar = new Car();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("car.ser"))) {
oos.writeObject(myCar);
}
}
}
✅ Correct Answer: A) java.io.NotSerializableException: Engine
When an object of a `Serializable` class is serialized, all its non-transient and non-static fields must also be `Serializable`. Here, the `Car` class is `Serializable`, but its `engine` field of type `Engine` is not, leading to a `NotSerializableException`.
Q1704mediumcode error
Examine the Java code below. What kind of compilation error will it yield?
java
public class TernaryTypeMismatch {
public static void main(String[] args) {
String message = (10 > 5) ? "Greater" : 123;
System.out.println(message);
}
}
✅ Correct Answer: B) Cannot convert from int to String
The ternary operator's second and third operands must be compatible or convertible to a common type. Here, '"Greater"' is a String and '123' is an int. Since String cannot be implicitly cast from an int, a compilation error occurs.
Q1705medium
Which type of argument does the `BufferedWriter` constructor typically accept to wrap another stream or writer?
✅ Correct Answer: D) A `Writer` object.
`BufferedWriter` is a character output stream that wraps another `Writer` object. Its constructor requires an instance of a `Writer` (e.g., `FileWriter`, `OutputStreamWriter`) to which it will buffer data before writing.
Q1706medium
To insert characters into an existing `StringBuffer` at a specified index, which method should be used?
✅ Correct Answer: A) `insert(int index, String str)`
The `insert()` method of `StringBuffer` allows you to add a string or other data types at a specific position within the existing character sequence, shifting subsequent characters.
Q1707easy
When `break` is executed inside a nested loop without any labels, which loop does it affect?
✅ Correct Answer: A) It terminates only the innermost loop.
Without a label, `break` always terminates the most immediate enclosing loop.
Q1708easy
What is the recommended way to ensure a `BufferedReader` or `BufferedWriter` is closed after use, especially in the presence of exceptions?
✅ Correct Answer: C) Using a `try-with-resources` statement.
The `try-with-resources` statement automatically ensures that resources like `BufferedReader` and `BufferedWriter` are closed when the try block is exited, regardless of how the block is exited.
Q1709mediumcode output
What does this code print to the console?
java
public class StringBuilderTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Fast Code");
sb.replace(0, 4, "Quick");
System.out.println(sb);
}
}
✅ Correct Answer: A) Quick Code
The replace(start, end, String) method replaces the substring from the start index (inclusive) to the end index (exclusive) with the specified string. 'Fast' (indices 0-3) is replaced by 'Quick'.
Q1710easycode output
What is the output of this Java code snippet?
java
public class LoopTest {
public static void main(String[] args) {
int i = 0;
do {
System.out.print(i);
i++;
} while (i < 0);
}
}
✅ Correct Answer: A) 0
The do-while loop executes its body at least once. It prints '0', then increments 'i' to 1. The condition 'i < 0' (1 < 0) is then false, terminating the loop.
Q1711hard
In Java, due to type erasure, what is the consequence of attempting to cast a `List<Object>` to a `List<String>` at runtime, assuming it's done via a raw type or an `Object` reference to circumvent compile-time checks?
✅ Correct Answer: B) The cast succeeds, but a warning is issued at compile time, and `ClassCastException` might occur later if elements are retrieved and cast.
Due to type erasure, `List<Object>` and `List<String>` become raw `List` at runtime. The cast itself will succeed at runtime (possibly with a compile-time unchecked warning). However, a `ClassCastException` will occur later if an element that is not actually a `String` is retrieved from the list and an implicit or explicit cast to `String` fails.
Q1712easycode output
What does this code print?
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<>();
ts.add("hello");
ts.add(null);
System.out.println(ts);
}
}
✅ Correct Answer: C) java.lang.NullPointerException
TreeSet uses natural ordering to sort elements. When a non-null element is already present, adding a null element will cause a NullPointerException because the set attempts to compare null with existing elements.
Q1713hardcode output
What is the output of this code?
java
public class UncaughtExceptionHandlerTest {
public static void main(String[] args) throws InterruptedException {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
System.out.println("Handled by default handler for " + t.getName() + ": " + e.getMessage());
});
Thread buggyThread = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " starting.");
throw new NullPointerException("Intentional NPE");
}, "BuggyWorker");
buggyThread.start();
buggyThread.join();
System.out.println("Main thread finished.");
}
}
✅ Correct Answer: A) BuggyWorker starting.
Handled by default handler for BuggyWorker: Intentional NPE
Main thread finished.
When an uncaught exception occurs in a thread, if a `DefaultUncaughtExceptionHandler` is set, it will be invoked. The handler prints the message, and then the main thread continues its execution.
Q1714mediumcode output
What is the output of this code?
java
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 92);
int totalScore = 0;
for (int score : scores.values()) {
totalScore += score;
}
System.out.println(totalScore);
}
}
✅ Correct Answer: A) 267
The code iterates over the collection of values returned by `scores.values()` and sums them up. 90 + 85 + 92 equals 267.
Q1715easy
Which method is used to get the number of elements currently stored in an `ArrayList`?
✅ Correct Answer: C) `size()`
The `size()` method returns the number of elements in the `ArrayList`, which is the logical size of the list, not its internal capacity.
Q1716hard
Which of the following statements about multi-dimensional arrays in Java is true?
✅ Correct Answer: D) An array declared as `new int[0][0]` is valid and represents an empty array of arrays.
It is legal to declare arrays with a zero length for any dimension. `new int[0][0]` is valid, representing an empty array. `new int[0][5]` has zero outer elements, thus no inner arrays to store anything. Iterating an inner loop of `new int[5][0]` won't cause an error as the inner loop condition `j < arr[i].length` would be `j < 0`, causing it not to execute.
Q1717hardcode output
What is the output of this code?
java
public class SwitchTest {
public static void main(String[] args) {
int x = 1;
String msg = "Initial";
switch (x) {
case 1:
String temp = "Case 1";
msg = temp;
break;
case 2:
String temp = "Case 2"; // This line is problematic
msg = temp;
break;
default:
msg = "Default";
}
System.out.println(msg);
}
}
✅ Correct Answer: D) Compilation error: Variable 'temp' is already defined in the scope
In a traditional `switch` statement without explicit curly braces `{}` around each `case` block, a variable declared in one `case` is scoped to the entire `switch` block. Therefore, `temp` declared in `case 1` is still in scope when `case 2` attempts to declare a variable with the same name, leading to a compile-time error.
Q1718hardcode output
What is the output of this code?
java
public class SideEffectWhile {
public static void main(String[] args) {
int i = 0;
int sum = 0;
while (i++ < 5) {
sum += i;
}
System.out.println(sum + ", " + i);
}
}
✅ Correct Answer: A) 15, 6
The post-increment operator `i++` means `i` is incremented after its original value is used in the `while` condition. So, `sum` adds `i` values from 1 to 5, and `i` becomes 6 after the last check that evaluates to false.
Q1719easy
Which of the following is a key benefit of using encapsulation in Java?
✅ Correct Answer: B) Improves code maintainability and flexibility.
Encapsulation hides implementation details, making it easier to change internal workings without affecting external code, thus improving maintainability and flexibility.
Q1720hardcode output
What is the output of this code?
java
import java.io.IOException;
class Parent {
public void method() throws IOException {
System.out.println("Parent method");
}
}
class Child extends Parent {
@Override
public void method() throws java.io.FileNotFoundException {
System.out.println("Child method");
}
}
class GrandChild extends Child {
@Override
public void method() {
System.out.println("GrandChild method");
}
}
public class Test {
public static void main(String[] args) {
Parent p = new GrandChild();
try {
p.method();
} catch (IOException e) {
System.out.println("Caught IOException");
}
}
}
✅ Correct Answer: A) GrandChild method
Due to dynamic method dispatch, the `method()` implemented in `GrandChild` is called. Overriding methods can declare a subtype of the original exception or no exceptions at all. The `try-catch` block for `IOException` is still required by the compiler because `Parent.method()` declares it, even though the actual runtime method (`GrandChild.method()`) doesn't throw it.