What kind of error will occur when compiling and running the following Java code?
java
public class Test {
public static void main(String[] args) {
outer: for (int i = 0; i < 2; i++) {
try {
System.out.println("Try block i: " + i);
} finally {
if (i == 0) {
continue outer;
}
System.out.println("Finally block i: " + i);
}
}
}
}
✅ Correct Answer: A) Compile-time error: 'continue' cannot jump out of a 'finally' block.
Control flow statements like `break`, `continue`, and `return` are not allowed to transfer control out of a `finally` block to an enclosing statement. This restriction ensures that the `finally` block always completes its execution.
Q1522mediumcode error
What is the compilation error in the following code?
java
class Parent {
protected String name;
Parent(String name) { this.name = name; }
}
class Child extends Parent {
Child(String name) {
this.name = name; // Attempt to access name field directly
}
}
✅ Correct Answer: A) Error: implicit super constructor Parent() is undefined for default constructor. Must define an explicit constructor
Every subclass constructor must explicitly or implicitly call a superclass constructor. Since 'Parent' only has a parameterized constructor, 'Child' must explicitly call 'super(name)' as its first statement. The direct assignment to 'this.name' comes after the implicit 'super()' call, which fails.
Q1523easy
What is the default initial capacity of a `StringBuilder` when created using the no-argument constructor `new StringBuilder()`?
✅ Correct Answer: C) 16
By default, when `new StringBuilder()` is called without specifying an initial capacity, it initializes with a capacity of 16 characters.
Q1524mediumcode error
What error does this Java code produce when executed?
java
public class Main {
public static void main(String[] args) {
String message = null;
System.out.println(message.trim());
}
}
✅ Correct Answer: A) java.lang.NullPointerException
Calling the trim() method on a null String reference results in a NullPointerException at runtime. The method can only be invoked on an actual String object, not on null.
Q1525hard
What is the primary purpose of a 'compact constructor' in a Java Record class?
✅ Correct Answer: B) To provide a simplified syntax for custom validation and canonical form adjustments without explicitly listing parameters.
A compact constructor in a Record provides a concise way to add validation or normalize component values without redeclaring the component parameters or manually assigning them to the fields; assignments are implicitly handled after the constructor body.
Q1526hardcode error
What is the result of compiling and running the following Java code snippet?
java
import java.io.UnsupportedEncodingException;
public class StringError {
public static void main(String[] args) {
String data = "sample text";
try {
byte[] bytes = data.getBytes("INVALID-CHARSET");
System.out.println(bytes.length);
} catch (UnsupportedEncodingException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
✅ Correct Answer: B) Prints "Caught: INVALID-CHARSET"
The getBytes(String charsetName) method throws an UnsupportedEncodingException if the named charset is not supported. The code catches this exception and prints its message, which will include the invalid charset name.
Q1527hardcode error
What is the output of this code?
java
import java.io.File;
import java.io.IOException;
public class DeleteOnExitParentDeletion {
public static void main(String[] args) {
File parentDir = new File("dir_for_cleanup");
File nestedFile = new File(parentDir, "nested_file.txt");
try {
parentDir.mkdir();
nestedFile.createNewFile();
nestedFile.deleteOnExit(); // Register only the nested file for deletion
boolean parentDeleted = parentDir.delete(); // Attempt to delete the parent directory immediately
System.out.println("Parent directory deleted immediately: " + parentDeleted);
} catch (IOException e) {
System.out.println("Error: " + e.getClass().getSimpleName() + ": " + e.getMessage());
} finally {
// The nested file will be deleted on JVM exit. The parent won't if it was not empty.
// Manual cleanup if the program didn't exit or parent deletion failed.
nestedFile.delete();
parentDir.delete();
}
}
}
✅ Correct Answer: B) Parent directory deleted immediately: false
The `File.delete()` method can only delete empty directories. Since `nested_file.txt` exists inside `parentDir` (even though it's registered for deletion on exit), `parentDir` is not empty, and thus `parentDir.delete()` will return `false`.
Q1528medium
How does `HashSet` handle an attempt to add a duplicate element?
✅ Correct Answer: C) It ignores the new element, not adding it to the set.
`HashSet` does not allow duplicate elements. If `add()` is called with an element that already exists (determined by `hashCode()` and `equals()`), the method returns `false` and the set remains unchanged.
Q1529easycode error
What is the outcome when compiling and running this Java code?
java
public class IntegerModification {
public static void main(String[] args) {
Integer value = 10;
value.intValue() = 20;
System.out.println(value);
}
}
✅ Correct Answer: A) Compile-time error: "The left-hand side of an assignment must be a variable"
`Integer.intValue()` returns a primitive `int` value, not a reference to modify the internal state of the `Integer` object. `Integer` objects, like other wrapper classes, are immutable in Java.
Q1530easycode error
What happens when you run this Java code?
java
import java.util.Queue;
import java.util.PriorityQueue;
public class QueueError {
public static void main(String[] args) {
Queue<String> pq = new PriorityQueue<>();
pq.add("apple");
pq.add(null);
System.out.println(pq.peek());
}
}
✅ Correct Answer: C) NullPointerException
`PriorityQueue` does not permit `null` elements because it relies on natural ordering or a `Comparator` for element comparison, and `null` cannot be compared, leading to a `NullPointerException`.
Q1531mediumcode output
What is the output of this Java program?
java
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class StreamTest {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Optional<String> result = names.stream()
.filter(s -> s.length() > 5)
.findFirst();
System.out.println(result.orElse("No match"));
}
}
✅ Correct Answer: A) Charlie
The filter `s.length() > 5` matches "Charlie". `findFirst()` returns an `Optional` containing "Charlie". `orElse("No match")` then extracts this value.
Q1532easycode error
What is the runtime error in the following Java code snippet?
java
import java.util.ArrayList;
public class Question5 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add(1, "Java");
System.out.println(list);
}
}
✅ Correct Answer: A) Runtime error: java.lang.IndexOutOfBoundsException.
When using `add(index, element)`, the specified index must be within the bounds `0 <= index <= size()`. For an empty list (size 0), index 1 is out of bounds, leading to an `IndexOutOfBoundsException`.
Q1533easycode error
What kind of error will occur when compiling or running the following Java code snippet?
java
import java.io.File;
import java.io.IOException;
public class FileError9 {
public static void main(String[] args) throws IOException {
File dir = new File("myDir");
dir.mkdir(); // Assume this succeeds
File file = new File("myDir"); // Reusing the same path string
file.createNewFile();
System.out.println("File creation attempted.");
}
}
✅ Correct Answer: C) No error, `createNewFile()` will simply return `false` as `myDir` already exists and is not a regular file.
The `createNewFile()` method attempts to atomically create a new, empty file. If a file or directory with the specified path already exists, `createNewFile()` returns `false` without throwing an `IOException`. It does not attempt to overwrite or change the type of an existing entry.
Q1534easy
Which keyword, when applied to a method, prevents it from being overridden by any subclass?
✅ Correct Answer: C) `final`
The `final` keyword explicitly prevents a method from being overridden by any subclass, ensuring its implementation remains unchanged.
Q1535mediumcode output
What does this Java code print to the console?
java
import java.io.BufferedWriter;
import java.io.StringWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
bw.write("Line 1");
bw.newLine();
bw.write("Line 2");
bw.close();
System.out.print(sw.toString());
}
}
✅ Correct Answer: A) Line 1\nLine 2
The `newLine()` method inserts a platform-specific line separator, which is typically `\n` on Unix-like systems (including common development environments) and `\r\n` on Windows. The most general output for `\n` is represented here.
Q1536hard
When a `break` statement is encountered within a `try` block nested inside a loop, what is the sequence of execution concerning an associated `finally` block before the loop is exited?
✅ Correct Answer: B) The `finally` block is guaranteed to execute before the `break` statement causes the loop to be exited.
Regardless of how a `try` block is exited (normally, via `return`, `break`, `continue`, or an exception), its associated `finally` block is always guaranteed to execute. Therefore, the `finally` block will run before the `break` fully exits the loop.
Q1537mediumcode error
What exception will be thrown when running this Java code snippet?
java
import java.util.PriorityQueue;
import java.util.Queue;
public class QueueError {
public static void main(String[] args) {
Queue<Integer> pq = new PriorityQueue<>();
pq.element(); // Attempt to retrieve but not remove from an empty queue
}
}
✅ Correct Answer: A) NoSuchElementException
The `element()` method of the `Queue` interface (implemented by `PriorityQueue`) throws a `NoSuchElementException` if the queue is empty. In contrast, `peek()` would return `null`.
Q1538medium
Consider a `do-while` loop where the loop condition is initially `false`. How many times will the loop body execute?
✅ Correct Answer: B) One time.
A `do-while` loop guarantees at least one execution because its condition is checked after the first iteration, even if the condition is `false` from the start.
Q1539hard
Consider a statement placed immediately after an unconditional `break` statement within a loop (e.g., `while(true) { break; System.out.println("Unreachable"); }`). What is the Java compiler's assessment of this subsequent statement's reachability?
✅ Correct Answer: C) The subsequent statement is always considered unreachable, leading to a compile-time error.
According to Java's reachability rules, a statement immediately following an unconditional `break` within the same code block (loop iteration) is considered unreachable. The Java compiler will detect this and issue a compile-time error, as the code can never be executed.
Q1540easy
What is the primary purpose of serialization in Java?
✅ Correct Answer: A) To convert an object into a sequence of bytes for storage or transmission.
Serialization is the process of converting an object into a byte stream, which allows it to be stored in a file or transmitted over a network.