What error will occur when compiling the following Java code?
java
public class Main {
public static void main(String[] args) {
int x = 5;
if (x = 10) {
System.out.println("X is 10");
} else {
System.out.println("X is not 10");
}
}
}
✅ Correct Answer: B) Compilation Error: `Incompatible types: int cannot be converted to boolean`
The `=` operator is an assignment operator, not a comparison operator. The `if` statement requires a boolean expression, but `x = 10` evaluates to an int (10), causing a compilation error.
Q3202easy
Which type of polymorphism is achieved through method overloading in Java?
✅ Correct Answer: A) Compile-time polymorphism
Method overloading is resolved by the compiler based on the method signature, making it an example of compile-time (or static) polymorphism.
Q3203hardcode error
What is the result of compiling and running the following Java code snippet?
java
public class StringError {
public static void main(String[] args) {
String greeting = "Hi";
System.out.println(greeting.substring(3));
}
}
✅ Correct Answer: C) Throws StringIndexOutOfBoundsException
The substring(int beginIndex) method requires the beginIndex to be less than or equal to the length of the string. 'Hi' has a length of 2. Passing 3 as the beginIndex (3 > 2) results in a StringIndexOutOfBoundsException.
Q3204mediumcode output
What will the following Java code print to the console?
java
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Set<String> set1 = new HashSet<>(Arrays.asList("A", "B", "C"));
Set<String> set2 = new HashSet<>(Arrays.asList("B", "D", "E"));
set1.addAll(set2);
System.out.println(set1.size());
}
}
✅ Correct Answer: B) 5
The `addAll()` method adds all elements from `set2` to `set1`. Since `HashSet` does not allow duplicate elements, 'B' (which is present in both sets) is added only once. The resulting set will contain A, B, C, D, E, leading to a size of 5.
Q3205easy
Which interface does `java.util.ArrayList` primarily implement?
✅ Correct Answer: C) List
The `ArrayList` class implements the `List` interface, which is a subinterface of `Collection` and defines methods for ordered collections (sequences).
Q3206mediumcode output
What is the output of this code?
java
class Building {
{
System.out.println("Instance Initializer Block 1");
}
public Building() {
System.out.println("Constructor called");
}
{
System.out.println("Instance Initializer Block 2");
}
}
public class Main {
public static void main(String[] args) {
Building b = new Building();
}
}
✅ Correct Answer: A) Instance Initializer Block 1
Instance Initializer Block 2
Constructor called
Instance Initialization Blocks (IIBs) are executed every time an object is created, right before the constructor. If there are multiple IIBs, they execute in the order they appear in the class definition.
Q3207hard
Consider a `Parent` class with a method `doWork()` and a `Child` class extending `Parent` that overrides `doWork()`. If `Parent p = new Child();` and then `((Child) p).doWork();` is called, which `doWork()` method is executed?
✅ Correct Answer: B) The `doWork()` method defined in `Child` due to dynamic method dispatch.
Java employs dynamic method dispatch (or virtual method invocation), meaning the actual method invoked is determined by the runtime type of the object, not the compile-time type of the reference or the explicit cast. Since `p` refers to a `Child` object, the `Child`'s overridden `doWork()` method is executed.
Q3208mediumcode error
What error will this Java code produce when executed?
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("One", "Two", "Three"));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String current = it.next();
if (current.equals("Two")) {
list.add("Four"); // Direct modification of the list during iteration
}
}
}
}
✅ Correct Answer: C) java.util.ConcurrentModificationException
Adding an element to the list directly while iterating over it using an `Iterator` causes a `ConcurrentModificationException` when the iterator detects the modification.
Q3209easycode error
What is the error in the following Java code?
java
public class Main {
public static void main(String[] args) {
Integer num = 50;
String str = (String) num;
System.out.println(str);
}
}
✅ Correct Answer: A) Compile-time error: Inconvertible types: cannot cast java.lang.Integer to java.lang.String.
You cannot directly cast an Integer object to a String object. These are distinct classes without a direct inheritance relationship, leading to a compile-time error.
Q3210easycode error
What is the compile-time error in this Java code snippet?
java
public class ArrayTest {
public static void main(String[] args) {
int[][] matrix = new int[][3];
}
}
✅ Correct Answer: A) Compile-time error: array dimension missing
When declaring a multi-dimensional array and only specifying the second dimension, the first dimension must also be specified. The syntax `new int[][3]` is invalid; it should be `new int[rows][3]` or `new int[rows][]`.
Q3211easy
What is the primary purpose of the `Iterator` interface in Java?
✅ Correct Answer: B) To provide a standard way to traverse elements in a collection.
The `Iterator` interface defines methods for iterating over a collection's elements, providing a universal way to access them sequentially.
Q3212hardcode error
What error occurs when running this Java code?
java
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class ListIteratorSetAfterAdd {
public static void main(String[] args) {
List<String> list = new LinkedList<>(Arrays.asList("A", "B"));
ListIterator<String> listIterator = list.listIterator();
listIterator.next(); // Moves past A
listIterator.add("X"); // Adds X after A
listIterator.set("Y"); // Attempts to set the element
System.out.println(list);
}
}
✅ Correct Answer: C) java.lang.IllegalStateException
The ListIterator's set() method can only be called after a call to next() or previous(). Calling add() invalidates the 'last element returned' state required by set(), causing an IllegalStateException.
Q3213easy
In method overloading, what defines the method signature?
✅ Correct Answer: B) Method name and parameter list.
For the purpose of method overloading, the method signature consists solely of the method name and its parameter list. The return type, access modifiers, and exception declarations are not part of the signature used for overloading.
Q3214hardcode error
What is the compilation error, if any, for the provided Java code snippet?
java
class Overloader {
public int calculate(String s) { return 1; }
public String calculate(String s) { return "1"; } // Line X
public static void main(String[] args) {
Overloader o = new Overloader();
}
}
✅ Correct Answer: B) error: method calculate(String) is already defined in class Overloader
Method overloading is determined solely by the method name and parameter types (the method signature). Changing only the return type does not constitute overloading. The compiler sees two methods with the exact same signature `calculate(String s)`, resulting in a 'method already defined' error.
Q3215hard
Which statement accurately describes the memory layout of a `int[][]` array in Java?
✅ Correct Answer: B) It's an array of references, where each reference points to a separate `int[]` array, which themselves are contiguous blocks of `int`s.
Java's multi-dimensional arrays are 'arrays of arrays.' A `int[][]` is an array whose elements are references to `int[]` arrays, and each `int[]` is a contiguous block of memory for its primitive elements.
Q3216easycode error
What compile-time error will occur in the `main` method?
java
class SpecificException extends Exception {
public SpecificException(String message) { super(message); }
}
public class Main {
public static void operation() throws SpecificException {
throw new SpecificException("Detail issue");
}
public static void main(String[] args) {
try {
operation();
} catch (Exception e) {
System.out.println("Caught generic: " + e.getMessage());
} catch (SpecificException e) {
System.out.println("Caught specific: " + e.getMessage());
}
}
}
✅ Correct Answer: A) error: exception SpecificException has already been caught
When catching multiple exceptions, more specific exception types must be caught before more general ones. `Exception` is a superclass of `SpecificException`, so `catch (Exception e)` will catch `SpecificException` first, making the subsequent `catch (SpecificException e)` unreachable.
Q3217hard
What happens if you iterate over a `java.util.List` declared as a raw type (e.g., `List rawList = new ArrayList<String>();`) using an enhanced `for` loop, attempting to assign elements to a specific type (e.g., `for (String s : rawList)`)?
✅ Correct Answer: B) It will compile with an 'Unchecked cast' warning, and if `rawList` contains non-String objects, it will throw a `ClassCastException` at runtime.
When iterating a raw type `List` with an enhanced `for` loop expecting a specific type, the compiler inserts an implicit cast. This results in an 'Unchecked cast' warning at compile-time and a `ClassCastException` at runtime if the list contains an element that cannot be cast to the specified type.
Q3218mediumcode error
What compile-time error will occur in this Java code snippet?
java
public class LoopError {
public static void main(String[] args) {
for (int i = 0; i < 3; i++); {
System.out.println(i);
}
}
}
✅ Correct Answer: A) Compile-time error: 'i' cannot be resolved to a variable.
The semicolon after `for (int i = 0; i < 3; i++)` makes the loop body an empty statement. The subsequent block `{ System.out.println(i); }` is executed after the loop, but 'i' is out of scope, causing a 'cannot be resolved to a variable' compile-time error.
Q3219medium
If an exception is thrown in the `try` block, handled by a `catch` block, and then a *new* exception is thrown within the `finally` block, which exception will be propagated out of the method?
✅ Correct Answer: B) The exception thrown from the `finally` block.
If an exception occurs in the `finally` block, it will supersede any pending exception from the `try` or `catch` block, becoming the exception that is propagated out of the method.
Q3220medium
When using a method reference, what is the primary factor the Java compiler uses to infer which specific method is being referenced, especially in cases of method overloading?
✅ Correct Answer: C) The signature (number and types of parameters, and return type) of the functional interface's abstract method.
The compiler uses the target type, which is the functional interface's abstract method signature, to determine which overloaded method is best suited for the method reference. This ensures type compatibility.