import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<String> greet = name -> System.out.print("Greetings, " + name + "!");
greet.accept("Alice");
}
}
✅ Correct Answer: A) Greetings, Alice!
The Consumer `greet` accepts a string and prints a greeting message. When 'Alice' is passed, it prints 'Greetings, Alice!'.
Q3802easy
Given `int[][] data = new int[5][10];`, how would you access the element at the 2nd row and 3rd column (0-indexed)?
✅ Correct Answer: A) data[1][2]
Array indices are 0-based in Java. Therefore, the 2nd row corresponds to index 1, and the 3rd column corresponds to index 2.
Q3803hardcode error
What compilation error will occur when compiling this Java code?
java
public class MethodContinue {
public static void processValue(int val) {
if (val % 2 == 0) {
continue;
}
System.out.println("Processed odd: " + val);
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Loop iteration: " + i);
processValue(i);
}
}
}
✅ Correct Answer: A) `continue outside of loop`
The `continue` statement is used within the `processValue` method. Since the method itself is not a loop, `continue` is not permitted directly within it, even if the method is called from a loop.
Q3804easy
Which of the following statements is true about a Java do-while loop?
✅ Correct Answer: A) The loop body is executed at least once.
A do-while loop is an exit-controlled loop, meaning its condition is evaluated after the loop body has executed. This guarantees at least one execution of the loop body.
Q3805hardcode output
What is the output of this code?
java
import java.util.LinkedList;
import java.util.List;
public class Test {
public static void main(String[] args) {
LinkedList<String> original = new LinkedList<>();
original.add("One");
original.add("Two");
original.add("Three");
original.add("Four");
List<String> sub = original.subList(1, 3); // 'Two', 'Three'
sub.clear(); // Clears 'Two' and 'Three' from original
original.add("Five");
System.out.println(original);
}
}
✅ Correct Answer: A) [One, Four, Five]
`subList()` returns a view of the original list. Modifying the sublist (e.g., `clear()`) directly affects the original list. After `sub.clear()`, `original` becomes `[One, Four]`. Adding 'Five' makes it `[One, Four, Five]`.
Q3806hardcode error
Identify the compile-time error in the following Java code snippet.
java
class MyClass {
static MyClass() {
System.out.println("Static constructor?");
}
public MyClass(String s) {}
}
✅ Correct Answer: A) Error: `illegal modifier for the constructor; expected only public, protected, private, or no modifier`
Constructors in Java cannot be declared with the `static` keyword. A `static` block is used for static initialization, but it's not a constructor with a `static` modifier.
Q3807easy
If you want to iterate through a block of code as long as a condition is true, and you're unsure if the loop needs to run even once, which loop structure is most appropriate?
✅ Correct Answer: D) `while` loop
A `while` loop is suitable when the number of iterations is unknown, and the loop might not need to execute even once if the condition is initially false.
Q3808hard
What occurs if a non-positive integer (zero or negative) is passed as the `sz` parameter to the `BufferedWriter(Writer out, int sz)` constructor?
✅ Correct Answer: A) An `IllegalArgumentException` is thrown.
The `BufferedWriter` constructor explicitly checks if the provided buffer size `sz` is less than or equal to zero and throws an `IllegalArgumentException` if this condition is met.
Q3809hard
If an unchecked `RuntimeException` is thrown within the `do` block of a `do-while` loop and is not caught, what is the immediate consequence regarding the loop's execution and the `while` condition?
✅ Correct Answer: B) The loop immediately terminates, and the exception propagates up the call stack without the `while` condition being evaluated.
An uncaught `RuntimeException` immediately unwinds the stack. It will terminate the loop and propagate up the call stack from the point it was thrown, without the `while` condition ever being reached or evaluated.
Q3810easycode error
What is the error in this Java code?
java
class Parent {
public static void greet() {
System.out.println("Parent greets");
}
}
class Child extends Parent {
@Override // Line 7
public static void greet() {
System.out.println("Child greets");
}
}
public class Main {
public static void main(String[] args) {
Child.greet();
}
}
✅ Correct Answer: C) Compile-time error: method does not override or implement a method from a supertype
Static methods cannot be overridden; they are hidden. The `@Override` annotation specifically checks for overriding, so using it on a hidden static method causes a compile-time error.
Q3811easycode output
What is the output of this code?
java
public class MyClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("Result: ");
sb.append(100);
sb.append(true);
System.out.print(sb);
}
}
✅ Correct Answer: A) Result: 100true
The `append()` method can take various data types and converts them to their string representation before appending. Both 100 (int) and true (boolean) are appended as strings.
Q3812easy
What does the `getAbsolutePath()` method of the `java.io.File` class return?
✅ Correct Answer: D) The absolute path of the file or directory.
The `getAbsolutePath()` method returns the absolute pathname string of the file or directory represented by the `File` object.
Q3813hard
Which of the following is a primary reason why `java.lang.String` is designed to be immutable in Java?
✅ Correct Answer: B) To enable the String Pool mechanism, allowing multiple references to point to the same String literal for memory optimization and performance.
String's immutability allows for the String Pool, where identical string literals can share the same object, optimizing memory and enabling caching of hash codes for security-sensitive operations.
Q3814hard
How does a computationally expensive custom `Comparator` (e.g., one that performs complex string manipulations or database lookups) impact the performance of `TreeSet` operations like `add()`, `remove()`, and `contains()`?
✅ Correct Answer: B) It significantly increases the constant factor within the O(log n) time complexity, making operations slower overall.
While `TreeSet` operations are theoretically O(log n), each comparison performed by the underlying Red-Black tree involves invoking the `Comparator`. A computationally expensive comparator will increase the time taken for each comparison, thus increasing the constant factor and making the overall operations slower.
Q3815hardcode error
What exception is thrown when the `oos.writeObject(container)` line is executed in the `main` method?
java
import java.io.*;
class NotSerializableClass {
private String name;
public NotSerializableClass(String name) { this.name = name; }
public String getName() { return name; }
}
class SerializableContainer implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private NotSerializableClass nonSerializableField; // This field is not Serializable
public SerializableContainer(int id, String name) {
this.id = id;
this.nonSerializableField = new NotSerializableClass(name);
}
}
public class SerializationError1 {
public static void main(String[] args) throws IOException {
SerializableContainer container = new SerializableContainer(1, "Test");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(container); // Error occurs here
oos.close();
}
}
✅ Correct Answer: A) java.io.NotSerializableException: NotSerializableClass
A `NotSerializableException` is thrown because `SerializableContainer` attempts to serialize `nonSerializableField`, which is an instance of `NotSerializableClass`. For an object to be serializable, all its non-transient fields must also be serializable.
Q3816medium
Which of the following logical operators in Java exhibits short-circuiting behavior, potentially preventing the evaluation of its right-hand operand?
✅ Correct Answer: C) `&&` (logical AND)
The `&&` (logical AND) operator is short-circuiting; if its left operand is `false`, the right operand is not evaluated because the entire expression is already determined to be `false`.
Q3817easycode error
What error will this Java code produce during compilation?
java
public class ArrayError {
public static void main(String[] args) {
int[][] matrix = new int[2][];
matrix[0] = new int[3][];
}
}
✅ Correct Answer: A) Compilation Error: incompatible types: int[][] cannot be converted to int[]
`matrix[0]` is of type `int[]` (a one-dimensional array). You are trying to assign `new int[3][]` which is of type `int[][]` (a two-dimensional array). This type mismatch causes a compilation error.
Q3818easycode output
What is the output of this code?
java
class LoginFailedException extends Exception {
public LoginFailedException(String reason) {
super("Login failed: " + reason);
}
}
public class Main {
public static void authenticate(String username, String password) throws LoginFailedException {
if (!username.equals("user") || !password.equals("pass")) {
throw new LoginFailedException("Invalid credentials.");
}
}
public static void main(String[] args) {
try {
authenticate("admin", "pass");
} catch (LoginFailedException e) {
System.out.println(e.getMessage());
}
System.out.println("Program continues.");
}
}
✅ Correct Answer: A) Login failed: Invalid credentials.
Program continues.
The `authenticate` method throws `LoginFailedException` because the credentials are incorrect. This exception is caught in `main`, its message is printed, and then the program proceeds to print 'Program continues.'.
Q3819hard
Which statement about Java functional interfaces is TRUE?
✅ Correct Answer: D) A functional interface can declare default and static methods in addition to its single abstract method.
A functional interface is defined by having exactly one abstract method (SAM). It can optionally include any number of default and static methods, and the `@FunctionalInterface` annotation is optional, serving primarily as a compiler check.
Q3820easy
What type of exception is typically thrown by `FileWriter` methods like `write()` or `close()` if an I/O error occurs?
✅ Correct Answer: C) IOException
`IOException` is the general class for input/output errors, which `FileWriter` methods can throw during file operations.