In which scenario would an anonymous inner class typically be preferred over a lambda expression for implementing an abstract type in Java?
✅ Correct Answer: B) When the abstract type defines multiple abstract methods.
Lambda expressions are designed for functional interfaces (interfaces with a single abstract method). An anonymous inner class would be necessary to implement an abstract type that has multiple abstract methods, or to implement a non-functional abstract class.
Q2762easycode error
What compile-time error will this code produce?
java
class MyRunnable implements Runnable {
public int run() {
System.out.println("Running task");
return 0;
}
}
public class Main {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
new Thread(r).start();
}
}
✅ Correct Answer: A) Error: MyRunnable is not abstract and does not override abstract method run() in Runnable
The `run()` method defined in the `Runnable` interface has a `void` return type. Implementing it with an `int` return type does not correctly override the interface method, leading to a compile error about the missing implementation.
Q2763hardcode error
What error will be thrown by `thread1` when `thread2` interrupts it while it's attempting to acquire the lock?
java
import java.util.concurrent.locks.ReentrantLock;
public class InterruptibleLock {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
try {
lock.lockInterruptibly(); // Attempts to acquire lock, but can be interrupted
System.out.println("Thread 1 acquired lock.");
} catch (InterruptedException e) {
System.out.println("Thread 1 was interrupted while acquiring lock.");
// No re-interrupt, just prints message
}
});
lock.lock(); // Main thread acquires the lock first
thread1.start();
Thread.sleep(100); // Give thread1 time to try and acquire lock
thread1.interrupt(); // Interrupt thread1
lock.unlock(); // Main thread releases the lock
}
}
✅ Correct Answer: C) No error will be thrown, "Thread 1 was interrupted..." will be printed.
When `thread1` is interrupted while waiting to acquire the lock via `lockInterruptibly()`, it correctly throws an `InterruptedException`. The `catch` block then handles this exception by printing a message, but it doesn't re-throw the exception or cause the program to terminate, so no unhandled error is thrown.
Q2764easycode output
What is the output of this Java code?
java
public class TypeCast {
public static void main(String[] args) {
int x = 10;
x += 5.5;
System.out.println(x);
}
}
✅ Correct Answer: A) 15
Compound assignment operators like `+=` implicitly cast the result of the operation back to the type of the left-hand operand. `x += 5.5` is equivalent to `x = (int)(x + 5.5)`, which evaluates to `x = (int)15.5`, resulting in 15.
Q2765hard
What is the amortized time complexity for adding `N` elements to an `ArrayList` starting from an empty list (`new ArrayList<>()`)?
✅ Correct Answer: B) O(N)
While individual `add()` operations are O(1) most of the time, resizing operations (which involve copying all existing elements to a larger array) occur periodically. These O(N) resizes, distributed over `N` additions, make the amortized time complexity for adding `N` elements O(N).
Q2766easycode output
What does this code print?
java
public class Main {
public static void main(String[] args) {
try {
int x = 5 / 0;
System.out.print("Try ");
} catch (ArithmeticException e) {
System.out.print("Catch ");
} finally {
System.out.print("Finally ");
}
System.out.print("End ");
}
}
✅ Correct Answer: A) Catch Finally End
An ArithmeticException is thrown in the 'try' block and caught by the 'catch' block. The 'finally' block always executes. After the try-catch-finally construct completes, the program continues with the 'End' statement.
Q2767hard
In Java, when overriding an instance method, which statement correctly describes the behavior regarding return types and polymorphism?
✅ Correct Answer: B) The overriding method can return a subtype of the return type declared in the overridden method (covariant return type).
Java supports covariant return types since Java 5. An overriding method can return a subtype of the return type of the method it overrides, maintaining the polymorphic contract while allowing more specific types.
Q2768hardcode error
What is the error encountered when running this Java code?
java
public class LoopBoundsError {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie"};
for (int i = 0; i <= names.length; i++) {
System.out.println(names[i]);
}
}
}
✅ Correct Answer: A) java.lang.ArrayIndexOutOfBoundsException
The array `names` has a length of 3, meaning valid indices are 0, 1, and 2. The loop condition `i <= names.length` allows `i` to go up to 3. When `i` is 3, `names[3]` is accessed, which is outside the array's bounds, resulting in an `ArrayIndexOutOfBoundsException`.
Q2769mediumcode error
What error will occur when compiling and running this Java code?
java
import java.util.HashSet;
import java.util.Set;
public class HashSetError1 {
public static void main(String[] args) {
Set<String> names = new HashSet<>();
names.add("Alice");
names.add("Bob");
String first = names.get(0); // ERROR line
System.out.println(first);
}
}
✅ Correct Answer: A) Compilation Error: Cannot find symbol method get(int) for type java.util.Set<java.lang.String>.
The `java.util.Set` interface (and `HashSet` implementation) does not provide a `get(int index)` method, as sets are unordered collections without index-based access. Attempting to call this method results in a compilation error.
Q2770mediumcode output
What does this code print?
java
public class Main {
private static int counter = 0;
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 10000; i++) {
counter++;
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter);
}
}
✅ Correct Answer: A) A value less than 20000 (e.g., between 10001 and 19999)
The `counter++` operation is not atomic. When multiple threads access and modify it concurrently without synchronization, race conditions occur where increments can be lost. This results in a final value less than the expected 20000.
Q2771hardcode output
What is the output of this Java code, demonstrating strong immutability and encapsulation with `Collections.unmodifiableList()`?
java
import java.util.ArrayList; import java.util.Collections; import java.util.List;
class ImmutableSettings {
private final List<String> options;
public ImmutableSettings(List<String> inputOptions) {
this.options = Collections.unmodifiableList(new ArrayList<>(inputOptions));
}
public List<String> getOptions() { return options; }
}
public class Main {
public static void main(String[] args) {
ImmutableSettings settings = new ImmutableSettings(new ArrayList<>(List.of("A", "B")));
System.out.println("Initial: " + settings.getOptions());
try {
settings.getOptions().add("C");
} catch (UnsupportedOperationException e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}
}
}
✅ Correct Answer: B) Initial: [A, B]
Caught: UnsupportedOperationException
The constructor first makes a defensive copy of the input list and then wraps it with `Collections.unmodifiableList()`. This returns a view of the list that disallows any structural modifications (like `add`, `remove`). Any attempt to modify this unmodifiable list will result in an `UnsupportedOperationException`, effectively enforcing strong immutability and encapsulation.
Q2772easycode error
What is the output or error of the following Java code?
java
public class ExceptionTest {
public static void main(String[] args) {
try {
Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Caught NFE");
} finally {
throw new RuntimeException("Finally Exception");
}
}
}
✅ Correct Answer: A) Prints "Caught NFE" then "Finally Exception" is thrown and terminates.
The NumberFormatException is caught and "Caught NFE" is printed. The finally block always executes, and in this case, it throws a RuntimeException which then terminates the program.
Q2773easy
Can a `while` loop execute zero times?
✅ Correct Answer: B) Yes, if its condition is initially `false`.
Yes, a `while` loop can execute zero times if its boolean condition is `false` from the very beginning, as it checks the condition before the first iteration.
Q2774mediumcode error
What is the compile-time error in the following Java code?
java
class MyLogger {
private String loggerName;
public MyLogger() {
this.loggerName = "default";
}
public void initialize(String name) {
this(name); // Invalid usage: this() can only be in a constructor
System.out.println("Logger initialized to: " + loggerName);
}
public MyLogger(String name) {
this.loggerName = name;
}
public static void main(String[] args) {
MyLogger log = new MyLogger();
log.initialize("app_log");
}
}
✅ Correct Answer: A) Error: call to this must be first statement in constructor
The special syntax `this(...)` or `super(...)` for constructor invocation can only be used as the very first statement within another constructor of the same class or its superclass, respectively. Attempting to use it in a regular method like `initialize()` leads to a compile-time error.
Q2775medium
When using `System.arraycopy(source, srcPos, destination, destPos, length)` to copy elements from one array to another, what does `srcPos` represent?
✅ Correct Answer: C) The starting index in the source array from which elements will be copied.
`srcPos` in `System.arraycopy` specifies the starting index within the source array from which the copying operation will begin.
Q2776medium
In Java, what is the main function of the `throws` keyword in a method signature?
✅ Correct Answer: C) It declares the types of checked exceptions that a method might propagate to its caller.
The `throws` keyword is used in a method signature to declare the checked exceptions that the method might throw, requiring the caller to handle or re-declare them.
Q2777hardcode error
What is the compile-time error in this Java code?
java
import java.io.IOException;
import java.sql.SQLException;
public class RethrowProblem {
public void processData() {
try {
if (true) throw new IOException("Data read error");
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
throw new SQLException("Database error wrapping IO", e);
}
}
public static void main(String[] args) {
// new RethrowProblem().processData();
}
}
✅ Correct Answer: B) Error: Unhandled exception type SQLException in the `catch` block.
The `processData()` method declares no `throws` clause. Inside the `catch` block, a new `SQLException` (which is a checked exception) is thrown. This `SQLException` is unhandled by the method's signature, leading to a compile-time error.
Q2778easy
Which method is used to retrieve an element at a specific index from an `ArrayList`?
✅ Correct Answer: C) `get(index)`
The `get(index)` method is used to access and return the element located at the specified position within the `ArrayList`.
Q2779medium
Which statement about null keys and null values in a `java.util.TreeMap` is true when using natural ordering for keys?
✅ Correct Answer: B) It does not allow null keys but allows multiple null values.
When using natural ordering, `TreeMap` does not permit null keys because the `compareTo` method would throw a `NullPointerException`. However, it allows multiple null values, as values do not participate in ordering.
Q2780mediumcode error
Identify the compilation error in the following Java code.
java
public class CompoundAssignment {
public static void main(String[] args) {
byte b = 10;
b = b + 5; // Potential issue here
System.out.println(b);
}
}
✅ Correct Answer: A) Incompatible types: possible lossy conversion from int to byte
When performing arithmetic operations with `byte`, `short`, or `char` types, the result is implicitly promoted to an `int`. Assigning an `int` back to a `byte` without an explicit cast causes a 'possible lossy conversion' error.