Which line causes a compilation error regarding exception handling?
java
import java.io.IOException;
class Service {
public void performAction() throws IOException {
System.out.println("Performing action...");
}
}
class SpecialService extends Service {
@Override
public void performAction() throws Exception { // Line 10
System.out.println("Performing special action...");
}
}
public class Runner {
public static void main(String[] args) {
Service s = new SpecialService();
// try-catch block for IOException
}
}
✅ Correct Answer: B) Line 10: `public void performAction() throws Exception {`
An overridden method can only throw the same checked exceptions as the superclass method, or a subtype of those exceptions. It cannot throw a new, broader checked exception like `Exception` when the superclass throws `IOException`, causing a compile-time error on Line 10.
Q2202easy
Which access modifier allows members to be accessed within the same package and by subclasses in any package?
✅ Correct Answer: C) protected
The `protected` access modifier allows members to be accessed by any class within the same package and by any subclass (even if it's in a different package).
Q2203easy
What is the underlying data structure that `ArrayList` uses to store its elements?
✅ Correct Answer: C) A dynamic array
`ArrayList` internally uses a dynamic array (an array that can change its size) to store its elements. This allows for fast random access but can be slow for insertions/deletions in the middle.
Q2204easy
Which statement must be the first statement in a constructor if you want to explicitly call a constructor of its superclass?
✅ Correct Answer: B) super()
The `super()` call is used to explicitly invoke a constructor of the immediate superclass, and it must be the first statement in the constructor body.
Q2205hard
Given the following Java class:
java
import java.io.Serializable;
import java.util.Comparator;
class Resolver {
void resolve(Serializable s) { System.out.println("Serializable"); }
void resolve(Comparator c) { System.out.println("Comparator"); }
}
What is the result of compiling and running the following code?
`new Resolver().resolve(null);`
✅ Correct Answer: C) Compilation Error: Ambiguous method call
Both `Serializable` and `Comparator` are interfaces that can accept `null`. Since neither interface is a sub-interface or super-interface of the other, the compiler cannot determine the 'most specific' method for `null`, leading to an ambiguous call.
Q2206easycode output
What is the output of this code?
java
class Base { }
class Derived extends Base { }
public class Main {
public static void main(String[] args) {
Base b = new Derived();
System.out.println(b instanceof Base);
System.out.println(b instanceof Derived);
}
}
✅ Correct Answer: C) true
true
An object of `Derived` type is also an instance of its superclass `Base`. Therefore, both `b instanceof Base` and `b instanceof Derived` evaluate to `true`.
Q2207hard
From an internal JVM perspective, how are generic functional interfaces like `Function<T, R>` often implemented with lambdas, especially considering type erasure and method dispatch?
✅ Correct Answer: C) The compiler generates a synthetic 'bridge method' that performs any necessary type casting (due to type erasure) before calling the actual lambda body method, which is invoked via `invokedynamic`.
While `invokedynamic` dispatches to the lambda's implementation, for generic functional interfaces, the compiler may generate a 'bridge method' to handle type erasure by adapting types (e.g., `Object` to specific type) before delegating to the actual lambda body, ensuring type safety at runtime.
Q2208hardcode error
What compile-time error will this Java code produce?
java
public class OperatorError5 {
public static void main(String[] args) {
int x = 5;
int y = 10;
if (x = y) { // Error line
System.out.println("x is now " + x);
} else {
System.out.println("Condition false");
}
}
}
✅ Correct Answer: B) incompatible types: int cannot be converted to boolean
In Java, conditional expressions within `if`, `while`, or `for` statements must evaluate to a `boolean` type. The assignment `x = y` returns the value assigned to `x` (which is an `int`), and Java does not support implicit conversion from `int` to `boolean`, leading to a compile-time error.
Q2209easy
What is the primary purpose of an `if` statement in Java?
✅ Correct Answer: C) To execute a block of code only if a specified condition is true.
The `if` statement allows for conditional execution, running its code block only when the given boolean expression evaluates to true.
Q2210mediumcode error
What is the result of attempting to compile and run the following Java code?
java
import java.io.IOException;
class MyFaultyTask implements Runnable {
@Override
public void run() throws IOException { // This line
if (true) {
throw new IOException("Simulated I/O error");
}
System.out.println("Task complete.");
}
}
public class Main {
public static void main(String[] args) {
MyFaultyTask task = new MyFaultyTask();
Thread thread = new Thread(task);
thread.start();
}
}
✅ Correct Answer: A) A compilation error: The run() method cannot declare checked exceptions.
The run() method of the Runnable interface (and Thread class) has a signature public void run(). It cannot declare any checked exceptions; if code within run() throws a checked exception, it must be caught inside run().
Q2211easy
What is the main purpose of abstraction in Java?
✅ Correct Answer: A) To hide implementation details and show only necessary features.
Abstraction focuses on 'what' an object does rather than 'how' it does it, by hiding internal implementation and showing only essential information to the user.
Q2212medium
Can a `TreeSet` store `null` elements?
✅ Correct Answer: C) No, attempting to add `null` will generally result in a `NullPointerException`.
A `TreeSet` cannot contain `null` elements. When using natural ordering or a `Comparator` not specifically designed to handle `null`, attempting to add `null` will throw a `NullPointerException` because `null` cannot be compared.
Q2213hard
You have a `TreeMap<MyKey, MyValue>` initialized with `new TreeMap<>(new MyNonSerializableComparator())`, where `MyNonSerializableComparator` does not implement `Serializable`. If you attempt to serialize this `TreeMap` instance using `ObjectOutputStream`, what will happen?
✅ Correct Answer: A) `NotSerializableException` will be thrown during serialization.
For a `TreeMap` with a custom comparator to be serializable, the comparator itself must implement `Serializable`. Otherwise, a `NotSerializableException` will occur during the serialization process.
Q2214hard
Which statement accurately describes the `char` data type in Java?
✅ Correct Answer: B) `char` is a 16-bit unsigned integer type, capable of representing UTF-16 code units.
`char` in Java is a 16-bit unsigned integer type that represents a single UTF-16 code unit. It can store characters from `\u0000` to `\uffff`. Supplementary characters (code points beyond `\uffff`) require two `char` values (a surrogate pair).
Q2215hardcode output
What is the output of this code?
java
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String data = "HelloWorld";
BufferedReader br = new BufferedReader(new StringReader(data));
br.mark(5); // Mark at 'o' (index 5)
br.read(); // H
br.read(); // e
br.reset(); // Should reset to 'o'
System.out.print((char) br.read()); // Read 'o'
System.out.print((char) br.read()); // Read 'W'
br.close();
}
}
✅ Correct Answer: A) oW
The mark() method marks the current position. After reading 'H' and 'e', the internal buffer position moves. reset() restores the stream to the marked position (index 5, character 'o'). Then two more characters ('o', 'W') are read.
Q2216easycode output
Given the Java code, what will be printed?
java
public class Main {
public static void main(String[] args) {
int num = 0;
do {
if (num == 2) {
num++;
continue;
}
System.out.print(num + "-");
num++;
} while (num < 5);
}
}
✅ Correct Answer: A) 0-1-3-4-
The 'do-while' loop executes at least once. When 'num' is 2, the 'continue' statement skips the print statement but 'num' is incremented inside the 'if' block, preventing an infinite loop. Thus, 2 is skipped.
Q2217mediumcode error
What is the compile-time or runtime error in the following Java code snippet when `main` method is executed?
java
import java.io.*;
class Book {
String title = "Java Programming";
}
public class SerializationQuestion2 {
public static void main(String[] args) throws IOException {
Book myBook = new Book();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("book.ser"))) {
oos.writeObject(myBook);
}
}
}
✅ Correct Answer: B) java.io.NotSerializableException: Book
To be eligible for default serialization, a class must implement the `java.io.Serializable` interface. Since the `Book` class does not implement `Serializable`, attempting to serialize an instance of it will throw a `NotSerializableException`.
Q2218easycode error
What is the outcome when compiling and running this Java code?
java
public class LoopError4 {
public static void main(String[] args) {
while (true) {
System.out.println("Looping forever...");
}
System.out.println("Done."); // This code is unreachable
}
}
✅ Correct Answer: A) Compile-time error: Unreachable statement.
A `while(true)` loop creates an infinite loop. Any statement immediately after an infinite loop that doesn't include a `break` or `return` will be considered unreachable code by the Java compiler, resulting in a compile-time error.
Q2219mediumcode output
What is the output of the child thread's state at each observation point?
java
public class ThreadStateDemo10 {
public static void main(String[] args) throws InterruptedException {
Thread childThread = new Thread(() -> {
try {
System.out.println("Child: Starting work.");
Thread.sleep(300); // Child is TIMED_WAITING
System.out.println("Child: Work done.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
System.out.println("Main: Child state (initial): " + childThread.getState());
childThread.start();
System.out.println("Main: Child state (after start): " + childThread.getState());
Thread.sleep(100); // Give child time to enter sleep
System.out.println("Main: Child state (during sleep): " + childThread.getState());
childThread.join(); // Main waits for child to finish
System.out.println("Main: Child state (after join): " + childThread.getState());
}
}
✅ Correct Answer: A) Main: Child state (initial): NEW
Main: Child state (after start): RUNNABLE
Child: Starting work.
Main: Child state (during sleep): TIMED_WAITING
Child: Work done.
Main: Child state (after join): TERMINATED
A thread is NEW before `start()`. After `start()`, it's RUNNABLE. When it calls `Thread.sleep(long)`, it enters TIMED_WAITING. After its `run()` method completes, it transitions to TERMINATED.
Q2220mediumcode error
What is the outcome when this Java code is executed?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<String> stringList = new LinkedList<>();
stringList.add("Hello");
stringList.set(0, 123);
System.out.println(stringList.get(0));
}
}
✅ Correct Answer: D) Compilation Error
The `stringList` is declared to hold `String` objects. Attempting to set an `int` literal (123) into it via `set(0, 123)` causes a compile-time error because `int` cannot be converted to `String`.