What is the primary advantage of using `String.format()` over simple `+` concatenation for constructing complex formatted strings?
✅ Correct Answer: B) It allows for type-safe insertion of values, alignment, padding, and localized formatting.
`String.format()` provides powerful formatting capabilities similar to C's `printf`, allowing precise control over how different data types (numbers, dates, strings) are presented, including alignment, padding, and locale-specific formatting. While `StringBuilder` is better for raw performance in loops, `format()` excels in structured formatting.
Q662medium
When `BufferedReader` is chained with `InputStreamReader`, what is the specific role of `InputStreamReader`?
✅ Correct Answer: B) It converts bytes from an `InputStream` into characters, handling character encoding.
`InputStreamReader` acts as a bridge, translating byte streams into character streams. It decodes bytes from an `InputStream` into characters using a specified or default charset, which `BufferedReader` then buffers.
Q663hard
Which of the following elements cannot be overridden in Java?
✅ Correct Answer: D) A constructor.
Constructors are special methods used to initialize objects and cannot be inherited or overridden. While a subclass can call a superclass constructor using `super()`, it cannot define a method that overrides a constructor.
Q664hardcode error
What compile-time error occurs when attempting to compile this Java code?
java
class Base {
private Base() {
System.out.println("Base constructor");
}
}
class Derived extends Base {
public Derived() {
super();
System.out.println("Derived constructor");
}
}
✅ Correct Answer: A) Error: constructor Base() has private access in Base
A subclass constructor must call a superclass constructor. If the superclass only has private constructors, the subclass cannot access them, leading to a compile-time error.
Q665medium
Which pair of methods in the Java `Queue` interface is designed to insert an element, with one throwing an exception on failure and the other returning a special value?
✅ Correct Answer: A) add() and offer()
`add()` inserts an element and throws an `IllegalStateException` if the queue is full. `offer()` inserts an element and returns `false` if the queue is full, making it suitable for capacity-constrained queues.
Q666medium
What is the scope of a variable declared in the initialization section of a traditional Java `for` loop (e.g., `for (int i = 0; ...)`)?
✅ Correct Answer: B) The variable is accessible only within the `for` loop's body and its header
A variable declared in the initialization section of a `for` loop is scoped to the loop itself, meaning it is accessible within the loop header (condition and update sections) and the loop's body.
Q667hard
What is the primary difference in how `String.chars()` and `String.codePoints()` represent supplementary Unicode characters (those requiring surrogate pairs)?
✅ Correct Answer: B) `codePoints()` treats them as single Unicode code points, while `chars()` represents each `char` of the surrogate pair separately.
`String.chars()` returns an `IntStream` of `char` values, meaning a supplementary character (represented by two `char`s, a surrogate pair) will be streamed as two separate `int` values. `String.codePoints()` returns an `IntStream` of Unicode code points, so a supplementary character will be streamed as a single `int` value representing its actual code point.
Q668easycode output
What is the output of this code?
java
class Worker {
private int taskCount = 0;
public void doWork() {
synchronized (this) {
taskCount++;
System.out.print("Worker " + taskCount + ": ");
}
System.out.print("Finished. ");
}
}
public class MyProgram {
public static void main(String[] args) throws InterruptedException {
Worker worker = new Worker();
Thread t1 = new Thread(() -> worker.doWork());
Thread t2 = new Thread(() -> worker.doWork());
t1.start();
t2.start();
t1.join();
t2.join();
}
}
✅ Correct Answer: D) The output can be intermingled, e.g., 'Worker 1: Finished. Worker 2: Finished.'
The `synchronized(this)` block ensures that `taskCount` increment and the first print statement ('Worker X: ') are atomic and ordered for this object. However, the second print statement ('Finished. ') is *outside* the synchronized block. This means one thread can print 'Worker 1: ' and then release the lock, allowing the second thread to print 'Worker 2: '. Then the first thread finishes its 'Finished. ' and then the second. So, 'Worker 1: Worker 2: Finished. Finished. ' or other interleavings are possible.
Q669hard
When is `java.util.LinkedList` a more suitable choice than `java.util.ArrayList` for a `List` implementation?
✅ Correct Answer: C) When elements are frequently added or removed from the beginning or end of the list, or when frequent insertions/deletions occur in the middle after locating the position via an iterator.
LinkedList's doubly-linked nature provides O(1) performance for additions and removals at either end, and efficient O(1) removal/insertion once an element's node is located (e.g., by an iterator), making it ideal for queue/stack implementations or when elements are frequently manipulated at specific points.
Q670mediumcode output
What is the output of this code?
java
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class BufferedReaderTest {
public static void main(String[] args) {
String data = "Hello\nWorld\nJava";
try (BufferedReader br = new BufferedReader(new StringReader(data))) {
System.out.println(br.readLine());
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: A) Hello
World
The `readLine()` method reads a line of text, discarding the newline character, and returns it. The first call prints 'Hello', and the second prints 'World'.
Q671easycode output
What does this Java code print?
java
public class Main {
public static void main(String[] args) {
int value = 7;
if (value % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
}
✅ Correct Answer: B) Odd
The condition `value % 2 == 0` (7 % 2 == 0) evaluates to `1 == 0`, which is false. Therefore, the `else` block is executed, printing 'Odd'.
Q672mediumcode error
What is the compile-time error in this Java code?
java
interface Calculator {
int calculate(int a, int b);
}
public class LambdaError {
public static void performCalculation(Calculator calc) {
System.out.println(calc.calculate(10, 5));
}
public static void main(String[] args) {
performCalculation((a, b) -> System.out.println(a + b)); // Missing return
}
}
✅ Correct Answer: A) The lambda expression for `Calculator` is expected to return an `int` but does not explicitly do so, leading to a 'Missing return statement' error.
The `Calculator` interface's `calculate` method expects an `int` return value. The lambda provided uses a block body (`{...}`) but does not include an explicit `return` statement, causing a 'Missing return statement' compile-time error.
Q673mediumcode error
What is the compile-time error in the following Java code?
java
class MyClass {
private int data;
public void MyClass(int data) { // This looks like a constructor but has a return type
this.data = data;
System.out.println("Constructor-like method called");
}
public static void main(String[] args) {
MyClass obj = new MyClass(); // Attempting to call default constructor
}
}
✅ Correct Answer: C) Error: no suitable constructor found for MyClass()
A constructor must not have any return type, not even `void`. By adding `void`, `public void MyClass(int data)` becomes a regular method named `MyClass`. Since an explicit constructor is defined, the default no-argument public constructor is not automatically generated, causing `new MyClass()` to fail.
Q674easycode output
What is the output of this Java code snippet?
java
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(3, "C");
treeMap.put(1, "A");
treeMap.put(2, "B");
System.out.println(treeMap.size());
}
}
✅ Correct Answer: A) 3
The TreeMap successfully stores three key-value pairs. The `size()` method returns the number of entries currently in the map, which is 3.
Q675easy
What is the primary advantage of using `StringBuffer` over `String` when performing many string modifications (e.g., concatenations) in a loop?
✅ Correct Answer: B) `StringBuffer` is faster because it creates fewer intermediate objects.
`StringBuffer` is mutable, so modifications happen in-place without creating new objects, which improves performance and reduces memory usage compared to the immutable `String` for repeated operations.
Q676easycode error
What will happen when the following Java code is executed?
java
import java.util.Queue;
import java.util.LinkedList;
public class QueueError {
public static void main(String[] args) {
Queue<String> messages = new LinkedList<>();
messages.add("Start");
messages.remove();
System.out.println(messages.remove());
}
}
✅ Correct Answer: C) NoSuchElementException
The `remove()` method retrieves and removes the head of the queue. If the queue is empty, calling `remove()` throws a `NoSuchElementException`.
Q677easycode error
What kind of error will occur when compiling this Java code?
java
public class Main {
public static void main(String[] args) {
int num = 1;
if (num == 1) {
System.out.println("One")
System.out.println("Value is 1");
}
}
}
✅ Correct Answer: C) Compile-time Error: ';' expected.
Every statement in Java must end with a semicolon. The line `System.out.println("One")` is missing its terminating semicolon, which causes a compile-time error.
Q678mediumcode error
What kind of error will occur when executing this Java code?
java
import java.util.TreeSet;
class MyObject {
int id;
public MyObject(int id) {
this.id = id;
}
}
public class Main {
public static void main(String[] args) {
TreeSet<MyObject> set = new TreeSet<>();
set.add(new MyObject(1));
set.add(new MyObject(2));
System.out.println(set.size());
}
}
✅ Correct Answer: B) ClassCastException
TreeSet attempts to sort its elements. For custom objects like 'MyObject', it requires them to implement the Comparable interface or a Comparator to be provided. Since neither is present, a ClassCastException occurs at runtime when the second element is added and a comparison is attempted.
Q679easy
Where are local variables typically declared in Java?
✅ Correct Answer: B) Inside a method, constructor, or block.
Local variables are defined within a specific method, constructor, or code block. They are only accessible within the scope where they are declared.
Q680hardcode error
What compilation error will occur when compiling the following Java code?
java
import java.util.function.Consumer;
import java.util.function.Supplier;
public class LambdaReturnTypeMismatch {
public static void main(String[] args) {
Consumer<String> consumer = () -> "Hello";
}
}
✅ Correct Answer: A) Error: incompatible types: bad return type in lambda expression; String cannot be converted to void
The `Consumer<T>` functional interface's `accept` method has a `void` return type. The lambda expression `() -> "Hello"` implicitly returns a `String`. This mismatch between the lambda's actual return type and the expected `void` return type causes a compilation error.