What is the compile-time error in this code involving the ternary operator?
java
public class TernaryTypeTest {
public static void main(String[] args) {
int i = 10;
double d = 20.0;
long result = (true ? i : d); // Ternary result type is double, assigned to long
System.out.println(result);
}
}
✅ Correct Answer: A) Error: incompatible types: possible lossy conversion from double to long
The ternary operator's result type is determined by type promotion rules. Since 'd' is a 'double', the entire expression (true ? i : d) evaluates to a 'double'. Assigning this 'double' result to a 'long' variable is a narrowing conversion and requires an explicit cast, causing a compile-time error.
Q162medium
Under what circumstance is a method reference generally considered a more concise alternative to a lambda expression?
✅ Correct Answer: B) When the lambda's only action is to call an existing method by name.
Method references provide a compact syntax for a lambda expression that simply calls an existing method. For instance, `ClassName::methodName` is shorthand for `(args) -> ClassName.methodName(args)`.
Q163medium
What is a primary characteristic of a checked exception in Java?
✅ Correct Answer: B) They must be declared using `throws` in the method signature or handled using `try-catch` blocks.
Checked exceptions are exceptions that are checked at compile-time. The compiler enforces that they must either be caught using a `try-catch` block or declared in the method signature using the `throws` keyword.
Q164easycode error
What kind of error will occur when compiling this Java code?
java
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File file = new File("output.txt");
// BufferedWriter requires a Writer object, not a File object directly
BufferedWriter bw = new BufferedWriter(file);
bw.write("Test data.");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: A) Compile-time error: no suitable constructor found for BufferedWriter(File)
The `BufferedWriter` class's constructors expect an object of type `Writer` (or a subclass like `FileWriter` or `OutputStreamWriter`). It does not have a constructor that directly accepts a `java.io.File` object. Attempting to pass a `File` object directly results in a compile-time error because no suitable constructor is found.
Q165medium
What is the underlying data structure of `java.util.LinkedList`?
✅ Correct Answer: C) A doubly linked list where each node points to both the previous and next nodes.
java.util.LinkedList is implemented as a doubly linked list, meaning each node stores references to both its successor and its predecessor. This structure facilitates efficient insertions and deletions at any point.
Q166hardcode error
What is the result of executing this Java code snippet?
java
public class NullUnboxing {
public static void main(String[] args) {
Integer x = (Integer) null;
int y = x;
System.out.println(y);
}
}
✅ Correct Answer: A) A NullPointerException occurs at runtime.
Casting `null` to `Integer` is valid, so `x` becomes `null`. However, when attempting to assign `x` (which is `null`) to the primitive `int y`, auto-unboxing occurs. Unboxing a `null` wrapper object results in a `NullPointerException`.
Q167hardcode error
What is the runtime error when executing this Java code snippet?
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Number> set = new TreeSet<>();
set.add(10);
set.add(20.5);
System.out.println(set.size());
}
}
✅ Correct Answer: A) java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Comparable
The Number class does not implement Comparable, nor is a custom Comparator provided. When the second element (20.5) is added, TreeSet attempts to compare it with the first (10), leading to a ClassCastException because neither Integer nor Double are directly comparable via a common supertype of Comparable<Number>.
Q168hardcode output
What is the output of this code?
java
import java.util.HashSet;
import java.util.Objects;
class MutableItem {
int value;
public MutableItem(int value) { this.value = value; }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MutableItem that = (MutableItem) o;
return value == that.value;
}
@Override public int hashCode() { return Objects.hash(value); }
}
public class Main {
public static void main(String[] args) {
HashSet<MutableItem> set = new HashSet<>();
MutableItem item1 = new MutableItem(10);
set.add(item1);
item1.value = 20; // Modifying item in set
System.out.println(set.contains(new MutableItem(10)));
System.out.println(set.contains(new MutableItem(20)));
System.out.println(set.size());
}
}
✅ Correct Answer: C) false
false
1
Modifying an object's field (item1.value) after it's added to a `HashSet`, when that field is used in `hashCode()`, corrupts the set's internal structure. The object remains in the bucket determined by its *original* hash code, but `contains(new MutableItem(10))` looks in the '10' bucket, and `contains(new MutableItem(20))` looks in the '20' bucket. Neither finds the object at its expected location.
Q169easy
What is deserialization in Java?
✅ Correct Answer: B) The process of converting a sequence of bytes back into an object.
Deserialization is the reverse operation of serialization, taking a byte stream and reconstructing it into a live Java object in memory.
Q170medium
What is true about `abstract` methods in Java?
✅ Correct Answer: C) They must be overridden by concrete subclasses.
Abstract methods lack an implementation (body) and must be declared in abstract classes or interfaces. A concrete subclass extending an abstract class must provide an implementation for all inherited abstract methods.
Q171easy
Why might a developer choose to create an immutable class over a mutable one for certain data?
✅ Correct Answer: C) To ensure data consistency and prevent unexpected side effects.
Immutability helps in achieving data consistency and predictability. Since an object's state never changes, there are no hidden side effects, making code easier to reason about and debug.
Q172mediumcode error
What is the compilation error in the provided Java code?
java
class Device {
public final void initialize() {
System.out.println("Device initialized.");
}
}
class Smartphone extends Device {
@Override // ERROR: cannot override final method
public void initialize() {
System.out.println("Smartphone initialized.");
}
}
public class Main {
public static void main(String[] args) {
Smartphone s = new Smartphone();
s.initialize();
}
}
✅ Correct Answer: A) Smartphone.java:9: error: initialize() in Smartphone cannot override initialize() in Device; overridden method is final
A method declared as `final` cannot be overridden by subclasses. The `final` keyword prevents any further modification of the method's behavior in child classes, ensuring it remains consistent.
Q173medium
Is it possible to declare and initialize multiple variables in the initialization section of a Java `for` loop, and update multiple variables in the update section?
✅ Correct Answer: A) Yes, by separating them with commas
In the initialization and update sections of a `for` loop, multiple statements or variable declarations/updates can be provided, separated by commas.
Q174hardcode output
What does this code print?
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> original = new ArrayList<>();
original.add("X");
List<String> unmodifiable = Collections.unmodifiableList(original);
original.add("Y");
// unmodifiable.add("Z"); // This line would throw UnsupportedOperationException
System.out.println(unmodifiable.size());
}
}
✅ Correct Answer: B) 2
`Collections.unmodifiableList()` returns an unmodifiable *view* of the original list. It does not create a deep copy. Therefore, any structural modifications (like adding or removing elements) made to the `original` list will be reflected in the `unmodifiable` view. The `unmodifiable` view itself cannot be modified directly. Initially, `original` has "X". Then `unmodifiable` is created. Adding "Y" to `original` means `unmodifiable` now also sees "X", "Y", giving a size of 2.
Q175hard
You're designing a custom exception `InvalidConfigurationException` which needs to carry detailed, immutable context data (e.g., a map of invalid properties and their error messages) about the configuration issue. What is the most robust and thread-safe way to store this data within the exception instance?
✅ Correct Answer: C) Store the context in a `private final Map<String, String>` field, initialized via a constructor parameter, and return an unmodifiable view via a getter.
Using a `private final` field initialized in the constructor ensures immutability once the exception is created. Returning an unmodifiable view prevents external modification of the internal state, making the exception robust and thread-safe with respect to its context data.
Q176mediumcode error
What error will occur when compiling and running this Java code?
java
import java.util.HashSet;
import java.util.Set;
class CustomKey {
private int value;
public CustomKey(int value) {
this.value = value;
}
@Override
public int hashCode() {
if (value == 0) {
throw new IllegalArgumentException("Value cannot be zero for hashing"); // Deliberate error
}
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomKey customKey = (CustomKey) o;
return value == customKey.value;
}
}
public class HashSetError9 {
public static void main(String[] args) {
Set<CustomKey> keys = new HashSet<>();
keys.add(new CustomKey(1));
keys.add(new CustomKey(10));
keys.add(new CustomKey(0)); // ERROR line
}
}
✅ Correct Answer: C) Runtime Error: java.lang.IllegalArgumentException.
When a `CustomKey` object with `value` 0 is added to the `HashSet`, the `HashSet` internally calls the object's `hashCode()` method. The `hashCode()` method explicitly throws an `IllegalArgumentException` if `value` is 0, leading to a runtime error.
Q177hardcode output
What does this code print?
java
public class StringJoinTest {
public static void main(String[] args) {
String[] elements = {"apple", null, "banana", ""};
String result = String.join(" - ", elements);
System.out.println(result);
}
}
✅ Correct Answer: A) apple - null - banana -
`String.join()` handles `null` elements in the provided array or iterable by converting them to the string literal "null". Empty strings are also included as-is.
Q178mediumcode error
What happens when this code is executed?
java
public class LoopTest {
public static void main(String[] args) {
int counter = 0;
while (counter < 3) {
System.out.println("Count: " + counter);
// counter++; // Missing increment
}
System.out.println("Loop Finished");
}
}
✅ Correct Answer: B) The program will run indefinitely, printing 'Count: 0' repeatedly.
The `counter` variable is never incremented inside the loop, causing the condition `counter < 3` to always be true. This results in an infinite loop, continuously printing 'Count: 0'.
Q179easycode error
Which compilation error will occur when compiling the following Java code?
java
import java.util.function.UnaryOperator;
@FunctionalInterface
interface Formatter {
String format(String input);
}
public class Main {
private String prefix = "Format: ";
public static void main(String[] args) {
Formatter formatter = s -> prefix + s;
System.out.println(formatter.format("Data"));
}
}
✅ Correct Answer: B) non-static variable prefix cannot be referenced from a static context
The `main` method is `static`, and it attempts to access the non-static instance variable `prefix` directly within the lambda. Non-static members require an instance of the class to be accessed, which is not available in a static context without creating an object.
Q180medium
What is the guaranteed iteration order of elements (keys or values) when iterating over a `java.util.HashMap`?
✅ Correct Answer: D) There is no guaranteed iteration order for elements.
HashMap does not guarantee any specific order for its elements. The iteration order can even change over time due to operations like rehashing.