What is the compilation error in the following Java code snippet?
java
import java.util.ArrayList;
import java.util.List;
public class Question3 {
public static void main(String[] args) {
List<String> myNames = new List<>();
myNames.add("Bob");
System.out.println(myNames);
}
}
✅ Correct Answer: A) Compile error: Cannot instantiate the type List (interface).
`List` is an interface and cannot be instantiated directly. You must instantiate a concrete class that implements `List`, such as `ArrayList`.
Q1002easycode error
What compile-time error does the following Java code exhibit?
java
class SimpleOperations {
public void perform(String operationName) {
System.out.println("Performing " + operationName);
}
public void perform(String operationName) {
System.out.println("Executing " + operationName);
}
}
✅ Correct Answer: A) Compile-time error: Method 'perform(String)' is already defined in 'SimpleOperations'.
This code attempts to define two methods with identical names and parameter lists. This is a direct violation of Java's rule that each method within a class must have a unique signature, leading to a 'method already defined' compile-time error.
Q1003hardcode error
What is the compilation error in the following Java code snippet?
java
import java.util.function.BiFunction;
class Calculator {
public static int add(int a, int b) { return a + b; }
public static long add(long a, long b) { return a + b; }
}
public class Main {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> adder = Calculator::add;
}
}
✅ Correct Answer: A) Reference to 'add' is ambiguous, both 'add(int,int)' and 'add(long,long)' match
The target type `BiFunction<Integer, Integer, Integer>` can be mapped to both `add(int, int)` (via autoboxing) and `add(long, long)` (via autoboxing and widening conversion from int to long). This ambiguity prevents the compiler from selecting a specific method reference.
Q1004hard
How do `sealed` classes and interfaces (introduced in Java 17) enhance or modify the concept of abstraction in Java?
✅ Correct Answer: C) They enable abstraction with a closed hierarchy, explicitly listing which classes or interfaces can extend or implement them, thereby controlling the scope of implementation.
`sealed` classes and interfaces provide fine-grained control over the inheritance hierarchy by explicitly declaring which classes or interfaces are permitted to extend or implement them, offering a more controlled form of abstraction where the set of possible implementations is known and limited.
Q1005hardcode error
What is the compile-time error in the `if` statement?
java
class Gadget {}
class Device {}
public class TypeChecker {
public static void main(String[] args) {
Gadget g = new Gadget();
if (g instanceof Device) { // Line 6
System.out.println("g is a Device");
}
}
}
✅ Correct Answer: A) Incompatible conditional operand types: `Gadget` and `Device` have no inheritance relationship.
The `instanceof` operator can only be used between types where one is a subtype of the other, or they are related by inheritance. Since `Gadget` and `Device` have no inheritance relationship, the compiler knows this comparison is impossible, causing a compile-time error on Line 6.
Q1006easycode error
What kind of error will occur when compiling or running the following Java code snippet?
java
import java.io.File;
public class FileError10 {
public static void main(String[] args) {
File root = new File("/"); // Represents the root directory on Unix-like systems
File parentOfRoot = root.getParentFile();
System.out.println(parentOfRoot.getName());
}
}
✅ Correct Answer: A) A `NullPointerException` at runtime because the root directory has no parent.
The `getParentFile()` method returns `null` if the path does not have a parent (e.g., for the root directory). Attempting to call `getName()` on a `null` reference will result in a `NullPointerException`.
Q1007mediumcode error
What is the compilation error in the given Java code snippet?
java
public class LogicalOperatorError {
public static void main(String[] args) {
int value = 5;
if (value && true) {
System.out.println("This won't compile");
}
}
}
✅ Correct Answer: A) Bad operand types for binary operator '&&'
The logical AND operator `&&` requires both of its operands to be of boolean type. Here, `value` is an `int`, which cannot be implicitly converted to a boolean, causing a compile-time error.
Q1008hardcode output
What is the output of this code?
java
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
public class Test {
public static void main(String[] args) {
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
try {
bw.write("First");
bw.close();
bw.write("Second");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Content: " + sw.toString());
}
}
}
✅ Correct Answer: A) Error: Stream closed
Content: First
Attempting to write to a BufferedWriter after it has been closed will result in an IOException, typically with the message "Stream closed". The 'First' string is written and flushed during bw.close(), but 'Second' is never written to the underlying StringWriter.
Q1009easy
Which `StringBuilder` method can be used to remove a sequence of characters from the builder?
✅ Correct Answer: C) `delete()`
The `delete()` method allows you to remove characters within a specified start and end index from the `StringBuilder`.
Q1010mediumcode error
What kind of exception will this Java code throw during execution?
java
import java.util.Comparator;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Comparator<Object> comp = (o1, o2) -> ((String) o1).compareTo((String) o2);
TreeMap<Object, String> map = new TreeMap<>(comp);
map.put("hello", "World");
map.put(123, "Number");
}
}
✅ Correct Answer: B) java.lang.ClassCastException
The custom Comparator expects keys to be Strings and attempts to cast them. When an Integer (123) is added as a key, the Comparator will try to cast it to a String, which results in a ClassCastException.
Q1011mediumcode error
What compile-time error will occur in this Java code snippet?
java
public class LoopError {
public static void main(String[] args) {
final int x = 0;
for (int i = 0; i < 2; i++) {
x = i;
System.out.println(x);
}
}
}
✅ Correct Answer: A) Compile-time error: Cannot assign a value to final variable 'x'.
The variable 'x' is declared as `final`, meaning its value can only be assigned once. Attempting to reassign `x` within the loop causes a 'cannot assign a value to final variable' compile-time error.
Q1012medium
When a static method is declared `synchronized`, which lock is acquired?
✅ Correct Answer: C) The class-level lock (monitor) associated with the `Class` object of the class.
A `synchronized` static method acquires the intrinsic lock of the `Class` object itself, not the instance of the class. This means only one thread can execute any `synchronized` static method of that class at a time.
Q1013easycode error
What kind of error will occur when compiling this Java code?
java
public class Main {
public static void main(String[] args) {
int x = 5;
if (x = 10) {
System.out.println("X is 10");
}
}
}
✅ Correct Answer: B) Compile-time Error: Incompatible types: int cannot be converted to boolean.
The 'if' condition requires a boolean expression. Using the assignment operator (=) assigns 10 (an int) to x, which cannot be implicitly converted to a boolean for the condition, resulting in a compile-time type mismatch error.
Q1014hardcode output
What is the output of this code? (Assuming Java 14+)
java
public class SwitchTest {
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public static void main(String[] args) {
Day today = Day.MONDAY;
String type = switch (today) {
case MONDAY -> "Start";
case TUESDAY -> "Mid";
// Missing WEDNESDAY case and no default
};
System.out.println(type);
}
}
✅ Correct Answer: D) Compilation error: the switch expression does not cover all possible input values
In Java 14+, `switch` expressions must be exhaustive. For enum types, this means all enum constants must be covered, or a `default` case must be provided. Failing to do so results in a compile-time error.
Q1015medium
Which operation is generally more efficient for `LinkedList` compared to `ArrayList` in Java, assuming an unsorted list?
✅ Correct Answer: C) Insertion or deletion of an element in the middle of the list.
`LinkedList` uses a doubly-linked structure, making insertion and deletion in the middle of the list efficient (O(1) after finding the position). `ArrayList` requires shifting elements, resulting in O(n) complexity for these operations.
Q1016hardcode error
What kind of error will this Java code produce when compiled?
java
final class Settings {
private final String theme;
public Settings(String theme) {
this.theme = theme;
}
public void setTheme(String newTheme) {
this.theme = newTheme; // Attempt to reassign a final field
}
}
public class ImmutableViolation {
public static void main(String[] args) {
Settings appSettings = new Settings("Dark");
appSettings.setTheme("Light");
}
}
✅ Correct Answer: B) A compile-time error: 'cannot assign a value to final variable theme'.
The 'theme' field is declared as 'final', meaning its reference cannot be reassigned after initialization. Attempting to assign a new value in the 'setTheme' method will result in a compile-time error.
Q1017hardcode output
What is the likely output of this code?
java
public class SimpleDeadlock {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
synchronized (lock1) {
System.out.println("T1: Acquired lock1");
try { Thread.sleep(50); } catch (InterruptedException e) {}
synchronized (lock2) {
System.out.println("T1: Acquired lock2");
}
}
}).start();
new Thread(() -> {
synchronized (lock2) {
System.out.println("T2: Acquired lock2");
try { Thread.sleep(50); } catch (InterruptedException e) {}
synchronized (lock1) {
System.out.println("T2: Acquired lock1");
}
}
}).start();
Thread.sleep(200);
System.out.println("Main: Done waiting.");
}
}
✅ Correct Answer: A) T1: Acquired lock1
T2: Acquired lock2
Main: Done waiting.
(Program then hangs indefinitely)
This code demonstrates a classic deadlock. Thread 1 acquires `lock1` and waits for `lock2`. Thread 2 acquires `lock2` and waits for `lock1`. Both threads end up waiting for a resource held by the other, leading to a permanent halt in execution (deadlock). The order of the first two lines might vary, but the deadlock will occur.
Q1018easycode error
What is the error in the following Java code?
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<String> names = new TreeSet<Integer>();
names.add("Charlie");
}
}
✅ Correct Answer: B) The code will not compile due to incompatible generic types.
The `TreeSet` is declared to hold `String` objects (`TreeSet<String>`), but it is being initialized with a `TreeSet<Integer>`. These are incompatible generic types, leading to a compile-time error.
Q1019hardcode error
What will be the result of compiling this Java code?
java
interface MyInterface {
void doSomething();
}
public class Anomaly {
public static void main(String[] args) {
MyInterface mi = new MyInterface() {
public static int count = 0; // Problematic line
@Override
public void doSomething() {
System.out.println("Doing something");
}
};
mi.doSomething();
}
}
✅ Correct Answer: A) Compile-time error: An anonymous class cannot have static declarations.
Anonymous inner classes are treated as non-static contexts. They cannot declare static members themselves, except for `static final` fields initialized with compile-time constant expressions. Since `count` is not `final`, this is a compile-time error.
Q1020medium
When using `wait()` and `notify()` methods for inter-thread communication, what is a crucial requirement for the calling thread?
✅ Correct Answer: C) The calling thread must hold the lock (monitor) of the object on which `wait()` or `notify()` is invoked.
`wait()` and `notify()` (and `notifyAll()`) are `Object` class methods that can only be called from within a synchronized block or method that holds the monitor lock for that specific object, otherwise an `IllegalMonitorStateException` is thrown.