public class MyClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.modify("World");
System.out.println(sb);
}
}
✅ Correct Answer: C) Compile-time error: cannot find symbol method modify(java.lang.String)
The `StringBuffer` class does not have a method named `modify(String)`. Attempting to call a non-existent method results in a compile-time error, specifically 'cannot find symbol'.
Q3822mediumcode error
What is the error in this Java code?
java
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
if (name.equals("Bob")) {
names.remove(name);
}
}
System.out.println(names);
}
}
✅ Correct Answer: C) Runtime Error: `ConcurrentModificationException`.
Modifying an `ArrayList` directly while iterating over it using an enhanced for-loop will result in a `ConcurrentModificationException`. This is because the iterator's expected modification count differs from the actual count.
Q3823easy
What happens if a subclass method attempts to override a superclass method but declares a new checked exception that is broader than any declared by the superclass method (or declares a checked exception when the superclass method declared none)?
✅ Correct Answer: C) A compile-time error will occur.
An overriding method cannot declare new or broader checked exceptions than the overridden method. Doing so will result in a compile-time error.
Q3824easy
What is method overriding in the context of inheritance?
✅ Correct Answer: B) Defining a method in the subclass with the exact same signature as a method in its superclass
Method overriding occurs when a subclass provides its own implementation for a method that is already defined in its superclass, using the same method signature.
Q3825mediumcode error
What is the compilation error in the provided Java code?
java
class Parent {
public void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
protected void display() { // ERROR: weaker access
System.out.println("Child display");
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.display();
}
}
✅ Correct Answer: A) Child.java:8: error: display() in Child cannot override display() in Parent; attempting to assign weaker access privileges; was public
When overriding a method in a subclass, the access modifier cannot be more restrictive (weaker) than that of the superclass method. A `protected` method is weaker than a `public` method.
Q3826hardcode output
What is the output of this Java code snippet?
java
public class MultiArrayQ3 {
public static void main(String[] args) {
int[][] original = {{1, 2}, {3, 4}};
int[][] cloned = original.clone();
cloned[0][0] = 99;
cloned[1] = new int[]{5, 6};
System.out.println(original[0][0]);
System.out.println(original[1][0]);
}
}
✅ Correct Answer: A) 1
3
The `clone()` method for multi-dimensional arrays performs a shallow copy. The outer array (`original`) is copied, but its elements (the references to the inner arrays) are copied by value, meaning `original[0]` and `cloned[0]` still point to the same inner array object. Thus, `cloned[0][0] = 99` modifies the inner array referenced by both `original[0]` and `cloned[0]`. However, `cloned[1] = new int[]{5, 6}` makes `cloned[1]` refer to a *new* array, leaving `original[1]` untouched.
Q3827hardcode output
What is the output of this code?
java
class InitOrder {
static { System.out.print("Static A. "); }
{ System.out.print("Instance X. "); }
InitOrder() {
System.out.print("Constructor 1. ");
}
InitOrder(String s) {
System.out.print("Constructor 2 (" + s + "). ");
}
static { System.out.print("Static B. "); }
{ System.out.print("Instance Y. "); }
}
public class Main {
public static void main(String[] args) {
new InitOrder();
new InitOrder("arg");
}
}
✅ Correct Answer: A) Static A. Static B. Instance X. Instance Y. Constructor 1. Instance X. Instance Y. Constructor 2 (arg).
Static blocks run once in order when the class is loaded. Instance initializers run before the constructor body for each new object. Thus, static blocks run first, then for each object, instance initializers run in order, followed by the constructor body.
Q3828hardcode output
What is the output of this code snippet?
java
class Animal {}
class Dog extends Animal {}
class Labrador extends Dog {}
public class Main {
public static void main(String[] args) {
Animal a = new Labrador();
Dog d = (Dog) a;
Labrador l = (Labrador) d;
System.out.println(l.getClass().getSimpleName());
}
}
✅ Correct Answer: A) Labrador
The object created is a `Labrador`. Upcasting to `Animal` and then downcasting to `Dog` and subsequently to `Labrador` is valid because the underlying object is indeed a `Labrador`.
Q3829medium
What is the main advantage of `ReadWriteLock` over a simple `ReentrantLock` for a data structure that is frequently read but rarely written?
✅ Correct Answer: B) It allows multiple reader threads to access the resource concurrently, improving performance.
`ReadWriteLock` allows multiple threads to acquire a read lock concurrently, as long as no thread holds the write lock. This significantly improves concurrency for read-heavy operations compared to `ReentrantLock`, which would serialize all access.
Q3830easycode output
What does this Java code print?
java
public class WrapperImmutability {
public static void main(String[] args) {
Integer val = 100;
val = val + 50;
System.out.println(val);
}
}
✅ Correct Answer: A) 150
Wrapper classes like `Integer` are immutable. When `val + 50` is performed, a new `Integer` object representing `150` is created, and the `val` reference is updated to point to this new object (due to autoboxing and reassigning the reference).
Q3831hard
Given that `java.util.LinkedList` implements the `Deque` interface, what is the primary distinction between the `addFirst(E e)` and `push(E e)` methods?
✅ Correct Answer: C) Both methods are functionally identical for `LinkedList` as it has no capacity restrictions, serving as aliases for adding an element to the front of the list.
For `LinkedList`, which does not have capacity restrictions, `addFirst(E e)` and `push(E e)` are functionally equivalent, both adding an element to the front of the list. They are aliased in the implementation.
Q3832hard
When considering memory usage for an `ArrayList` initialized with a large capacity (e.g., `new ArrayList<>(1000)`), then populated with 50 elements, and subsequently having all 50 elements removed using `remove(0)` repeatedly, what is the memory footprint behavior?
✅ Correct Answer: C) The internal array's capacity remains 1000, as `remove()` operations only clear element references but don't resize down.
Removing elements from an `ArrayList` (even all of them) only sets their references to null and decrements the size, but it does *not* automatically reduce the capacity of the underlying array. The large initial capacity persists until `trimToSize()` is explicitly called.
Q3833mediumcode error
What is the error in this Java code?
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
List<String> cities = Arrays.asList("London", "Paris");
cities.add("Rome"); // Attempt to add to a fixed-size list
System.out.println(cities);
}
}
✅ Correct Answer: C) Runtime Error: `UnsupportedOperationException`.
`Arrays.asList()` returns a fixed-size `List` that is backed by the original array. Operations that modify the size of the list, such as `add()` or `remove()`, are not supported and throw an `UnsupportedOperationException`.
Q3834hardcode error
What error will this Java code most likely encounter given sufficient execution time?
java
public class ThreadBombLoop {
public static void main(String[] args) {
int i = 0;
while (true) {
new Thread(() -> {
try {
Thread.sleep(1000000); // Sleep indefinitely
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
i++;
System.out.println("Started thread " + i);
}
}
}
✅ Correct Answer: A) java.lang.OutOfMemoryError: unable to create new native thread
The `while (true)` loop continuously creates and starts new `Thread` objects. Each thread consumes native operating system resources. Eventually, the JVM will be unable to create new native threads, leading to an `OutOfMemoryError`.
Q3835mediumcode output
What is the output of this code?
java
public class StringBuilderVsString {
public static void main(String[] args) {
String s = "Hello";
StringBuilder sb = new StringBuilder("World");
s.concat(" Java");
sb.append(" Java");
System.out.println(s);
System.out.println(sb);
}
}
✅ Correct Answer: A) Hello
World Java
String objects are immutable, so `s.concat(" Java")` creates a new String but `s` still refers to the original "Hello". `StringBuilder` objects are mutable, so `sb.append(" Java")` modifies the content of the `sb` object in place.
Q3836hardcode error
What error occurs when running this Java code?
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class RemoveIfDuringIteration {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
Integer num = it.next();
if (num % 2 == 0) {
// This modifies the list externally (not via iterator's remove)
nums.removeIf(n -> n.equals(num));
}
}
}
}
✅ Correct Answer: A) java.util.ConcurrentModificationException
Calling a bulk modification method like List.removeIf() on the underlying list while an iterator is actively traversing it (and not using the iterator's own remove() method) constitutes an external structural modification, leading to a ConcurrentModificationException on the subsequent iterator operation.
Q3837medium
What is the result of calling `String.valueOf(null)`?
✅ Correct Answer: C) The string literal "null" is returned.
The `String.valueOf(Object obj)` method is designed to handle null references gracefully. If the object passed is `null`, it returns the string `"null"` rather than throwing an exception. Other `valueOf` overloads for primitive types would typically throw an error if passed a `null` primitive, but not `valueOf(Object)`.
Q3838hard
A thread calls `Object.wait()` without a timeout within a synchronized block. What two crucial things happen simultaneously regarding its state and monitor ownership?
✅ Correct Answer: A) Enters `WAITING` state and releases the monitor.
`Object.wait()` causes the calling thread to enter the `WAITING` state and atomically releases the monitor associated with the object, allowing other threads to acquire it.
Q3839hard
Which of the following statements about throwing `null` is correct in Java?
✅ Correct Answer: C) `throw null;` results in a `NullPointerException` at runtime.
Attempting to throw a `null` reference, i.e., `throw null;`, results in a `NullPointerException` at runtime, as the JVM attempts to dereference the null object to get its type and stack trace.
Q3840easycode error
What compilation error will occur in the following Java code?
java
abstract class Vehicle {
public abstract void start();
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Vehicle();
}
}
✅ Correct Answer: A) Error: Cannot instantiate the type Vehicle
Abstract classes cannot be instantiated directly. An instance can only be created from a concrete subclass that implements all abstract methods.