Under which specific circumstance will a `finally` block in a `try-catch-finally` construct *not* be executed?
✅ Correct Answer: C) When `System.exit(0)` is called within the `try` or `catch` block.
The `finally` block is almost always executed. The most common exception to this rule is when the JVM itself terminates, for example, by calling `System.exit()`.
Q2942mediumcode error
What kind of error will occur when compiling this Java code?
java
public class ArrayError {
public static void main(String[] args) {
int[] myNumbers;
myNumbers = {1, 2, 3};
System.out.println(myNumbers[0]);
}
}
✅ Correct Answer: A) Compile-time error: 'array initializer is not allowed here'.
The shorthand array initializer syntax `{}` can only be used during the declaration of an array variable. When assigning to an already declared array variable, you must use the `new` keyword, e.g., `myNumbers = new int[]{1, 2, 3};`. This causes a compile-time error.
Q2943hardcode output
What is the output of this code?
java
class BusinessLogicException extends Exception { public BusinessLogicException(String msg) { super(msg); } }
class ResourceCloseException extends RuntimeException { public ResourceCloseException(String msg) { super(msg); } }
class MyResource implements AutoCloseable {
public void doWork() throws BusinessLogicException { System.out.println("Working"); throw new BusinessLogicException("Error in work"); }
public void close() { System.out.println("Closing"); throw new ResourceCloseException("Failed to close"); }
}
public class Main {
public static void main(String[] args) {
try (MyResource res = new MyResource()) { res.doWork(); }
catch (BusinessLogicException e) {
System.out.println("Main: " + e.getMessage());
for (Throwable t : e.getSuppressed()) { System.out.println("Suppressed: " + t.getMessage()); }
}
}
}
✅ Correct Answer: A) Working
Closing
Main: Error in work
Suppressed: Failed to close
The `try-with-resources` statement ensures `MyResource.close()` is called. If an exception occurs in the `try` block (`BusinessLogicException`) and another in the `close()` method (`ResourceCloseException`), the exception from the `close()` method is added as a suppressed exception to the primary exception (`BusinessLogicException`). Both `Main` and `Suppressed` messages are printed.
Q2944mediumcode error
What type of error will occur when executing this Java code?
java
import java.util.*;
public class LoopTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("B")) {
list.add("D"); // Modifying collection directly during iteration
}
System.out.println(element);
}
}
}
✅ Correct Answer: B) A java.lang.ConcurrentModificationException.
When a collection is modified directly (e.g., using `list.add()`) while it is being iterated over by an `Iterator` (except through the iterator's own `remove()` method), Java's fail-fast iterators detect this concurrent modification and throw a `ConcurrentModificationException`.
Q2945medium
Why is it generally recommended to use immutable objects as keys in a `HashMap`?
✅ Correct Answer: B) It prevents the hash code of a key from changing after it has been inserted into the map, ensuring it can always be retrieved.
If a mutable object's hash code changes after it's been used as a key, `HashMap` may no longer be able to find the corresponding value because it will look in the wrong bucket.
Q2946hardcode error
What is the compilation error in the following Java code?
java
public class InitExample {
public static void main(String[] args) {
int value;
boolean condition = false;
if (condition) {
value = 10;
}
System.out.println(value);
}
}
✅ Correct Answer: A) Error: variable value might not have been initialized.
Local variables in Java must be explicitly initialized before use. The compiler cannot guarantee that `value` will be assigned a value because the `if` condition might be false.
Q2947hardcode output
What is the output of this code?
java
public class EffectivelyFinal {
public static void main(String[] args) {
int counter = 0;
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("Task counter: " + counter);
}
};
counter = 5; // This line modifies 'counter'
task.run();
}
}
✅ Correct Answer: C) Compilation Error
Local variables accessed from an anonymous inner class (or lambda) must be 'effectively final'. Modifying `counter` after its declaration (`counter = 5;`) makes it not effectively final, thus causing a compilation error when accessed by the `Runnable`.
Q2948easycode error
Which exception will be thrown when running the following Java code snippet?
java
import java.util.ArrayList;
import java.util.Arrays;
public class IteratorError {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String s : list) { // Enhanced for loop uses an Iterator internally
if (s.equals("B")) {
list.remove(s); // Modifying list directly inside enhanced for loop
}
}
}
}
✅ Correct Answer: A) java.util.ConcurrentModificationException
An enhanced for loop uses an Iterator internally. Modifying the underlying collection directly (`list.remove(s)`) while iterating over it with an internal iterator will result in a `ConcurrentModificationException`.
Q2949hardcode output
What does this code print?
java
public class StringReplaceTest {
public static void main(String[] args) {
String text = "abracadabra";
String result = text.replaceAll("(a|b)", "$1$1");
System.out.println(result);
}
}
✅ Correct Answer: B) aabbrraaccaaddaarraa
The regex `(a|b)` matches either 'a' or 'b'. The replacement string `$1$1` uses a backreference to the first capturing group, effectively doubling each matched 'a' or 'b' character. Thus 'a' becomes 'aa', 'b' becomes 'bb'.
Q2950easy
Consider the following method signature: `public void processFile() throws IOException`. What does `throws IOException` signify?
✅ Correct Answer: C) The `processFile` method might throw an `IOException`, and callers must handle or re-declare it.
The `throws IOException` clause indicates that the `processFile` method itself does not handle `IOException` but might propagate it, requiring its callers to manage it.
Q2951easy
When a subclass inherits from a superclass, which members of the superclass are generally NOT inherited?
✅ Correct Answer: B) Private fields
Private members of a superclass are not directly inherited by the subclass. While they exist in the superclass object part, they are not accessible or visible to the subclass.
Q2952medium
What is the key difference in memory allocation between static variables and instance variables in Java?
✅ Correct Answer: B) Static variables are allocated once per class, while instance variables are allocated per object.
Static variables belong to the class and are shared by all instances, so they are allocated once. Instance variables belong to specific objects and are allocated each time a new object is created.
Q2953hard
In Java 14 and later, when using a `switch` *expression* with an `int` selector, what happens if not all possible `int` values are covered by `case` labels and there is no `default` branch?
✅ Correct Answer: C) A compile-time error occurs because the `switch` expression is not exhaustive.
Switch expressions in Java are designed to be exhaustive, meaning all possible input values must be handled. For non-enum types like `int`, if not all theoretical values are explicitly covered by `case` labels, a `default` branch is mandatory to satisfy exhaustiveness, otherwise a compile-time error occurs.
Q2954easy
Which method of the `Thread` class should be overridden to define the code that the thread will execute?
✅ Correct Answer: D) run()
The `run()` method contains the code that is executed by the thread when it starts. This method is typically overridden in a class extending `Thread`.
Q2955easycode error
What compile-time error will occur in the `MyClass()` constructor?
java
class MyClass {
int x;
MyClass() {
x = 10;
this(20); // Not the first statement
}
MyClass(int x) {
this.x = x;
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
}
}
✅ Correct Answer: A) call to this must be first statement in constructor
A constructor chaining call using `this()` must be the very first statement in the constructor body. Any other statement before it will cause a compile-time error.
Q2956easy
Which of the following correctly declares and initializes a 2D array `matrix` with specified values?
✅ Correct Answer: D) Both a and b
Both `int[][] matrix = {{1,2},{3,4}};` (shorthand) and `int[][] matrix = new int[][]{{1,2},{3,4}};` are valid ways to declare and initialize a 2D array with specific values. The size declaration `[2][2]` is not needed when directly providing the values.
Q2957medium
What is a fundamental difference between a `switch` *statement* and a `switch` *expression* (introduced in Java 14)?
✅ Correct Answer: B) A `switch` expression can return a value, whereas a `switch` statement cannot.
A `switch` expression is designed to compute a single value, which it then returns. A `switch` statement, on the other hand, is for control flow and does not produce a value.
Q2958mediumcode output
What is the expected output of the following Java program?
java
public class LambdaThread {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
thread.start();
thread.join(); // Ensures the thread finishes before main exits
}
}
✅ Correct Answer: A) Thread is running
A lambda expression is used to implement the `Runnable` functional interface for a new `Thread`. The `thread.start()` method starts the execution, and `thread.join()` ensures the main thread waits for the new thread to complete, printing 'Thread is running'.
Q2959hardcode error
What is the compile-time error in this Java code?
java
public class DirectRunnableInstantiation {
public static void main(String[] args) {
Runnable myTask = new Runnable(); // Line 3
myTask.run();
}
}
✅ Correct Answer: A) Compile-time error: 'Runnable' is abstract; cannot be instantiated (at Line 3)
`Runnable` is an interface, which is inherently abstract and cannot be instantiated directly. To create a `Runnable` object, you must either implement it in a class or use an anonymous inner class or a lambda expression.
Q2960easycode error
What will happen when this Java code is compiled and executed?
java
class MyClass {
public void testMethod() {
try {
// No code here that throws IOException
} catch (java.io.IOException e) {
System.out.println("Caught an IO Exception");
}
}
}
✅ Correct Answer: A) Compilation Error
For checked exceptions, if the `try` block contains no code that could possibly throw the specified exception, the `catch` block is considered unreachable. The Java compiler detects this and reports a compilation error.