import java.io.FileReader;
import java.io.IOException;
public class FileReaderTest {
public static void main(String[] args) {
// Assume test.txt exists and contains a single character 'X'
try (FileReader reader = new FileReader("test.txt")) {
reader.read(); // Reads 'X'
int charCode = reader.read(); // Tries to read again
System.out.print(charCode);
} catch (IOException e) {
System.out.print("Error");
}
}
}
✅ Correct Answer: A) -1
After reading the last character from the file, subsequent calls to `read()` will return -1, indicating the end of the stream.
Q2082hardcode error
What is the output of this code?
java
import java.io.File;
import java.io.IOException;
public class ListFilesOnFile {
public static void main(String[] args) {
File regularFile = new File("my_test_file.txt");
try {
regularFile.createNewFile(); // Create it as a file
File[] files = regularFile.listFiles();
if (files == null) {
System.out.println("listFiles returned null.");
} else {
System.out.println("Number of files: " + files.length);
}
} catch (IOException e) {
System.out.println("Error: " + e.getClass().getSimpleName());
} finally {
regularFile.delete();
}
}
}
✅ Correct Answer: B) listFiles returned null.
`listFiles()` returns `null` if the `File` object does not denote a directory or if an I/O error occurs. In this case, it's a regular file.
Q2083easy
Which type of expression must the condition inside the parentheses of a `while` loop be?
✅ Correct Answer: C) A boolean expression.
The condition of a `while` loop must evaluate to a boolean value (`true` or `false`) to determine whether to continue iterating.
Q2084hardcode error
What error will occur when the `Worker` thread attempts to call `wait()`?
java
class SharedResource {
public void doWork() {
// This thread does not own the monitor for 'this'
try {
this.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread worker = new Thread(resource::doWork);
worker.start();
}
}
✅ Correct Answer: C) java.lang.IllegalMonitorStateException
Calling `wait()`, `notify()`, or `notifyAll()` on an object requires the current thread to own that object's monitor. Since `doWork()` is not synchronized on `this`, an `IllegalMonitorStateException` is thrown.
Q2085medium
What is the default initial value for elements of a newly created `double[]` array in Java?
✅ Correct Answer: C) 0.0
For numeric primitive types like `double`, the default value for array elements is 0, which is `0.0` for doubles. `null` is for object references, and `undefined` is not a Java concept.
Q2086hard
Consider the behavior of the `this` keyword within a lambda expression versus an anonymous inner class. Which statement is correct?
✅ Correct Answer: B) A lambda expression captures `this` lexically, referring to the `this` of the enclosing instance, while an anonymous inner class defines its own `this`.
Lambda expressions do not create a new scope for 'this'; it refers to the 'this' of the enclosing class. Anonymous inner classes, however, create their own scope and their 'this' refers to the instance of the anonymous class itself.
Q2087hard
Consider an interface `I` with a `default` method `void perform()`. A class `C` implements `I` and also extends a class `A` which has a concrete method `void perform()`. If `C` does not explicitly override `perform()`, which `perform()` method is invoked when calling `new C().perform()`?
✅ Correct Answer: B) The method from class `A`.
When a class inherits a method with the same signature from both a superclass and a default method from an interface, the class's method (or its superclass's method) always takes precedence. This rule resolves potential ambiguity in Java 8+.
Q2088mediumcode output
What is the output of this code?
java
class MyJob implements Runnable {
private String message;
public MyJob(String message) {
this.message = message;
}
@Override
public void run() {
System.out.println("Running: " + message);
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyJob("Job A"));
Thread t2 = new Thread(new MyJob("Job B"));
t1.start();
t2.start();
System.out.println("Main thread done scheduling.");
}
}
✅ Correct Answer: D) The order of "Running: Job A", "Running: Job B" and "Main thread done scheduling." is not guaranteed, any valid interleave is possible.
When multiple threads are started, their execution is concurrent and managed by the JVM's scheduler. The exact order in which their `run()` methods execute and interact with the main thread is non-deterministic. Thus, any valid interleaving of the print statements is possible.
Q2089easy
Can the return type of an overriding method be different from the overridden method in the superclass?
✅ Correct Answer: C) Yes, if the new return type is a subtype (covariant return type) of the original return type.
Since Java 5, an overriding method can have a covariant return type, meaning its return type can be a subtype of the return type declared in the superclass method.
Q2090mediumcode error
What error occurs when compiling this Java code?
java
public class LoopTest {
public static void main(String[] args) {
final int value = 0;
do {
System.out.println("Value: " + value);
value++;
} while (false);
}
}
✅ Correct Answer: C) error: cannot assign a value to final variable value
The 'value' variable is declared as 'final', meaning its value cannot be changed after initialization. Attempting to increment it ('value++') leads to a compile-time error.
Q2091easy
Which of the following statements about `Serializable` interface is true?
✅ Correct Answer: B) It is a marker interface and contains no methods.
`Serializable` is a marker interface, meaning it has no methods to implement. Its sole purpose is to mark a class as capable of being serialized.
Q2092hardcode error
What is the error encountered when running this Java code?
The 'read(char[] cbuf)' method expects a non-null character array. Passing 'null' as the buffer will result in a NullPointerException.
Q2093easycode output
What is the output of this code?
java
abstract class Vehicle {
abstract String getType();
}
class Car extends Vehicle {
@Override
String getType() {
return "Sedan";
}
}
public class Test {
public static void main(String[] args) {
Vehicle v = new Car();
System.out.println(v.getType());
}
}
✅ Correct Answer: B) Sedan
Due to polymorphism, although the reference type is `Vehicle` (abstract), the actual object is a `Car`. When `getType()` is called, the `Car` class's overridden implementation is invoked.
✅ Correct Answer: A) apple-banana-cherry Xpple,bXnXnX,cherry
The replace(CharSequence target, CharSequence replacement) method replaces all occurrences of the target literal string. The replaceAll(String regex, String replacement) method replaces all occurrences that match the given regular expression.
Q2095easycode output
What will this Java code print?
java
public class MyClass {
public static void main(String[] args) {
String item = "Pen";
switch (item) {
case "Book": System.out.print("Reading");
case "Pen": System.out.print("Writing");
case "Pencil": System.out.print("Drawing"); break;
default: System.out.print("Other activity");
}
}
}
✅ Correct Answer: B) WritingDrawing
The 'item' is 'Pen', so execution starts at 'case "Pen"'. Since there is no 'break' after 'Writing', it falls through to 'case "Pencil"', printing 'Drawing', and then the 'break' stops further execution.
Q2096easycode error
What kind of error will this Java code produce?
java
public class LoopError9 {
public static void main(String[] args) {
int x = 5;
while (x) { // Error: int cannot be converted to boolean
System.out.println("Value: " + x);
x--;
}
}
}
✅ Correct Answer: A) Compile-time error: `incompatible types: int cannot be converted to boolean`.
The condition for a `while` loop in Java must be a `boolean` expression. Attempting to use an `int` directly as the condition will result in a compile-time type mismatch error.
Q2097medium
What does "fail-fast" behavior of an `Iterator` primarily mean in the context of Java collections?
✅ Correct Answer: B) The `Iterator` throws a `ConcurrentModificationException` if the underlying collection is structurally modified by any means other than the `Iterator`'s own `remove()` method during iteration.
Fail-fast iterators are designed to detect unauthorized concurrent modifications to the underlying collection and throw a `ConcurrentModificationException` to prevent indeterminate behavior.
Q2098medium
Compared to the `synchronized` keyword, what is a key advantage of using `ReentrantLock` for synchronization?
✅ Correct Answer: B) It can be acquired and released in separate methods or blocks, offering more flexible locking mechanisms.
`ReentrantLock` offers more flexibility, such as the ability to try to acquire a lock without blocking (`tryLock()`), acquire an interruptible lock (`lockInterruptibly()`), and acquire/release locks in different code blocks or methods, which is not possible with the implicit monitor lock of `synchronized`.
Q2099easycode output
What is the output of this code?
java
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.offer("Apple");
queue.offer("Banana");
System.out.println(queue.poll());
System.out.println(queue.peek());
}
}
✅ Correct Answer: D) Apple
Banana
The `offer` method adds elements. `poll()` retrieves and removes the head ('Apple'), printing it. `peek()` retrieves but does not remove the new head ('Banana'), printing it. So the output is Apple then Banana.
Q2100medium
Is `BufferedReader` inherently thread-safe?
✅ Correct Answer: C) No, it is not synchronized and concurrent access from multiple threads requires external synchronization.
`BufferedReader` is not thread-safe. If multiple threads access a `BufferedReader` instance concurrently, external synchronization mechanisms must be used to prevent data corruption.