Which line will cause a compilation error in the following Java code snippet related to 'effectively final' variables?
java
import java.util.function.Consumer;
public class ClosureExample {
public static void main(String[] args) {
String status = "Pending";
Consumer<String> printer = s -> {
System.out.println(s + ": " + status);
};
status = "Completed"; // This line causes the error
printer.accept("Task");
}
}
✅ Correct Answer: A) Local variable status defined in an enclosing scope must be final or effectively final
For a local variable to be captured by a lambda expression (or anonymous inner class), it must be 'final' or 'effectively final'. Changing 'status' after it's been captured by the lambda makes it not effectively final, leading to a compilation error.
Q1082hardcode error
What is the compilation error, if any, for the provided Java code snippet?
java
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
class Overloader {
public void schedule(Callable c) {}
public void schedule(Future f) {}
public static void main(String[] args) {
Overloader o = new Overloader();
o.schedule(null); // Line X
}
}
✅ Correct Answer: B) error: reference to schedule is ambiguous
Both `Callable` and `Future` are interfaces in `java.util.concurrent`, and neither is a sub-interface or super-interface of the other. As such, when `null` is passed, both `schedule(Callable c)` and `schedule(Future f)` are equally applicable, leading to an ambiguous method call.
Q1083hard
What is the primary difference between `Thread.currentThread().isInterrupted()` and `Thread.interrupted()`?
✅ Correct Answer: C) `isInterrupted()` only checks the interrupted status flag of the current thread, while `interrupted()` checks and clears it.
`Thread.currentThread().isInterrupted()` is an instance method that returns the interrupted status without changing it. `Thread.interrupted()` is a static method that returns the interrupted status of the current thread and then clears the flag.
Q1084hardcode error
Which compile-time error will prevent this Java code from running?
java
public class ShortRangeTest {
public static void main(String[] args) {
short s = 32768; // 32768 is outside the range of short
System.out.println(s);
}
}
✅ Correct Answer: A) Error: incompatible types: possible lossy conversion from int to short
Integer literals are treated as 'int' by default. The value 32768 is within the 'int' range but exceeds the maximum value for a 'short' (32767). Attempting to assign this 'int' literal to a 'short' variable without an explicit cast is considered a possible lossy conversion by the compiler.
Q1085easycode error
What kind of error will occur when compiling this Java code?
java
class Parent {
private int value = 10;
}
class Child extends Parent {
public void display() {
System.out.println(value);
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.display();
}
}
✅ Correct Answer: A) Compile-time error: cannot find symbol 'value'
Private members of a superclass are not directly accessible by subclasses. Attempting to access 'value' directly from the Child class will result in a compile-time error.
Q1086hardcode error
What is the compilation error in the following Java code regarding static final variable initialization?
java
public class StaticBlankFinal {
public static final int MY_STATIC_FINAL;
// Attempting to initialize a static final field in an instance constructor
public StaticBlankFinal() {
MY_STATIC_FINAL = 50;
}
public static void main(String[] args) {
System.out.println("Attempting to access: " + MY_STATIC_FINAL);
}
}
✅ Correct Answer: A) Error: cannot assign a value to final variable 'MY_STATIC_FINAL'.
A static final variable must be initialized either at its declaration or within a static initializer block. Attempting to initialize it within an instance constructor (which is a non-static context) results in a compile-time error because it's a final variable and can only be assigned once in a static context.
Q1087mediumcode error
What is the compile-time error in this Java code?
java
import java.util.function.Predicate;
public class LambdaError {
private int threshold = 10;
public void testPredicate() {
Predicate<Integer> isAboveThreshold = num -> {
threshold++; // Attempt to modify instance field
return num > threshold;
};
System.out.println(isAboveThreshold.test(15));
}
public static void main(String[] args) {
new LambdaError().testPredicate();
}
}
✅ Correct Answer: A) There is no compile-time error; instance variables can be modified within lambdas.
Unlike local variables, instance (non-static) variables captured by a lambda do not need to be final or effectively final and can be modified from within the lambda. Therefore, this code will compile and run without error related to variable capture.
Q1088medium
For reference type casting in Java, when is the *safeness* of a cast primarily verified?
✅ Correct Answer: C) Partially at compile-time and partially at runtime.
The compiler checks if a cast is *plausible* (i.e., if the types are related in a way that the cast *might* be valid). The actual runtime check, verifying if the object's true type is compatible with the target type, occurs at runtime.
Q1089hardcode output
What is the output of this code?
java
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<Float> set = new HashSet<>();
float nan1 = Float.NaN;
float nan2 = Float.NaN;
float inf1 = Float.POSITIVE_INFINITY;
float inf2 = Float.POSITIVE_INFINITY;
set.add(nan1);
set.add(nan2);
set.add(inf1);
set.add(inf2);
System.out.println(set.size());
}
}
✅ Correct Answer: B) 2
`Float.equals()` handles `NaN` values correctly: `Float.NaN.equals(Float.NaN)` returns `true`. Therefore, adding `nan1` and `nan2` (both `Float.NaN`) results in only one `NaN` value in the set. Similarly, `Float.POSITIVE_INFINITY` is also treated as equal by `Float.equals()`. So, one `NaN` and one `POSITIVE_INFINITY` are stored, resulting in a size of 2.
Q1090hard
Given `List<String> elements = Arrays.asList("one", null, "three");`, what is the resulting string from `String.join("-", elements);`?
✅ Correct Answer: A) `"one-null-three"`
`String.join()` explicitly handles `null` elements in the iterable by converting them to the string literal "null". It does not skip them or throw an exception for individual nulls within the collection.
Q1091hard
Consider a superclass method `public void performAction() throws IOException`. Which of the following declarations for an overriding method in a subclass would result in a compile-time error?
✅ Correct Answer: B) public void performAction() throws Exception
An overriding method cannot declare checked exceptions that are broader than those declared by the superclass method. `Exception` is a superclass of `IOException`, making it a broader checked exception. Options A, C, and D are valid as they either narrow the checked exception, remove it, or add an unchecked exception (which is always allowed).
Q1092medium
For efficient reading of large text files using `FileReader`, it is most common and recommended to wrap it in which other class?
✅ Correct Answer: C) BufferedReader
`BufferedReader` adds buffering capabilities to `FileReader`, which can significantly improve performance by reading larger blocks of data from the disk at once, rather than one character at a time.
Q1093easy
When you see `void myMethod() throws MyException {}`, what type of entity is `MyException`?
✅ Correct Answer: C) An exception class name.
The `throws` keyword is followed by one or more class names of exception types that the method might throw, not instances or variables.
Q1094mediumcode error
Which type of error will occur when compiling and running the following Java code?
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello");
writer.close();
}
}
✅ Correct Answer: B) A compile-time error because IOException is not handled.
Both the `FileWriter` constructor and `BufferedWriter` methods like `write()` and `close()` can throw `IOException`, which is a checked exception. The `main` method does not declare `throws IOException` and there's no `try-catch` block, leading to a compile-time error.
Q1095easycode error
What kind of error will occur when this Java code is executed?
java
public class Test {
public static void main(String[] args) {
String result = new StringBuilder("Start").append("End");
System.out.println(result);
}
}
✅ Correct Answer: C) Compilation Error: Incompatible types: StringBuilder cannot be converted to String
The `append()` method of `StringBuilder` returns a `StringBuilder` object. You cannot directly assign a `StringBuilder` to a `String` reference; you must explicitly call `toString()`.
Q1096hardcode error
What kind of runtime error or unexpected behavior will occur when running this Java code, primarily related to thread lifecycle?
java
public class DeadlockDemo {
private static Object lockA = new Object();
private static Object lockB = new Object();
public static void main(String[] args) {
new Thread(() -> {
synchronized (lockA) {
System.out.println("Thread-1 acquired lockA");
try { Thread.sleep(100); } catch (InterruptedException e) {} // Give Thread-2 a chance
synchronized (lockB) {
System.out.println("Thread-1 acquired lockB");
}
}
}).start();
new Thread(() -> {
synchronized (lockB) {
System.out.println("Thread-2 acquired lockB");
try { Thread.sleep(100); } catch (InterruptedException e) {} // Give Thread-1 a chance
synchronized (lockA) {
System.out.println("Thread-2 acquired lockA");
}
}
}).start();
}
}
✅ Correct Answer: C) The program will experience a deadlock and hang indefinitely.
This code demonstrates a classic deadlock scenario. Thread-1 acquires `lockA` and then tries to acquire `lockB`. Simultaneously, Thread-2 acquires `lockB` and then tries to acquire `lockA`. Both threads will block indefinitely, waiting for the other to release the lock they need, leading to a program hang.
Q1097mediumcode error
What is the error in this Java code snippet?
java
public class MyClass {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Code");
char c = sb.charAt(4);
System.out.println(c);
}
}
✅ Correct Answer: D) A runtime error: StringIndexOutOfBoundsException.
The StringBuilder 'sb' has a length of 4, so valid indices are 0 to 3. Accessing a character at index 4 (which is out of bounds) will cause a StringIndexOutOfBoundsException at runtime.
Q1098medium
Which of the following is an example of a stateful intermediate operation in the Java Stream API?
✅ Correct Answer: C) distinct()
Stateful operations like `distinct()` or `sorted()` require knowing the state of previously processed elements (or all elements) to produce a result, making them potentially more expensive, especially in parallel streams.
Q1099mediumcode error
Which type of error or exception will be produced by the following Java code at runtime, if the FileWriter constructor fails to initialize 'writer' due to an IOException?
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("log.txt"));
writer.write("Log entry 1");
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
// Intentionally no writer.close() here
}
writer.write("Log entry 2"); // This line will be reached
}
}
✅ Correct Answer: C) A NullPointerException when calling `writer.write("Log entry 2")`.
If the `FileWriter` constructor fails due to an `IOException`, the `writer` variable will remain `null`. The subsequent call to `writer.write("Log entry 2")` outside the `try-catch` block will then attempt to invoke a method on a `null` object, resulting in a `NullPointerException` at runtime.
Q1100medium
Which set of rules is crucial for creating a custom immutable class in Java?
✅ Correct Answer: C) Declare all fields as private and `final`, do not provide setter methods, and ensure no methods modify the object's state after construction.
To make a class immutable, its fields should be private and final, no methods should allow state modification (e.g., setters), and defensive copies should be made for any mutable objects passed in or returned.