import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(1, "One");
map.put(null, "Zero"); // Autoboxing null key
System.out.println(map.containsKey(null));
}
}
✅ Correct Answer: A) java.lang.NullPointerException
Similar to String keys, TreeMap keys must be comparable. A null Integer key cannot be compared, leading to a NullPointerException during insertion because the `put` method will try to compare the null key.
Q802easy
Which of the following represents the correct order of components in a traditional Java `for` loop header?
✅ Correct Answer: B) initialization; condition; increment/decrement
The correct order for a `for` loop header is: initialization (executed once), condition (checked before each iteration), and increment/decrement (executed after each iteration).
Q803medium
Which character encoding does `FileWriter` use by default if not explicitly specified?
✅ Correct Answer: D) The platform's default character encoding.
`FileWriter` is a convenience class that relies on `OutputStreamWriter` to convert characters to bytes. By default, `OutputStreamWriter` uses the platform's default charset.
Q804hardcode output
What does this code print?
java
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String data = "Line1\nLine2\nLine3";
BufferedReader br = new BufferedReader(new StringReader(data));
br.readLine();
br.skip(1);
System.out.println(br.readLine());
br.close();
}
}
✅ Correct Answer: C) ine2
The first readLine() consumes "Line1\n". The stream is now at 'L' of "Line2". skip(1) skips 'L'. The next readLine() reads "ine2\n" and returns "ine2".
Q805mediumcode output
What does this code print?
java
import java.util.TreeMap;
public class TreeMapNullKey {
public static void main(String[] args) {
TreeMap<String, String> map = new TreeMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put(null, "value3");
System.out.println("Map size: " + map.size());
}
}
✅ Correct Answer: C) NullPointerException
A TreeMap does not allow null keys by default because it uses the natural ordering of keys or a provided comparator, neither of which can handle a null key without a NullPointerException.
Q806hardcode output
What does this code print?
java
public class Test {
public static void main(String[] args) {
try {
try {
System.out.print("Try-inner ");
throw new RuntimeException("Exception from try");
} finally {
System.out.print("Finally-inner ");
throw new Error("Error from finally");
}
} catch (Exception e) {
System.out.print("Catch-outer " + e.getMessage());
} catch (Error e) {
System.out.print("Catch-error " + e.getMessage());
} finally {
System.out.print(" Finally-outer");
}
}
}
✅ Correct Answer: A) Try-inner Finally-inner Catch-error Error from finally Finally-outer
If an exception is thrown in the `try` block and another exception is thrown in the `finally` block, the exception from the `finally` block is propagated, and the original exception from the `try` block is suppressed. The `Error` is caught by the second `catch` block.
Q807easycode error
What error will occur when this code is executed?
java
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Testing");
sb.delete(5, 2);
System.out.println(sb);
}
}
✅ Correct Answer: B) StringIndexOutOfBoundsException
The `delete(start, end)` method requires the `start` index to be less than or equal to the `end` index. Since 5 is greater than 2, this call throws a `StringIndexOutOfBoundsException`.
Q808medium
You have an `Optional<User>` and want to transform it into an `Optional<String>` containing the user's email if the `User` is present. Which `Optional` method is most appropriate for this transformation?
✅ Correct Answer: C) `map()`
The `map()` method is used to transform the value inside an `Optional` from one type to another. If the `Optional` is empty, `map()` returns an empty `Optional`.
Q809hardcode error
What error will this code produce at compile time?
java
public class ContinueLabeledBlock {
public static void main(String[] args) {
int counter = 0;
myBlock: {
for (int i = 0; i < 3; i++) {
if (i == 1) {
continue myBlock;
}
counter++;
}
}
System.out.println(counter);
}
}
✅ Correct Answer: A) continue outside of loop
A `continue` statement can only be used to skip to the next iteration of an enclosing loop. Here, `myBlock` is a labeled block, not a loop, thus `continue myBlock` results in a compile-time error.
Q810hardcode error
What compilation error will occur when compiling the following Java code?
java
public class LambdaCaptureError {
public static void main(String[] args) {
int counter = 0;
// counter++; // Uncommenting this line would make it non-effectively final
Runnable r = () -> {
// counter++; // This line causes the error
System.out.println(counter);
};
r.run();
}
}
✅ Correct Answer: A) Error: local variables referenced from a lambda expression must be final or effectively final
Lambda expressions can only capture local variables that are final or effectively final. Attempting to modify a captured local variable (even if it's commented out in its initial state, uncommenting the `counter++` inside the lambda would trigger this) makes it non-effectively final, leading to a compile-time error.
Q811hardcode error
What is the runtime error when `main` method is executed?
java
class MaliciousException extends RuntimeException {
public MaliciousException(String message) {
super(message);
}
@Override
public synchronized Throwable fillInStackTrace() {
// Intentionally throwing an exception during stack trace filling
throw new IllegalStateException("Filling stack trace failed intentionally!"); // This line causes the runtime error
}
}
public class Main {
public static void main(String[] args) {
// Instantiation of MaliciousException triggers its fillInStackTrace() method
MaliciousException me = new MaliciousException("Original problem");
}
}
✅ Correct Answer: B) java.lang.IllegalStateException: Filling stack trace failed intentionally!
When an exception object is created, its `fillInStackTrace()` method is implicitly called. If this method is overridden to throw another exception, that new exception will be the one propagated at runtime when the original exception is instantiated.
Q812hardcode error
What runtime error will this Java code snippet throw?
java
public class Test {
public static void main(String[] args) {
int[][] matrix = new int[3][];
matrix[0] = new int[2];
matrix[1][0] = 5;
System.out.println(matrix[1][0]);
}
}
✅ Correct Answer: A) java.lang.NullPointerException
The inner array `matrix[1]` is declared but not initialized, meaning it holds a `null` reference. Attempting to access an element of a `null` array, like `matrix[1][0]`, results in a `NullPointerException`.
Q813medium
What is the effect of the `continue` statement when encountered inside a `while` loop?
✅ Correct Answer: B) It skips the rest of the current iteration and re-evaluates the loop condition for the next iteration.
The `continue` statement skips the remaining statements in the current iteration of the loop and proceeds to the next iteration by re-evaluating the loop's boolean condition.
Q814easy
To convert all characters in a String to uppercase, which method would you use?
✅ Correct Answer: B) toUpperCase()
The `toUpperCase()` method returns a new String with all of its characters converted to uppercase using the rules of the default locale.
Q815easy
In Java, what type of entity is an array?
✅ Correct Answer: B) Object
In Java, arrays are objects. They are dynamically created, can be assigned to `Object` variables, and their `length` is a public field.
Q816hard
In Java, what is the most precise rule regarding checked exceptions when overriding an instance method in a subclass, particularly concerning polymorphism?
✅ Correct Answer: C) The overriding method can declare no checked exceptions, or it can declare only checked exceptions that are subtypes of the exceptions declared by the overridden method.
An overriding method cannot declare new, broader checked exceptions than those declared by the overridden method. It can declare no checked exceptions, or only checked exceptions that are subtypes of the original, ensuring that the polymorphic contract for exception handling is maintained.
Q817mediumcode output
What does this code print?
java
interface MessagePrinter {
void print();
}
public class LambdaThisScope {
private String message = "Outer class message";
public void runPrinter() {
MessagePrinter printer = () -> {
System.out.println(this.message);
};
printer.print();
}
public static void main(String[] args) {
new LambdaThisScope().runPrinter();
}
}
✅ Correct Answer: A) Outer class message
Unlike anonymous inner classes, `this` inside a lambda expression refers to the `this` of the enclosing class. Therefore, `this.message` correctly accesses the `message` field of the `LambdaThisScope` instance, printing 'Outer class message'.
Q818mediumcode error
What error will occur when running this Java code snippet?
java
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class Test {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("existing", "present");
// Attempt to use computeIfAbsent with a null mapping function
String result = map.computeIfAbsent("newKey", null);
System.out.println(result);
}
}
✅ Correct Answer: A) `NullPointerException`
The `computeIfAbsent` method requires a non-null mapping function. Passing `null` as the `mappingFunction` argument will immediately result in a `NullPointerException` when the method is invoked.
Q819mediumcode error
What is the compilation error in the following Java code?
java
public class InvalidName {
public static void main(String[] args) {
int 1number = 100;
System.out.println(1number);
}
}
✅ Correct Answer: D) Identifier expected
Java variable names must begin with a letter, dollar sign (`$`), or an underscore (`_`). They cannot start with a digit, which violates the identifier rules, resulting in an 'Identifier expected' error.
Q820hard
Which statement correctly differentiates the effect of the `final` keyword when applied to a primitive data type versus a reference data type in Java?
✅ Correct Answer: C) For a primitive type, `final` means its value cannot be reassigned. For a reference type, `final` means the *reference itself* cannot be reassigned to point to a different object.
For a primitive type, `final` makes the stored value constant (it cannot be reassigned). For a reference type, `final` makes the reference itself constant (it cannot be reassigned to point to a different object), but the state of the object it refers to can still be modified if the object is mutable.