What is the compile-time error in this Java code snippet?
java
public class ArrayTest {
public static void main(String[] args) {
int[] items;
items = new int[3];
System.out.println(items[items.length]);
}
}
✅ Correct Answer: D) No compile-time error, but runtime ArrayIndexOutOfBoundsException
The code will compile successfully as `items` is initialized. However, `items.length` returns 3 for an array of size 3, and valid indices are 0, 1, 2. Accessing `items[3]` will cause an ArrayIndexOutOfBoundsException at runtime.
Q3742medium
How many `null` elements can a `HashSet` store?
✅ Correct Answer: B) One
A `HashSet` can store exactly one `null` element. Like any other object, `null` is considered a unique element within the set.
Q3743medium
What occurs if you call the `charAt(index)` method with an `index` that is less than 0 or greater than or equal to the String's `length()`?
✅ Correct Answer: C) It throws an `IndexOutOfBoundsException`.
The `charAt()` method performs bounds checking. If the provided index is outside the valid range (0 to length-1), it throws an `IndexOutOfBoundsException`.
Q3744easycode error
What kind of error will occur when executing the following Java code?
java
public class Joiner {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.println("Child thread running."));
t.start();
t.join(); // Attempt to join without handling InterruptedException
System.out.println("Child thread finished.");
}
}
✅ Correct Answer: A) Compilation Error: Unhandled exception type InterruptedException.
The `Thread.join()` method, like `Thread.sleep()`, throws a checked exception, `InterruptedException`. This exception must be handled either by catching it or declaring it in the method signature, otherwise it results in a compilation error.
Q3745medium
Consider a Java class `Product` with a field `public double price;`. Which statement best describes the encapsulation of the `price` field?
✅ Correct Answer: B) The `price` field violates encapsulation because it allows direct external modification without control or validation.
Making a field `public` allows any external code to directly read and modify its value, bypassing any intended validation or business rules, thereby violating encapsulation.
Q3746easycode 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 FileError1 {
public static void main(String[] args) {
File file = new File("nonExistentDir/myFile.txt");
try {
file.createNewFile();
System.out.println("File created.");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
✅ Correct Answer: D) An IOException will be caught, printing a message similar to 'No such file or directory' or 'The system cannot find the path specified'.
The `createNewFile()` method throws an `IOException` if the directory specified by the path does not exist. Since 'nonExistentDir' is not created, the `IOException` is caught, and its message is printed.
Q3747medium
Which statement best describes the difference in locking behavior between a `synchronized` instance method and a `synchronized` block on `this` in Java?
✅ Correct Answer: B) Both acquire the same intrinsic lock associated with the current object instance (`this`), making their locking behavior identical for that object.
Both a `synchronized` instance method and a `synchronized(this)` block acquire the intrinsic lock of the object instance on which they are invoked. Therefore, their locking behavior for that specific object is identical.
Q3748easycode error
What type of error will occur when compiling this Java code?
java
public class StaticSynchProblem {
private boolean flag = false;
public static void performStaticSync() {
synchronized (this) { // Attempting to synchronize on 'this' in a static method
System.out.println("Synchronized on 'this'.");
}
}
public static void main(String[] args) {
StaticSynchProblem.performStaticSync();
}
}
✅ Correct Answer: C) Compile-time error: non-static variable this cannot be referenced from a static context
`this` refers to the current instance of an object. In a static context, there is no instance available, so `this` cannot be referenced, resulting in a compile-time error.
Q3749mediumcode output
What is the output of this Java code?
java
import java.util.function.Predicate;
public class MethodRefTest {
public static void main(String[] args) {
String name = "Java";
Predicate<String> checker = name::startsWith;
boolean result = checker.test("J");
System.out.println(result);
}
}
✅ Correct Answer: A) true
The `name::startsWith` method reference points to the `startsWith` instance method of the specific `name` object. When `checker.test("J")` is invoked, it's equivalent to calling `name.startsWith("J")`, which evaluates to true.
Q3750hard
Consider a class `A` with a private constructor and a public static factory method `getInstance()`. What are the implications for its sub-classing?
✅ Correct Answer: B) Class `A` cannot be subclassed because its constructor is private, preventing implicit `super()` calls.
A class with a private constructor cannot be subclassed because a subclass constructor must always invoke a superclass constructor (implicitly or explicitly via `super()`), and a private constructor is not accessible from outside the class.
Q3751medium
When using an `ExecutorService`, which methods are commonly used to submit a `Runnable` task for asynchronous execution?
✅ Correct Answer: C) Both `execute()` and `submit()`
An `ExecutorService` can accept `Runnable` tasks using both its `execute()` method (which doesn't return a result) and its `submit()` method (which returns a `Future` representing the task's completion).
Q3752medium
What is the average time complexity for adding an element at a specific index (not the end) in an `ArrayList`?
✅ Correct Answer: C) O(n)
Adding an element in the middle of an `ArrayList` requires shifting all subsequent elements to the right, which takes O(n) time.
Q3753hard
Which statement correctly characterizes the mutability of `StringBuffer` in a multi-threaded context?
✅ Correct Answer: C) The *contents* of a `StringBuffer` instance are mutable and thread-safe for modifications by multiple threads using its synchronized methods.
`StringBuffer` objects are mutable; their internal character sequence can be changed after creation. The key is that these modifications are made thread-safe by the `synchronized` methods, ensuring that concurrent updates to the *same instance's contents* are handled without data corruption.
Q3754mediumcode error
What compilation error will occur in the following Java code?
java
public class FinalIncrement {
public static void main(String[] args) {
final int count = 5;
count++;
System.out.println(count);
}
}
✅ Correct Answer: A) Cannot assign a value to final variable 'count'
Once a variable is declared `final`, its value cannot be changed. The increment operator `++` attempts to modify the value of `count`, leading to a compilation error.
Q3755easycode error
What is the error in this code?
java
import java.util.Comparator;
import java.util.TreeMap;
class MyStringComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
// Intentionally causes a ClassCastException
return ((Integer)(Object)s1).compareTo((Integer)(Object)s2);
}
}
public class Test {
public static void main(String[] args) {
TreeMap<String, String> map = new TreeMap<>(new MyStringComparator());
map.put("apple", "fruit");
}
}
✅ Correct Answer: A) java.lang.ClassCastException
The custom `MyStringComparator` attempts to cast a `String` (s1) to an `Integer` inside its `compare` method. This cast is illegal and will throw a ClassCastException at runtime when the `put` method calls the comparator to insert the first element.
Q3756mediumcode output
What is the output of this code?
java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Set<Integer> uniqueNums = new HashSet<>();
uniqueNums.add(3);
uniqueNums.add(1);
uniqueNums.add(2);
uniqueNums.add(3); // Duplicate, ignored
int sum = 0;
Iterator<Integer> it = uniqueNums.iterator();
while (it.hasNext()) {
sum += it.next();
}
System.out.println(sum);
}
}
✅ Correct Answer: A) 6
A `HashSet` stores only unique elements; duplicates are ignored. The elements 1, 2, and 3 are added. The iterator then sums these unique elements (1 + 2 + 3 = 6).
Q3757hardcode error
What is the primary resource management error in this Java code?
java
import java.io.*;
public class ResourceLeakWhile {
public static void main(String[] args) {
BufferedReader reader = null;
try {
// Assume 'temp_data.txt' exists for this example
reader = new BufferedReader(new FileReader("temp_data.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("File I/O Error: " + e.getMessage());
}
// Missing reader.close() call
}
}
✅ Correct Answer: A) The file handle (BufferedReader) is not guaranteed to be closed, leading to a resource leak.
The `BufferedReader` `reader` is opened but never explicitly closed. If an `IOException` occurs during file reading or if the program completes successfully, the file handle will remain open, leading to a resource leak. The `reader.close()` call should be in a `finally` block or use try-with-resources.
Q3758easycode error
What kind of error will occur when this Java code is executed?
java
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("123");
sb.insert(4, "45");
System.out.println(sb);
}
}
✅ Correct Answer: A) Runtime Error: java.lang.StringIndexOutOfBoundsException
The `StringBuilder` "123" has a length of 3 (indices 0, 1, 2). Attempting to insert at index 4 (which is greater than the current length) will result in a `StringIndexOutOfBoundsException`.
Q3759easycode output
What is the output of this code?
java
public class DataTypeTest {
public static void main(String[] args) {
char unicodeChar = '€';
int intValue = unicodeChar;
System.out.println(intValue);
}
}
✅ Correct Answer: A) 8364
When a `char` is assigned to an `int`, Java performs an implicit conversion to its Unicode (UTF-16) integer value. The Unicode value for the Euro sign (€) is 8364.
Q3760easycode output
What does this Java code snippet print?
java
public class Settings {
private boolean notificationsEnabled;
public Settings() {
this.notificationsEnabled = false; // Default value
}
public void enableNotifications() {
this.notificationsEnabled = true;
}
public boolean areNotificationsEnabled() {
return notificationsEnabled;
}
public static void main(String[] args) {
Settings s = new Settings();
System.out.println(s.areNotificationsEnabled());
}
}
✅ Correct Answer: A) false
The 'notificationsEnabled' field is explicitly initialized to 'false' in the constructor. Since the 'enableNotifications()' method is never called, the 'areNotificationsEnabled()' method returns the initial default value, 'false'.