In a standard Queue, elements are typically added to which end and removed from which end?
✅ Correct Answer: B) Added to tail, removed from head
Elements are added to the 'tail' (or end) of the queue and removed from the 'head' (or front) of the queue to maintain the FIFO order.
Q1242mediumcode error
What error will this code produce at runtime?
java
public class LoopTest {
public static void main(String[] args) {
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
// names[2] remains null
int i = 0;
while (i < names.length) {
System.out.println(names[i].toUpperCase());
i++;
}
}
}
✅ Correct Answer: A) A java.lang.NullPointerException.
The array element `names[2]` is not initialized and thus holds `null`. When the loop attempts to call `toUpperCase()` on `names[2]`, it results in a `NullPointerException` because a method cannot be called on a null reference.
Q1243hardcode error
Consider the following Java code snippet. What kind of error will occur when this code is executed?
java
import java.io.*;
public class FileWriterError1 {
public static void main(String[] args) {
File dir = new File("my_test_directory");
dir.mkdir(); // Ensure directory exists
try {
FileWriter fw = new FileWriter(dir); // Attempt to create FileWriter with a directory
fw.write("Some data");
fw.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
dir.delete(); // Clean up
}
}
}
✅ Correct Answer: C) An IOException, typically indicating 'Is a directory' or 'Access denied' depending on OS.
Attempting to initialize a FileWriter with a File object that represents an existing directory will result in an IOException. The system prevents writing to a directory as if it were a regular file, leading to an error message like 'Is a directory'.
Q1244medium
A thread calls `Thread.yield()`. What is the immediate effect on the calling thread's state?
✅ Correct Answer: C) It remains in the RUNNABLE state but hints to the scheduler that it can yield the CPU to other threads.
`Thread.yield()` is a hint to the scheduler that the current thread is willing to yield its current use of a processor. The thread remains in the RUNNABLE state and may be immediately rescheduled.
Q1245easy
Is Java's `java.util.HashMap` inherently thread-safe?
✅ Correct Answer: B) No, it is not synchronized and not thread-safe.
HashMap is not synchronized, meaning it's not thread-safe and should not be used in multi-threaded environments without external synchronization.
Q1246hard
You have a hierarchy of custom exceptions: `BaseAppException` -> `DataAccessException` -> `ConstraintViolationException`. If a method throws `ConstraintViolationException`, and another method `handleException(BaseAppException e)` is called with this exception, what is the most specific type of catch block that will *also* catch `ConstraintViolationException` without catching `BaseAppException` directly?
✅ Correct Answer: B) `catch (DataAccessException dae)`
Due to polymorphism, a `catch (DataAccessException dae)` block will catch `ConstraintViolationException` because `ConstraintViolationException` is a subclass of `DataAccessException`. This is the most specific option that catches the exception without explicitly targeting `BaseAppException`.
Q1247easy
Which of the following operations CANNOT be performed using the `java.io.File` class directly?
✅ Correct Answer: C) Reading the content of a file.
The `java.io.File` class deals with file system objects as abstract pathnames, allowing manipulation of metadata and properties, but it does not provide methods for reading or writing file content directly.
Q1248easy
Which operator represents the logical AND operation in Java?
✅ Correct Answer: C) &&
The logical AND operator (&&) returns true if both its operands are true; otherwise, it returns false. It is also a short-circuit operator.
Q1249hardcode output
What is the output of this code?
java
interface SpeakerA {
default void greet() { System.out.println("Hello from A"); }
}
interface SpeakerB {
default void greet() { System.out.println("Hello from B"); }
}
class HybridSpeaker implements SpeakerA, SpeakerB {
// No override for greet()
}
public class DiamondProblemTest {
public static void main(String[] args) {
// new HybridSpeaker().greet(); // This line would cause the error
}
}
✅ Correct Answer: A) Compile-time error
When a class implements two interfaces that both provide a default method with the same signature, and the class does not override that method, it results in a compile-time ambiguity error for the `greet()` method.
Q1250hardcode error
What kind of error will occur when executing the following Java code?
java
import java.util.concurrent.LinkedBlockingQueue;
public class QError8 {
public static void main(String[] args) {
LinkedBlockingQueue<String> lbq = new LinkedBlockingQueue<>(5);
try {
lbq.put("Item A");
lbq.put(null);
System.out.println(lbq.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: A) java.lang.NullPointerException
LinkedBlockingQueue, like other `BlockingQueue` implementations and concurrent collections, does not permit null elements. Attempting to `put()` a null value will result in a `java.lang.NullPointerException`.
Q1251easycode error
What kind of error will occur when compiling this Java code?
java
class SecretAgent {
private SecretAgent() {
System.out.println("Agent created");
}
}
class JamesBond extends SecretAgent {
public JamesBond() {
super(); // Attempting to call private constructor
System.out.println("007 created");
}
}
public class Main {
public static void main(String[] args) {
JamesBond jb = new JamesBond();
}
}
✅ Correct Answer: A) Compile-time error: SecretAgent() has private access in SecretAgent
A subclass cannot call a private constructor of its superclass, as private members are not accessible from outside the class. This will result in a compile-time error.
Q1252easy
What is it called when a subclass provides a specific implementation for a method that is already defined in its superclass with the exact same signature?
✅ Correct Answer: C) Method overriding
Method overriding is the mechanism where a subclass provides its own specific implementation for a method already present in its superclass.
Q1253hard
When `BufferedReader` wraps a `FileReader` (e.g., `new BufferedReader(new FileReader("file.txt"))`), how does this differ fundamentally in character encoding handling compared to wrapping an `InputStreamReader` (e.g., `new BufferedReader(new InputStreamReader(new FileInputStream("file.txt")))`)?
✅ Correct Answer: B) `FileReader` internally creates an `InputStreamReader` and uses the platform's default charset for byte-to-char conversion, whereas `InputStreamReader` allows explicit charset specification.
`FileReader` is a convenience class that uses the platform's default character encoding. `InputStreamReader`, however, allows the developer to explicitly specify the character set for byte-to-character conversion, offering more control.
Q1254hardcode output
What does this code print?
java
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
default int add(int a, int b) {
return a + b;
}
static int multiply(int a, int b) {
return a * b;
}
}
public class CustomFIWithMethods {
public static void main(String[] args) {
Calculator subtractor = (a, b) -> a - b;
Calculator divider = (a, b) -> a / b;
System.out.println("Subtract: " + subtractor.calculate(10, 5));
System.out.println("Add using subtractor: " + subtractor.add(10, 5));
System.out.println("Add using divider: " + divider.add(10, 5));
System.out.println("Multiply static: " + Calculator.multiply(10, 5));
}
}
✅ Correct Answer: A) Subtract: 5
Add using subtractor: 15
Add using divider: 15
Multiply static: 50
The `calculate` method executes the lambda expression. Default methods like `add` can be called directly on instances of the functional interface. Static methods like `multiply` must be called on the interface type itself.
Q1255hard
When `clone()` is invoked on an array of `String` objects (e.g., `String[] original = {"A", "B"}; String[] cloned = original.clone();`), what is the relationship between `original` and `cloned`?
✅ Correct Answer: B) `original` and `cloned` refer to different array objects, but their elements point to the same `String` objects (shallow copy).
Cloning an array in Java performs a shallow copy. This means a new array object is created, but its elements are references to the same objects as the original array's elements, not new copies of those objects.
Q1256mediumcode error
Which exception is expected to be printed to the console by the given Java code?
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("log.txt"))) {
writer.write("Message 1");
writer.flush();
writer.close();
writer.flush(); // Attempt to flush after close
} catch (IOException e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
✅ Correct Answer: C) IOException: Stream closed
After `writer.close()` is called, the stream is closed and no further operations like `flush()` or `write()` are permitted. Attempting `writer.flush()` on a closed stream will throw an `IOException` with the message 'Stream closed'.
Q1257medium
Consider `Optional<String> optional = Optional.empty();`. Which statement correctly describes the key difference between `optional.orElse("Default")` and `optional.orElseGet(() -> "Default")`?
✅ Correct Answer: A) `orElse` always evaluates its default value argument, while `orElseGet` evaluates its `Supplier` only if the `Optional` is empty.
The `orElse` method eagerly evaluates its argument, potentially creating an object unnecessarily. `orElseGet` takes a `Supplier` and lazily evaluates it only when the `Optional` is empty, which can be more efficient for expensive default value computations.
Q1258hardcode error
What is the error encountered when running this Java code?
java
public class JaggedArrayError {
public static void main(String[] args) {
int[][] matrix = new int[3][];
matrix[0] = new int[2];
matrix[1] = new int[3];
// matrix[2] is not initialized
System.out.println(matrix[1][2]); // Valid access
System.out.println(matrix[2][0]); // Problematic access
}
}
✅ Correct Answer: A) java.lang.NullPointerException
In a jagged array, when only the first dimension is initialized (e.g., `new int[3][]`), the inner arrays are initially `null`. `matrix[2]` is `null` because it was never assigned an array object. Attempting to access `matrix[2][0]` on a `null` reference causes a NullPointerException.
Q1259hard
If an abstract class `A` has two abstract methods `method1()` and `method2()`, and a non-abstract class `B` extends `A` but only provides an implementation for `method1()`, what are the implications for class `B`?
✅ Correct Answer: C) Class `B` will result in a compile-time error for not implementing `method2()`.
A concrete (non-abstract) class that extends an abstract class must provide implementations for all inherited abstract methods. Failing to do so will result in a compile-time error, as the class is still technically abstract but not declared as such.
Q1260mediumcode output
What is the state of `t2` at point Y in the output?
java
public class ThreadStateDemo6 {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
synchronized (lock) {
try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
});
Thread t2 = new Thread(() -> {
synchronized (lock) {
System.out.println("T2 acquired lock and is RUNNABLE.");
try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
System.out.println("T2 finished.");
});
t1.start();
Thread.sleep(50); t2.start(); Thread.sleep(50);
System.out.println("State of t2 at point X: " + t2.getState());
Thread.sleep(200); // Allow t1 to finish and t2 to acquire lock
System.out.println("State of t2 at point Y: " + t2.getState());
}
}
✅ Correct Answer: A) State of t2 at point Y: TIMED_WAITING
At point X, `t2` is BLOCKED. After `t1` releases the lock, `t2` acquires it and enters its `synchronized` block. Inside, it calls `Thread.sleep(100)`, which puts it into the TIMED_WAITING state.