Which of the following correctly demonstrates the creation and use of an anonymous array in Java?
✅ Correct Answer: B) printArray(new int[] {1, 2, 3});
An anonymous array is created without explicitly assigning it to a reference variable. `new int[] {1, 2, 3}` creates an array on the fly which can be passed directly to a method. Option A is shorthand for an array literal initializer which is not allowed directly as a method argument without `new type[]`. C is a named array. D is incorrect syntax.
Q1722hardcode output
What is the output of this code?
java
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String data = "1\n\n3\n";
BufferedReader br = new BufferedReader(new StringReader(data));
System.out.println("[" + br.readLine() + "]");
System.out.println("[" + br.readLine() + "]");
System.out.println("[" + br.readLine() + "]");
System.out.println("[" + br.readLine() + "]");
br.close();
}
}
✅ Correct Answer: A) [1]
[]
[3]
[null]
readLine() returns the content of the line, excluding the newline. For an empty line, it returns an empty string "". When the end of the stream is reached, it returns null. The last newline after '3' is consumed, making the next readLine() return null.
Q1723hardcode output
What is the output of this code?
java
class MyBrokenException extends Exception {
public MyBrokenException(String message) {
super(message);
if (message.contains("fatal")) {
throw new IllegalStateException("Internal error!");
}
}
}
public class Main {
public static void main(String[] args) {
try {
throw new MyBrokenException("fatal error");
} catch (MyBrokenException e) {
System.out.println("Caught MyBrokenException: " + e.getMessage());
} catch (IllegalStateException e) {
System.out.println("Caught IllegalStateException: " + e.getMessage());
} finally {
System.out.println("Finally block.");
}
}
}
✅ Correct Answer: A) Caught IllegalStateException: Internal error!
Finally block.
When `new MyBrokenException("fatal error")` is called, the `super(message)` constructor executes first. Then, within the `MyBrokenException` constructor, `IllegalStateException` is thrown, interrupting the constructor execution. This `IllegalStateException` is caught by the second `catch` block, followed by the `finally` block.
Q1724hardcode output
What does this code print?
java
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String data = "A\nB\nC";
BufferedReader br = new BufferedReader(new StringReader(data), 2);
br.mark(1);
System.out.print((char)br.read()); // A
System.out.print((char)br.read()); // \n
try {
br.reset();
} catch (IOException e) {
System.out.print("RESET_ERROR");
}
System.out.print((char)br.read()); // B
br.close();
}
}
✅ Correct Answer: A) A
RESET_ERRORB
The BufferedReader is created with a buffer size of 2. `mark(1)` sets a read limit of 1. After reading 'A' and '\n' (2 characters), the read limit of 1 is exceeded. Therefore, `reset()` will throw an IOException because the mark is no longer valid. The catch block prints 'RESET_ERROR'. The subsequent read will then read 'B'.
Q1725mediumcode error
Identify the compilation error in the provided Java code, which attempts to overload methods.
java
public class OverloadChecker {
public void processData(String s) {
System.out.println("Public: " + s);
}
private void processData(String s) { // This line causes the error
System.out.println("Private: " + s);
}
public static void main(String[] args) {
OverloadChecker oc = new OverloadChecker();
oc.processData("test");
}
}
✅ Correct Answer: A) Compile-time error: Method 'processData(String)' is already defined in 'OverloadChecker'.
Method overloading relies solely on the method signature (name and parameter list). Access modifiers do not differentiate overloaded methods, resulting in a duplicate method definition error.
Q1726medium
What will be the output of the following Java code snippet?
`String str = "Hello World";`
`System.out.println(str.substring(6, 11));`
✅ Correct Answer: A) "World"
The `substring(beginIndex, endIndex)` method returns a new string that is a substring of this string. It starts at `beginIndex` and extends to the character at index `endIndex - 1`. 'W' is at index 6, and 'd' is at index 10, so it extracts "World".
Q1727hardcode output
What is the output of this code?
java
class Animal {
public static void sound() {
System.out.println("Animal makes a sound");
}
public void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
public static void sound() {
System.out.println("Dog barks");
}
@Override
public void eat() {
System.out.println("Dog eats kibble");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
myDog.eat();
}
}
✅ Correct Answer: A) Animal makes a sound\nDog eats kibble
Static methods are hidden, not overridden. The invocation of `static` methods depends on the compile-time type (`Animal`), while instance methods are resolved polymorphically based on the runtime type (`Dog`). Thus, `Animal.sound()` is called, and `Dog.eat()` is called.
Q1728hardcode error
What is the primary flaw or error in this Java code related to the while loop's termination condition?
java
public class LogicalInfiniteLoop {
public static void main(String[] args) {
double x = 0.1;
while (x != 1.0) {
x += 0.1;
System.out.println(x);
}
System.out.println("Loop finished.");
}
}
✅ Correct Answer: A) The program will likely hang indefinitely due to floating-point precision issues.
Due to the imprecise nature of floating-point arithmetic, `x` might never exactly equal `1.0` (e.g., it might become `0.9999999999999999` then `1.1000000000000001`). This means the `while (x != 1.0)` condition may never be false, causing an infinite loop.
Q1729hard
Given `byte b = -1;`, what is the value of `b >>> 4` in Java?
✅ Correct Answer: C) 268435455
Bitwise operations on `byte` (and `short`) operands first promote them to `int`. The `int` representation of `byte -1` is `0xFFFFFFFF`. The unsigned right shift `>>> 4` then shifts the bits, filling with zeros from the left, resulting in `0x0FFFFFFF`, which is `268435455` in decimal.
Q1730mediumcode output
What does this code print?
java
public class ResourceCleanup {
static class MyResource implements AutoCloseable {
public void open() { System.out.println("Resource opened"); }
@Override
public void close() { System.out.println("Resource closed"); }
}
public static void main(String[] args) {
MyResource res = null;
try {
res = new MyResource();
res.open();
throw new RuntimeException("Error during processing");
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
} finally {
if (res != null) {
res.close();
}
}
}
}
✅ Correct Answer: A) Resource opened
Caught exception: Error during processing
Resource closed
The resource is opened in the `try` block, an exception is thrown, then caught. The `finally` block is guaranteed to execute whether an exception occurred or not. It correctly checks if `res` is not null and then closes the resource, ensuring cleanup.
Q1731hard
What is the primary purpose of the `trimToSize()` method in `StringBuffer`?
✅ Correct Answer: A) To reduce the internal character array's capacity to exactly match the current length of the character sequence.
`trimToSize()` is used to optimize memory usage by reducing the `StringBuffer`'s internal character array to its actual current length. This discards any unused excess capacity, which can be beneficial when a `StringBuffer` is no longer expected to grow significantly.
Q1732medium
What is the primary benefit of constructor overloading in Java?
✅ Correct Answer: B) To provide multiple ways to initialize an object, offering flexibility in object creation.
Constructor overloading allows a class to have multiple constructors with different parameter lists, enabling objects to be initialized in various ways depending on the data provided during creation.
Q1733medium
What is the most efficient and recommended method to copy elements from one array to another (existing) array in Java?
✅ Correct Answer: B) Using `System.arraycopy()` method.
`System.arraycopy()` is a native method that performs a block copy of array elements, which is highly optimized and generally more efficient than a manual loop. Option C only copies the reference, not the elements. `Arrays.copyOfRange()` creates a new array, rather than copying into an existing one.
Q1734hard
If a class `PoorHashObject` defines its `hashCode()` method to always return a constant value (e.g., `return 42;`) while still correctly implementing `equals()`, what is the asymptotic time complexity for `add()` and `contains()` operations in a `HashSet` containing `N` instances of `PoorHashObject`?
✅ Correct Answer: C) O(N) for both `add()` and `contains()`.
If all objects have the same hash code, they will all map to the same bucket. `HashSet` (which uses `HashMap`) will then essentially degenerate into a `LinkedList` for that bucket, requiring `equals()` comparisons against `N` elements in the worst case for `add()` and `contains()`.
Q1735easycode output
What is the output of this code?
java
class Base {
Base() {
System.out.print("Base constructor");
}
}
class Derived extends Base {
Derived() {
// super(); is implicitly called here
System.out.print("Derived constructor");
}
}
public class Main {
public static void main(String[] args) {
Derived d = new Derived();
}
}
✅ Correct Answer: C) Base constructorDerived constructor
When a `Derived` class object is created, the constructor of the `Base` class is implicitly called first, followed by the `Derived` class constructor. This results in both print statements executing in order.
Q1736easy
If a thread attempts to acquire an object's monitor lock that is already held by another thread, what state does the attempting thread enter?
✅ Correct Answer: B) BLOCKED
When a thread is waiting for a monitor lock, it is in the BLOCKED state. It will remain blocked until the lock becomes available.
Q1737easy
What is an object in Java?
✅ Correct Answer: B) An instance of a class.
An object is a concrete instance of a class, created from the class blueprint, representing a real-world entity.
Q1738hardcode output
What does this code print?
java
public class OperatorChallenge {
public static void main(String[] args) {
Object o = true ? new Integer(1) : new Double(2.0);
System.out.println(o.getClass().getName());
}
}
✅ Correct Answer: A) java.lang.Double
The type of a ternary expression is determined by type promotion rules. Since one operand is an `Integer` and the other is a `Double`, both are unboxed to their primitive types (`int` and `double`). The `double` type has a larger range and precision, so the `int` is promoted to `double`, and the result type of the expression is `Double`.
Q1739easy
Is it possible to cast a `char` to an `int` implicitly?
✅ Correct Answer: A) Yes, because `int` can hold all `char` values.
Yes, `char` values can be implicitly converted to `int` because `int` is a larger data type that can fully represent the Unicode values stored in a `char`.
Q1740hardcode output
What is the output of this code?
java
import java.util.function.Consumer;
public class MethodRefAmbiguity {
public static void print(String s) { System.out.println("String: " + s); }
public static void print(Object o) { System.out.println("Object: " + o); }
public static void main(String[] args) {
Consumer<Object> c = MethodRefAmbiguity::print;
c.accept("Hello");
}
}
✅ Correct Answer: B) Object: Hello
The target type `Consumer<Object>` explicitly resolves the method reference to the `print(Object o)` method. If the target type were `Consumer<String>`, `print(String s)` would be chosen. Without a specific target type that clearly prefers one over the other (e.g., if the argument type was just 'T'), it could lead to ambiguity.