import java.io.BufferedWriter;
import java.io.StringWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
bw.write('X');
bw.write(89); // ASCII value for 'Y'
bw.write("Z");
bw.close();
System.out.print(sw.toString());
}
}
✅ Correct Answer: A) XYZ
The `BufferedWriter`'s `write(int c)` method writes a single character, where the integer argument represents the Unicode value of the character. ASCII 89 corresponds to 'Y'. The `write(String str)` method writes the given string. All three are concatenated.
Q3362hardcode output
What is the output of this code?
java
import java.util.TreeSet;
public class App {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(5);
set.add(10);
set.add(null); // Adding null after non-null elements
System.out.println(set.size());
}
}
✅ Correct Answer: C) NullPointerException
TreeSet, when using natural ordering (for Integer), cannot handle null elements for comparison if non-null elements are already present. An attempt to compare a non-null integer with a null will result in a NullPointerException.
Q3363easy
Which of the following is NOT a characteristic of Java Lambda Expressions?
✅ Correct Answer: C) They can declare new fields and methods within their body.
Lambda expressions are stateless and cannot declare new fields or methods. They primarily focus on defining a block of executable code (behavior).
Q3364easycode output
What is the output of this Java code?
java
interface Calculator {
int calculate(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator multiply = (x, y) -> x * y;
System.out.println(multiply.calculate(6, 7));
}
}
✅ Correct Answer: A) 42
The lambda expression `(x, y) -> x * y` implements the `calculate` method to multiply two numbers. So, 6 * 7 results in 42.
Q3365hardcode error
What is the expected outcome when compiling the following Java code snippet?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterError6 {
public void createFile() { // Method does not declare throws IOException
FileWriter fw = new FileWriter("another_test.txt"); // IOException is a checked exception
fw.write("Some text");
fw.close();
}
public static void main(String[] args) {
new FileWriterError6().createFile();
}
}
✅ Correct Answer: C) A compilation error because `IOException` is a checked exception and is not handled or declared.
The `FileWriter` constructor, `write()` method, and `close()` method all declare `throws IOException`. Since `IOException` is a checked exception, it must either be caught using a `try-catch` block or declared in the method signature using `throws IOException`. Failing to do so results in a compilation error.
Q3366easycode output
What is the output of this code?
java
class Device {
void start() {
System.out.println("Device starting");
}
}
class Computer extends Device {
void start() {
System.out.println("Computer starting");
}
}
public class Main {
public static void main(String[] args) {
Device myDevice = new Computer();
myDevice.start();
}
}
✅ Correct Answer: B) Computer starting
This demonstrates polymorphism. Although `myDevice` is declared as type `Device`, it refers to a `Computer` object. The overridden `start()` method in `Computer` is invoked at runtime.
Q3367easycode output
What is the output of this Java code?
java
public class MyClass {
public static void main(String[] args) {
System.out.println("Step 1");
try {
System.out.println("Step 2");
throw new UnsupportedOperationException("Operation not supported");
} catch (UnsupportedOperationException e) {
System.out.println("Step 3: " + e.getMessage());
}
System.out.println("Step 4");
}
}
✅ Correct Answer: A) Step 1
Step 2
Step 3: Operation not supported
Step 4
The code executes sequentially. 'Step 1' is printed. Then, the try block prints 'Step 2' and throws an `UnsupportedOperationException`. This exception is immediately caught by the subsequent catch block, which prints 'Step 3' along with the exception message. Finally, execution continues after the try-catch block, printing 'Step 4'.
Q3368hard
Prior to Java 7 (specifically Java 6), a call to `String.substring()` could lead to a memory leak in certain scenarios. Which of the following best describes the underlying reason for this issue?
✅ Correct Answer: B) The new `String` object created by `substring` would still hold a reference to the original `char[]` array, even if only a small part was logically needed.
In Java 6 and earlier, `substring()` often reused the underlying `char[]` of the original string. If the original string was large and the substring was small, the large `char[]` would be kept alive by the small substring's reference, preventing garbage collection of the larger array.
Q3369mediumcode error
What error will occur when compiling this Java code snippet?
java
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("age", 30);
map.put("name", "Alice"); // Type mismatch
System.out.println(map.get("age"));
}
}
✅ Correct Answer: A) Compilation Error: incompatible types: java.lang.String cannot be converted to java.lang.Integer
The `HashMap` is declared to hold `String` keys and `Integer` values. Attempting to `put` a `String` value ("Alice") where an `Integer` is expected will result in a compile-time type mismatch error.
Q3370hard
What is the behavior if a `continue` statement uses a label that identifies a simple code block (i.e., not a loop)?
✅ Correct Answer: C) A compile-time error occurs, as labels for `continue` must identify an enclosing loop.
A `continue` statement, whether labeled or unlabeled, is only valid within the body of a loop. It cannot be used to target or affect a simple, non-looping code block, and attempting to do so results in a compile-time error.
Q3371mediumcode error
What is the outcome when this Java code is executed?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<int> primitiveList = new LinkedList<>();
primitiveList.add(100);
System.out.println(primitiveList.get(0));
}
}
✅ Correct Answer: B) Compilation Error
Java generics do not support primitive types. You must use wrapper classes (e.g., `Integer` for `int`) as type arguments for `LinkedList`.
Q3372hard
Which statement most accurately describes the difference in the behavior of `flush()` and `close()` methods for a `BufferedWriter` instance, specifically concerning its interaction with the underlying `Writer`?
✅ Correct Answer: D) `close()` first calls `flush()` on itself and then `close()` on the underlying `Writer`, whereas `flush()` only writes its buffer to the underlying `Writer` and then calls `flush()` on it.
`BufferedWriter.close()` ensures all buffered data is written and then explicitly calls `close()` on the wrapped `Writer`. `BufferedWriter.flush()` only writes its internal buffer to the underlying `Writer` and then calls `flush()` on it, leaving the underlying stream open.
Q3373mediumcode error
What is the output of this Java code?
java
public class ExceptionFlow6 {
public static void main(String[] args) {
testMethod();
}
public static void testMethod() {
try {
System.out.println("Try block");
throw new IllegalArgumentException("Invalid argument");
} catch (NullPointerException e) {
System.out.println("Catch block (NullPointerException)");
} finally {
System.out.println("Finally block");
}
}
}
✅ Correct Answer: A) Try block
Finally block
Exception in thread "main" java.lang.IllegalArgumentException: Invalid argument
An 'IllegalArgumentException' is thrown but not caught by the 'NullPointerException' catch block. The 'finally' block still executes, and then the uncaught exception terminates the program.
Q3374hard
Which statement accurately describes the thread-safety of `ArrayList` and its implications in a multi-threaded environment?
✅ Correct Answer: C) `ArrayList` is not thread-safe; multiple threads modifying it concurrently can lead to inconsistent state or `ConcurrentModificationException`.
`ArrayList` is not synchronized. Concurrent structural modifications by multiple threads without external synchronization can corrupt its internal state, leading to data inconsistency, `ArrayIndexOutOfBoundsException`, or `ConcurrentModificationException` during iteration.
Q3375hard
A common strategy to prevent deadlocks when acquiring multiple independent locks is to:
✅ Correct Answer: B) Ensure that all locks are acquired in a consistent, predetermined order by all participating threads.
Deadlock often occurs when threads acquire locks in different orders, leading to circular waiting. By establishing a global, consistent ordering for acquiring multiple locks, threads will avoid the circular wait condition necessary for deadlock.
Q3376medium
What happens if a subclass attempts to override a `final` method defined in its superclass?
✅ Correct Answer: C) A compile-time error occurs.
Methods declared as `final` cannot be overridden in subclasses. Attempting to do so will result in a compile-time error, as `final` prevents modification or extension.
Q3377hardcode error
What compile-time error will this Java code produce?
java
public class OperatorError8 {
public static void main(String[] args) {
int x = 10;
String s = "2";
int result = x << s; // Error line
System.out.println(result);
}
}
✅ Correct Answer: B) bad operand types for binary operator '<<'
The shift operators (`<<`, `>>`, `>>>`) require both operands to be of integral types (byte, short, char, int, or long). Using a `String` as the right-hand operand, which specifies the shift amount, is a type mismatch that results in a compile-time error.
Q3378hardcode error
What is the result of executing this Java code snippet?
java
public class WrapperCasting {
public static void main(String[] args) {
Integer i = 100;
Object obj = i;
Long l = (Long) obj;
System.out.println(l);
}
}
✅ Correct Answer: A) A ClassCastException occurs at runtime.
The variable 'obj' holds an `Integer` object. Although `Integer` and `Long` both extend `Number`, they are distinct, unrelated classes in the `Number` hierarchy. An `Integer` object cannot be directly cast to a `Long` object at runtime.
Q3379medium
When is `flatMap()` preferred over `map()` when working with `Optional`?
✅ Correct Answer: B) When the mapping function itself returns an `Optional` and you want to avoid a nested `Optional<Optional<T>>`.
`flatMap()` is used when the mapping function itself produces an `Optional`. It flattens the result, preventing the creation of an `Optional` nested within another `Optional`.
Q3380easycode output
What does this Java code print?
java
public class ArrayTest {
public static void main(String[] args) {
int[] data = {10, 20, 30};
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + " ");
}
}
}
✅ Correct Answer: A) 10 20 30
The `for` loop iterates from index 0 to `data.length - 1`. Inside the loop, `System.out.print()` prints each element followed by a space on the same line.