import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
int limit = 20;
Predicate<Integer> isUnderLimit = num -> num < limit;
System.out.println(isUnderLimit.test(15));
}
}
✅ Correct Answer: A) true
The lambda expression for `isUnderLimit` captures the effectively final variable `limit` from its enclosing scope. Since 15 is less than 20, `isUnderLimit.test(15)` returns true.
Q962easy
What is the initial state of a thread immediately after it has been created using `new Thread()` but before its `start()` method is invoked?
✅ Correct Answer: A) NEW
A thread is in the NEW state when it has been created but has not yet started execution. The `start()` method transitions it to RUNNABLE.
Q963hard
Consider a class `MyObject` that overrides `equals()` to compare objects based on their `id` field but does *not* override `hashCode()`. If two `MyObject` instances, `obj1` and `obj2`, have the same `id` (meaning `obj1.equals(obj2)` is true) but are distinct objects, what would be the most common outcome after adding both `obj1` and `obj2` to a `HashSet`?
✅ Correct Answer: A) The `HashSet` will contain both `obj1` and `obj2` because their default `hashCode()` values (based on memory address) will differ.
If `hashCode()` is not overridden, the default `Object.hashCode()` (usually memory-address based) will be used. Since `obj1` and `obj2` are distinct objects, they'll likely have different hash codes, causing them to be placed in different buckets, even though `equals()` considers them the same.
Q964medium
What is the underlying data structure primarily used by `HashSet` in Java?
✅ Correct Answer: C) A HashMap
`HashSet` internally uses a `HashMap` where elements are stored as keys, and a dummy `Object` (e.g., `PRESENT` constant) is stored as the value associated with each key.
Q965mediumcode error
What will be the compilation error in this code?
java
class Parent {
public void action() {
System.out.println("Parent's action.");
}
}
class Child extends Parent {
@Override
private void action() {
System.out.println("Child's action.");
}
}
✅ Correct Answer: A) Error: action() in Child cannot override action() in Parent; attempting to assign weaker access privileges; was public
An overridden method cannot have a more restrictive access modifier than the superclass method. Changing 'public' to 'private' is a reduction in visibility and will result in a compilation error.
Q966medium
Is `FileWriter` inherently buffered for performance optimization?
✅ Correct Answer: B) No, it writes characters directly to the underlying file system without internal buffering.
`FileWriter` itself does not provide buffering. For improved performance, especially with frequent small writes, it should be wrapped in a `BufferedWriter`.
Q967mediumcode error
What is the output of this Java code?
java
public class ExceptionFlow9 {
public static void main(String[] args) {
testMethod();
}
public static void testMethod() {
try {
System.out.println("In try");
throw new IllegalArgumentException("From try");
} catch (IllegalArgumentException e) {
System.out.println("In catch: " + e.getMessage());
} finally {
System.out.println("In finally");
throw new IllegalStateException("From finally");
}
}
}
✅ Correct Answer: A) In try
In catch: From try
In finally
Exception in thread "main" java.lang.IllegalStateException: From finally
An exception thrown in the 'finally' block will override and propagate instead of any exception that was previously thrown from the 'try' or 'catch' blocks.
Q968hardcode error
What type of error will occur when compiling this Java code?
java
public class StaticForwardRef {
static int sum = num1 + num2; // Error line
static int num1 = 5;
static int num2 = 10;
public static void main(String[] args) {
System.out.println(sum);
}
}
✅ Correct Answer: A) Error: illegal forward reference.
In Java, a static field cannot refer to other static fields declared textually after it during its initialization. Here, `sum` attempts to use `num1` and `num2` before they are declared and initialized, resulting in an illegal forward reference.
Q969easycode error
What type of error will occur when running this Java code?
java
public class Broadcaster {
private final Object eventLock = new Object();
public void broadcastEvent() {
// Missing synchronized(eventLock)
eventLock.notifyAll();
System.out.println("All notified!");
}
public static void main(String[] args) {
Broadcaster b = new Broadcaster();
b.broadcastEvent();
}
}
✅ Correct Answer: C) java.lang.IllegalMonitorStateException
`notifyAll()` must be called from within a synchronized block or method that holds the monitor lock on the object it is called on. Failing to do so results in an `IllegalMonitorStateException` at runtime.
Q970easycode output
What does this Java code print?
java
public class LoopTest {
public static void main(String[] args) {
int num = 0;
String s = "";
do {
s += num;
num += 2;
} while (num < 6);
System.out.print(s);
}
}
✅ Correct Answer: A) 024
The loop runs for 'num' values 0, 2, and 4. When 'num' becomes 6 (after appending 4 and adding 2), the condition 'num < 6' (6 < 6) becomes false, terminating the loop. The string '024' is printed.
Q971medium
Which type of object can `BufferedReader` directly wrap in its constructor to provide buffering capabilities?
✅ Correct Answer: C) Any subclass of `java.io.Reader`
`BufferedReader` is a character-input stream that decorates another `Reader`. Its constructor takes an existing `Reader` (e.g., `FileReader`, `InputStreamReader`) to buffer its input.
Q972mediumcode output
What is the output of this code?
java
import java.util.ArrayDeque;
import java.util.Queue;
public class ArrayDequeAsQueue {
public static void main(String[] args) {
Queue<Character> queue = new ArrayDeque<>();
queue.add('X');
queue.offer('Y');
queue.add('Z');
System.out.print(queue.size());
System.out.print(queue.poll());
System.out.print(queue.peek());
}
}
✅ Correct Answer: A) 3XY
Elements 'X', 'Y', 'Z' are added, so `size()` is 3. `poll()` removes and returns 'X'. `peek()` then returns the new head 'Y' without removing it, so the output is '3XY'.
Q973hardcode output
What is the output of this code?
java
public class DataTypeChallenge {
public static void main(String[] args) {
byte b1 = (byte) 200;
byte b2 = 100;
int sum = b1 + b2;
byte b3 = (byte) (b1 + b2);
System.out.println(sum + ", " + b3);
}
}
✅ Correct Answer: B) 44, 44
When `200` (an `int`) is cast to `byte`, it overflows and becomes `-56` (200 - 256). In the expression `b1 + b2`, both `b1` and `b2` are promoted to `int` before addition, so `-56 + 100` results in `44`. This `int` `44` is assigned to `sum`. When `(byte)(b1 + b2)` is performed, the `int` result `44` is cast back to `byte`, which remains `44`.
Q974hard
You have a `List<List<Integer>> listOfLists;`. Which approach is the most efficient and idiomatic way to create a single `Iterator<Integer>` that provides sequential access to all integers from all inner lists, effectively "flattening" the structure, without explicitly copying all elements into a new single list beforehand?
✅ Correct Answer: D) Convert the `listOfLists` to a `Stream<List<Integer>>`, then use `flatMap` to convert it to `Stream<Integer>`, and finally call `iterator()` on the resulting stream.
While custom iteration is possible, `Stream.flatMap` provides the most concise, efficient, and idiomatic way in modern Java to transform a stream of collections into a single stream of elements from those collections. Calling `iterator()` on the resulting `Stream<Integer>` yields the desired single iterator without intermediate collection creation.
Q975hard
What is the return value of `new String("abc").indexOf("")`?
✅ Correct Answer: B) 0
The `indexOf()` method specifies that an empty string is considered to occur at the beginning of any string (index 0). It also occurs after every character, but the first occurrence is at index 0.
Q976easycode output
What is the output of this Java code?
java
import java.io.FileNotFoundException;
public class MyClass {
public static void processFile() throws FileNotFoundException {
System.out.println("Processing...");
if (true) {
throw new FileNotFoundException("File not found exception");
}
}
public static void main(String[] args) {
try {
processFile();
} catch (Exception e) { // Catching a broader exception type
System.out.println("Caught exception: " + e.getClass().getName());
}
}
}
✅ Correct Answer: A) Processing...
Caught exception: java.io.FileNotFoundException
The `processFile` method prints 'Processing...' and then unconditionally throws a `FileNotFoundException`. The `main` method's `catch (Exception e)` block is broad enough to catch `FileNotFoundException` (which extends `IOException`, which extends `Exception`), and it prints the full class name of the caught exception.
Q977medium
Which `StringBuffer` method allows reversing the order of the characters in the sequence?
✅ Correct Answer: A) `reverse()`
The `reverse()` method is a convenient utility in `StringBuffer` that modifies the sequence of characters by reversing their order within the buffer itself.
Q978medium
What is the primary purpose of the `Runnable` interface in Java?
✅ Correct Answer: C) To encapsulate a task that can be executed by a thread.
The `Runnable` interface is designed to encapsulate a unit of work that can be executed independently, typically by a `Thread` or an `ExecutorService`.
✅ Correct Answer: A) The assignment `MyTransformer<String, Integer> incompatible = identity;` is invalid because of incompatible generic types.
The `identity` lambda is of type `MyTransformer<String, String>`, while `incompatible` is declared as `MyTransformer<String, Integer>`. Attempting to assign `identity` to `incompatible` results in a compile-time type mismatch due to incompatible generic type arguments.
Q980easycode error
What happens when you compile the following Java code?
java
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
if (i == 2) {
continue;
}
} while (false); // Loop only runs once
System.out.println("End of program");
}
}
✅ Correct Answer: A) The code compiles and prints "0" then "End of program"
The `continue` statement is correctly placed within a loop. Although the loop condition `while(false)` means it only runs once, there's no syntax error. The output will be '0' and then 'End of program'.