What is a common characteristic of a Java deserialization vulnerability (e.g., using 'gadget chains')?
✅ Correct Answer: B) It exploits the ability of the deserialization process to call methods on arbitrary objects in the deserialized object graph, leading to remote code execution.
Deserialization vulnerabilities arise when an attacker crafts a serialized stream to trigger unintended method calls on legitimate classes in the deserialized object graph, potentially leading to remote code execution.
Q22mediumcode output
What does this code print?
java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> letters = new ArrayList<>(List.of("X", "Y", "Z"));
Iterator<String> it = letters.iterator();
try {
it.next(); // Advances to X
it.remove(); // Removes X
it.next(); // Advances to Y
it.remove(); // Removes Y
it.remove(); // This is the problematic call
} catch (IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println(letters);
}
}
✅ Correct Answer: B) Error: Iterator.remove() can only be called once after a next() call
[Z]
The `remove()` method can only be called once per call to `next()`. Calling `it.remove()` a second time without an intervening `it.next()` call results in an `IllegalStateException`.
Q23easycode output
What is the output of this code?
java
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> items = new HashSet<>();
items.add("Pen");
items.add("Book");
items.remove("Pen");
items.add("Pencil");
items.add("Book"); // Duplicate
System.out.println(items.size());
}
}
✅ Correct Answer: A) 2
The set starts with 'Pen', 'Book'. 'Pen' is removed. Then 'Pencil' is added. 'Book' is added again but is a duplicate and ignored. The final elements are 'Book', 'Pencil', resulting in a size of 2.
Q24hardcode error
What compilation error will occur in the provided Java code?
java
public class FinalVarReassign {
public static void main(String[] args) {
final int counter = 0;
// Attempt to reassign a final variable
counter = 1;
System.out.println(counter);
}
}
✅ Correct Answer: A) Error: cannot assign a value to final variable 'counter'.
Once a `final` variable is initialized, its value cannot be changed. Attempting to reassign `counter` results in a compile-time error.
Q25mediumcode output
What does this code print?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> stack = new LinkedList<>();
stack.push(1);
stack.push(2);
stack.add(3);
System.out.print(stack.pop() + " ");
System.out.println(stack.peek());
}
}
✅ Correct Answer: A) 2 1
`push(1)` adds 1 to the front: [1]. `push(2)` adds 2 to the front: [2, 1]. `add(3)` adds to the end: [2, 1, 3]. `pop()` removes and returns the first element (2), printing '2'. The list becomes [1, 3]. `peek()` returns the first element (1) without removing it, printing '1'. Thus, the output is '2 1'.
Q26hardcode output
What is the output of this code?
java
public class StringMatchesTest {
public static void main(String[] args) {
String s1 = "a1b2c3";
String s2 = "a1b23";
System.out.println(s1.matches("([a-z]\\d)+") + ", " + s2.matches("([a-z]\\d)+"));
}
}
✅ Correct Answer: B) true, false
`matches()` attempts to match the entire string against the regular expression. The pattern `([a-z]\d)+` means one or more occurrences of a lowercase letter followed by a digit. `s1` ("a1b2c3") perfectly fits this pattern. `s2` ("a1b23") does not, because the final '3' is not preceded by a letter to form a complete `[a-z]\d` sequence.
Q27easycode error
What is the compilation error in the given Java code?
java
import java.util.function.Function;
@FunctionalInterface
interface Greeter {
String greet(String name);
}
public class Main {
public static void main(String[] args) {
Greeter greeter = new Greeter();
System.out.println(greeter.greet("World"));
}
}
✅ Correct Answer: B) Greeter is abstract; cannot be instantiated
Interfaces, including functional interfaces, are abstract by nature and cannot be instantiated directly using the `new` keyword. They must be implemented by a class or a lambda expression.
Q28mediumcode output
What will be printed when this Java code is executed?
java
class StaticParent {
static void greet() {
System.out.println("Parent's static greet");
}
}
class StaticChild extends StaticParent {
static void greet() { // Method hiding, not overriding
System.out.println("Child's static greet");
}
}
public class Main {
public static void main(String[] args) {
StaticParent p = new StaticChild();
p.greet();
StaticChild c = new StaticChild();
c.greet();
}
}
✅ Correct Answer: A) Parent's static greet
Child's static greet
Static methods cannot be overridden; they are hidden. The method invoked for a static call depends on the *reference type* at compile time, not the actual object type at runtime. So `p.greet()` calls `StaticParent.greet()` and `c.greet()` calls `StaticChild.greet()`.
Q29mediumcode error
What is the outcome when this Java code is executed?
java
import java.util.LinkedList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
LinkedList<String> items = new LinkedList<>();
items.add("Item1");
items.add("Item2");
for (String item : items) {
items.remove(item);
}
System.out.println(items.size());
}
}
✅ Correct Answer: C) ConcurrentModificationException
Modifying a collection (here, `items.remove(item)`) while iterating over it using an enhanced for-loop (which uses an implicit iterator) results in a `ConcurrentModificationException`.
Q30easy
What happens if you call `remove()` on an empty `Queue` in Java?
✅ Correct Answer: C) It throws a `NoSuchElementException`.
Calling `remove()` on an empty queue will result in a `NoSuchElementException` because there is no element to retrieve from the queue.
Q31mediumcode output
What is the output of the following Java code snippet?
java
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class BufferedReaderTest {
public static void main(String[] args) {
String data = "ABCD\nEFG";
try (BufferedReader br = new BufferedReader(new StringReader(data))) {
System.out.print((char) br.read());
System.out.print(br.readLine());
System.out.print((char) br.read());
} catch (IOException e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: B) A BCD E
`br.read()` reads 'A'. `br.readLine()` reads 'BCD' (consuming the 'D' and the newline). The next `br.read()` reads 'E' from 'EFG'. Note the implicit space between print statements on separate lines in the question, but the actual output concatenates.
Q32easy
What is the primary role of a 'setter' method in an encapsulated class?
✅ Correct Answer: C) To modify the value of a private instance variable, often with validation.
A setter method (also known as a mutator) is specifically designed to update the value of a private instance variable, allowing for custom logic or validation before the assignment.
Q33hard
You are using `Stream.forEach()` and the lambda you want to pass needs to perform an operation that can throw a checked exception (e.g., `IOException`). Which statement accurately describes the required handling?
✅ Correct Answer: C) The lambda expression must encapsulate the throwing code within a `try-catch` block and handle the `IOException` locally.
Functional interfaces like `Consumer` (used by `forEach`) do not declare checked exceptions. Thus, any checked exception thrown inside the lambda must either be caught and handled locally within the lambda's body, or explicitly re-thrown as an unchecked exception.
Q34easy
When might a do-while loop be particularly useful compared to a while loop?
✅ Correct Answer: A) When you need to ensure the loop body executes at least once, regardless of the initial condition.
The primary advantage of a do-while loop is its guarantee of at least one execution, which is useful for scenarios like menu prompts or initial data input.
Q35mediumcode error
What error does this Java code produce when executed?
java
public class Main {
public static void main(String[] args) {
String phrase = "Hello";
System.out.println(phrase.substring(2, 6));
}
}
✅ Correct Answer: A) java.lang.StringIndexOutOfBoundsException: String index out of range: 6
The substring(beginIndex, endIndex) method requires endIndex to be less than or equal to the string's length. For 'Hello' (length 5), an endIndex of 6 is out of bounds, leading to a StringIndexOutOfBoundsException.
Q36medium
When a subclass defines a static method with the same signature as a static method in its superclass, what is this called?
✅ Correct Answer: C) Method hiding.
This scenario is known as method hiding, not overriding, because static methods are resolved at compile time based on the reference type, not at runtime based on the actual object type.
Q37medium
What is the primary advantage of using a method reference over an equivalent lambda expression when applicable?
✅ Correct Answer: B) Method references reduce boilerplate code and improve readability by explicitly naming the method being called.
The main advantage of method references is improved readability and conciseness. When a lambda expression merely invokes an existing method, a method reference provides a more direct and often clearer way to express that intent.
Q38hard
Which access modifier is *not* permitted for an `abstract` method in Java, and why?
✅ Correct Answer: C) `private`, because it would make the method unreachable for implementation by subclasses.
An `abstract` method cannot be `private` because it must be visible to its subclasses for implementation. A `private` method is not inherited and cannot be overridden, thus contradicting the purpose of an `abstract` method.
Q39hardcode output
What does this code print?
java
public class MultiArrayQ2 {
public static void main(String[] args) {
int[][] arr1 = new int[2][2];
int[][] arr2 = new int[2][2];
arr1[0] = arr2[1];
arr2[1][0] = 99;
System.out.println(arr1[0][0]);
}
}
✅ Correct Answer: A) 99
The assignment `arr1[0] = arr2[1]` makes `arr1[0]` refer to the same inner array object as `arr2[1]`. Modifying `arr2[1][0]` subsequently reflects in `arr1[0][0]` because they point to the identical array instance.
Q40hard
What is the primary implication of declaring a method as `final` in a superclass with respect to inheritance?
✅ Correct Answer: C) The method cannot be overridden by any subclass.
The `final` keyword, when applied to a method, prevents any subclass from overriding that specific method, ensuring its implementation remains constant throughout the inheritance hierarchy.