What kind of error will occur when running this Java code?
java
public class ArrayError {
public static void main(String[] args) {
int[][] matrix = new int[2][];
matrix[0][0] = 10;
System.out.println(matrix[0][0]);
}
}
✅ Correct Answer: C) Runtime error: NullPointerException
When `new int[2][]` is used, only the outer array is initialized, and its elements (which are references to `int[]` arrays) are set to `null`. Attempting to access `matrix[0][0]` before `matrix[0]` has been initialized to an actual `int[]` array will result in a `NullPointerException`.
✅ Correct Answer: A) Fixed argument: Important info
When an exact match for a fixed number of arguments exists, it is always preferred over a varargs method, even if the varargs method could also accommodate the call.
Q1483medium
To define a custom checked exception in Java, which class should it typically extend?
✅ Correct Answer: C) java.lang.Exception
Custom checked exceptions, which must be declared or caught, should extend `java.lang.Exception`. This forces calling methods to handle the potential error.
Q1484medium
Which pair of methods can a `Serializable` class implement to provide custom serialization and deserialization logic?
✅ Correct Answer: C) `writeObject(ObjectOutputStream out)` and `readObject(ObjectInputStream in)`
The `writeObject` and `readObject` methods, with specific signatures, are special methods that the Java serialization mechanism automatically invokes for custom serialization and deserialization.
Q1485hardcode error
What compile-time error is expected from this Java code?
java
import java.io.IOException;
class DataProcessor {
DataProcessor() {
// Simulating an operation that might throw IOException
boolean errorCondition = true;
if (errorCondition) {
throw new IOException("Failed to initialize");
}
}
}
✅ Correct Answer: A) Error: `unreported exception IOException; must be caught or declared to be thrown`
Constructors that might throw a checked exception (like `IOException`) must either catch it or declare it in their `throws` clause. Failing to do so results in a compile-time error.
Q1486hardcode output
What is the output of this Java code?
java
import java.util.Comparator;
import java.util.TreeMap;
class CustomStringComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
if (s1 == null && s2 == null) return 0;
if (s1 == null) return -1; // Nulls come first
if (s2 == null) return 1; // Non-nulls come after null
return s1.compareTo(s2);
}
}
public class Test {
public static void main(String[] args) {
TreeMap<String, Integer> map = new TreeMap<>(new CustomStringComparator());
map.put("banana", 2);
map.put("apple", 1);
map.put(null, 0); // This is allowed by the comparator
map.put("cherry", 3);
System.out.println(map.firstEntry());
}
}
✅ Correct Answer: A) null=0
The custom `CustomStringComparator` is designed to explicitly handle `null` keys by sorting them before any non-null strings. Therefore, `map.firstEntry()` correctly returns the entry with the `null` key.
Q1487mediumcode error
What error will this Java code produce when executed?
java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
String extra = it.next(); // Attempt to retrieve an element when none left
}
}
✅ Correct Answer: A) java.util.NoSuchElementException
Calling `next()` on an Iterator when `hasNext()` has returned false (or when the collection is exhausted) results in a `NoSuchElementException`.
Q1488medium
For processing an input and performing an action without returning any result, which built-in functional interface should be used?
✅ Correct Answer: B) `java.util.function.Consumer<T>`
The `Consumer<T>` interface provides the abstract method `void accept(T t)`, designed for operations that consume an input parameter but do not produce any return value.
Q1489medium
What are the three main optional parts of a traditional Java `for` loop header, separated by semicolons?
✅ Correct Answer: A) Initialization, Condition, Update
The `for` loop header consists of an initialization expression, a boolean condition, and an update expression, all separated by semicolons.
Q1490hardcode error
What error occurs when attempting to compile the following Java code?
java
public class AssignmentInIf {
public static void main(String[] args) {
int x = 10;
if (x = 20) { // Assignment of int to boolean context
System.out.println("X is 20.");
} else {
System.out.println("X is not 20.");
}
}
}
✅ Correct Answer: B) Compilation error: incompatible types: int cannot be converted to boolean
In Java, the condition inside an `if` statement must be a `boolean` expression. The assignment `x = 20` evaluates to an `int` (the value 20), which cannot be implicitly converted to a `boolean` type, resulting in a compile-time error.
Q1491mediumcode error
Which exception will be thrown when executing this Java code?
java
public class StringError6 {
public static void main(String[] args) {
String prefix = null;
String full = prefix.concat("world");
System.out.println(full);
}
}
✅ Correct Answer: A) java.lang.NullPointerException
The concat() method is called on the 'prefix' object, which is null. This attempt to invoke a method on a null reference triggers a NullPointerException.
Q1492mediumcode error
What is the compilation error in the following Java code?
java
public class ScopeIssue {
public static void main(String[] args) {
if (true) {
String message = "Hello";
}
System.out.println(message);
}
}
✅ Correct Answer: A) Cannot find symbol variable message
The `message` variable is declared within the `if` block, making it a local variable whose scope is limited to that block. It cannot be accessed outside of its declared scope.
Q1493medium
Which pair of classes from `java.io` package are primarily used to perform object serialization and deserialization?
✅ Correct Answer: C) `ObjectOutputStream` and `ObjectInputStream`
`ObjectOutputStream` is used to write Java objects to an OutputStream (serialize), and `ObjectInputStream` is used to read objects from an InputStream (deserialize).
Q1494easycode output
What is the output of this code?
java
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.print("Try block executed. ");
} catch (ArithmeticException e) {
System.out.print("Catch block executed. ");
} finally {
System.out.print("Finally block executed.");
}
}
}
✅ Correct Answer: A) Catch block executed. Finally block executed.
An ArithmeticException occurs in the 'try' block, so control immediately transfers to the matching 'catch' block. After the 'catch' block finishes, the 'finally' block is executed.
Q1495medium
What is a 'race condition' in the context of multithreading, and how does synchronization help prevent it?
✅ Correct Answer: B) A race condition occurs when the order of thread execution affects the program's correctness, and synchronization ensures only one thread accesses shared resources at a time.
A race condition arises when multiple threads access a shared resource, and the outcome depends on the non-deterministic order of operations. Synchronization, through mechanisms like locks, ensures that only one thread can modify the shared resource at any given time, thus preventing race conditions.
Q1496easy
What principle in Object-Oriented Programming allows an object to hide its internal state and require all interaction to be performed through its public methods?
✅ Correct Answer: C) Encapsulation
Encapsulation is the bundling of data (fields) and methods that operate on the data into a single unit (class), restricting direct access to its internal components.
Q1497medium
Which type of method reference is used to refer to a constructor, such as when creating a new `ArrayList` object?
✅ Correct Answer: C) Constructor reference
Constructor references are a specific type of method reference that uses the syntax `ClassName::new` to refer to a class's constructor. This is useful for functional interfaces that define a factory method.
`sb.toString()` creates a *new* `String` object representing the current content of the `StringBuilder`. Modifying `sb` afterwards does not change the `s1` `String` object, which remains "Hello". `s2` is created from the modified `StringBuilder`.
Q1499easy
Where is the condition checked in a `while` loop?
✅ Correct Answer: C) Before the loop body executes.
The `while` loop is an entry-controlled loop, meaning its condition is evaluated before each iteration of the loop body.
Q1500easycode output
What is the output of this code?
java
public class Main {
public static void main(String[] args) {
int score = 75;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 70) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
}
}
✅ Correct Answer: B) Grade B
The first condition `score >= 90` (75 >= 90) is false. The second condition `score >= 70` (75 >= 70) is true, so 'Grade B' is printed and the `if-else if-else` chain terminates.