Under what conditions can a Java lambda expression be serialized?
✅ Correct Answer: B) A lambda expression is serializable if its target functional interface is `Serializable` and all captured variables are also serializable.
For a lambda to be serializable, its target functional interface must extend `java.io.Serializable`, and any values it captures from the enclosing scope (including `this` reference if implicitly captured) must also be serializable.
Q2622hard
When overriding a method, what is the rule regarding checked exceptions thrown by the overridden method in the subclass?
✅ Correct Answer: C) The overridden method can throw no checked exceptions, the same checked exceptions, or a *subtype* of the checked exceptions declared in the superclass method's throws clause.
An overridden method can throw fewer, the same, or a more specific (subtype) checked exception than the superclass method. It cannot throw new, broader, or unrelated checked exceptions.
Q2623hardcode output
What is the output of this code?
java
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("B")) {
list.remove("C");
}
}
System.out.println(list);
}
}
✅ Correct Answer: C) java.util.ConcurrentModificationException
Modifying an ArrayList structurally (e.g., using `list.remove()`) while iterating over it with an `Iterator` (or enhanced for loop) will result in a `ConcurrentModificationException`. The `remove()` operation directly on the list outside the iterator's own `remove()` method causes the issue.
Q2624hardcode output
Given the following Java code, what will be the output?
java
public class DaemonRunnable {
public static void main(String[] args) throws InterruptedException {
Runnable daemonTask = () -> {
while (true) {
try {
System.out.println("Daemon thread is running...");
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Daemon thread interrupted.");
break;
}
}
};
Thread daemonThread = new Thread(daemonTask, "MyDaemonThread");
daemonThread.setDaemon(true);
daemonThread.start();
Thread.sleep(500); // Main thread sleeps for a bit
System.out.println("Main thread finishing.");
}
}
✅ Correct Answer: B) Daemon thread is running...
Daemon thread is running...
Main thread finishing.
Daemon threads do not prevent the JVM from exiting. When the last non-daemon thread (in this case, the main thread) finishes, the JVM terminates, automatically stopping any running daemon threads. The daemon thread will print its message a few times during the main thread's sleep, then abruptly stop when the main thread finishes.
The `Item::new` method reference refers to the `Item(String id)` constructor. The `itemFactory.apply()` method calls this constructor, creating new `Item` objects. The IDs of these two distinct items are then concatenated and printed.
Q2626hardcode output
What is the output of this code, assuming System.getProperty("line.separator") returns "\n"?
java
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
public class Test {
public static void main(String[] args) throws IOException {
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
bw.write("Line 1");
bw.newLine();
bw.write("Line 2\n");
bw.write("Line 3");
bw.close();
System.out.println(sw.toString().replace("\n", "\\n").replace("\r", "\\r"));
}
}
✅ Correct Answer: A) Line 1\\nLine 2\\n\\nLine 3
bw.newLine() inserts the system-specific line separator (assumed \n). bw.write("Line 2\n") inserts an explicit newline. Both result in \n, leading to a double newline after "Line 2".
Q2627easycode output
What does the following Java code print to the console?
java
public class WhileLoopDemo {
public static void main(String[] args) {
boolean running = true;
int counter = 0;
while (running) {
System.out.print(counter);
counter++;
if (counter == 2) {
running = false;
}
}
}
}
✅ Correct Answer: A) 01
The loop prints `counter` (0, then 1). When `counter` becomes 2, the `running` flag is set to `false`, causing the loop to terminate before 2 can be printed. The value 2 itself is never printed.
Q2628hardcode error
What compile-time error will this Java code produce?
java
public class OperatorError1 {
public static void main(String[] args) {
short s = 10;
s = s + 5; // Error line
System.out.println(s);
}
}
✅ Correct Answer: B) incompatible types: possible lossy conversion from int to short
When performing arithmetic operations on `short` or `byte` types, Java implicitly promotes them to `int`. The result of `s + 5` is an `int`, and assigning an `int` to a `short` variable without an explicit cast causes a compile-time error due to possible loss of precision.
Q2629hard
What is the most accurate distinction between data hiding and encapsulation in object-oriented programming?
✅ Correct Answer: B) Data hiding refers to preventing direct access to internal state, while encapsulation is the broader concept of bundling data and methods that operate on that data into a single unit, controlling access and maintaining invariants.
Data hiding is a mechanism (often achieved with access modifiers) to restrict direct access to an object's internal state. Encapsulation is a broader principle that encompasses data hiding, along with bundling data and behavior, and controlling access to ensure the object maintains its internal consistency through its defined interface.
Q2630easycode error
What is the output or error of the following Java code?
java
public class ExceptionTest {
public static void main(String[] args) {
try {
System.out.println("In try block.");
} finally {
throw new IllegalArgumentException("Error in finally");
}
System.out.println("After finally");
}
}
✅ Correct Answer: C) Compilation Error: Unreachable statement 'System.out.println("After finally");'.
The `finally` block always executes. If it throws an exception, control never reaches statements after the `try-finally` block. Therefore, `System.out.println("After finally");` is unreachable code and results in a compilation error.
Q2631easycode output
What does this Java code print?
java
public class ArrayTest {
public static void main(String[] args) {
int[] values = new int[4];
System.out.println(values[0]);
}
}
✅ Correct Answer: A) 0
When an array of primitive types (like `int`) is declared but not explicitly initialized, its elements are automatically set to their default values. For `int`, the default value is 0.
Q2632medium
Which type of variable in Java has no default initial value and must be explicitly assigned a value before use?
✅ Correct Answer: C) Local variables (variables within methods)
Local variables, declared within a method, constructor, or block, do not have default values and must be initialized before they are used. Instance variables, static variables, and array elements are given default values if not explicitly initialized.
Q2633easy
Given `int[][] table = new int[3][5];`, what will `table[0].length` return?
✅ Correct Answer: B) 5
`table[0]` refers to the first row of the 2D array. Applying `.length` to `table[0]` returns the number of columns in that specific row.
Q2634hard
Why is it generally not possible to directly create an array of a generic type `T` using `new T[size]` in Java (e.g., `T[] array = new T[10];`)?
✅ Correct Answer: A) Array types are not subject to type erasure, so the JVM needs to know the exact component type at runtime to enforce type safety, which `T` does not provide.
Arrays are reified in Java, meaning their component type must be known and enforced at runtime. Due to type erasure, the specific type `T` is not available at runtime, preventing the JVM from ensuring type safety if `new T[size]` were allowed.
Q2635hardcode output
What is the output of this code?
java
public class BitwiseWhile {
public static void main(String[] args) {
int n = 10;
int count = 0;
while (n > 0) {
if ((n & 1) == 1) {
count++;
}
n >>= 1;
}
System.out.println(count);
}
}
✅ Correct Answer: A) 2
The code counts the number of set bits (1s) in the binary representation of `n`. For `n = 10` (binary `1010`), there are two set bits.
Q2636easycode output
What is printed by this Java code snippet?
java
public class Main {
public static void main(String[] args) {
int counter = 0;
do {
System.out.print(counter);
counter++;
if (counter == 3) {
break;
}
} while (counter < 5);
}
}
✅ Correct Answer: A) 012
The 'do-while' loop first executes the block, then checks the condition. 'counter' is printed and incremented. When 'counter' becomes 3, the 'break' statement is hit, stopping the loop.
Q2637medium
Why would you choose to declare a class as `abstract` even if it doesn't contain any abstract methods?
✅ Correct Answer: C) To indicate that the class is incomplete and should not be instantiated directly.
Even without abstract methods, declaring a class as abstract explicitly indicates that it is an incomplete blueprint and should not be instantiated on its own. It's often used as a base for a hierarchy where only derived classes make sense to create.
Q2638mediumcode error
What type of error will occur when compiling the following Java code?
java
public class Main {
public static void main(String[] args) {
char c = "A";
System.out.println(c);
}
}
✅ Correct Answer: A) Compile-time error
A `char` literal must be enclosed in single quotes (e.g., `'A'`). Assigning a `String` literal (enclosed in double quotes) to a `char` variable causes a compile-time type mismatch error.
Q2639easycode error
What is the error in this Java code?
java
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<>();
myMap.put("greeting", "Hello");
Integer value = myMap.get("greeting");
System.out.println(value);
}
}
✅ Correct Answer: C) A compile-time error because a String cannot be assigned to an Integer variable without explicit casting.
The 'get' method returns a String, but the code attempts to assign it to an Integer variable, which is a type mismatch causing a compile-time error.
Q2640easycode output
What is the output of this code snippet?
java
public class MyClass {
public static void main(String[] args) {
byte b = 1;
String text = "";
switch (b) {
case 0: text = "Zero"; break;
case 1: text = "One"; break;
case 2: text = "Two"; break;
default: text = "Other";
}
System.out.print(text);
}
}
✅ Correct Answer: B) One
The 'switch' statement works with 'byte' types. The value of 'b' is 1, which matches 'case 1'. The 'text' variable is set to 'One', and then printed.