By default, what character encoding does `FileReader` use to translate bytes read from the file into characters?
✅ Correct Answer: D) The platform's default encoding.
`FileReader` uses the default character encoding of the operating system platform where the Java program is executed. For specific encodings, `InputStreamReader` should be used.
Q1462hard
Which of the following `String` declarations would be invalid as a `case` label in a Java `switch` *statement*?
✅ Correct Answer: D) `final String LABEL = new String("my_label");`
Case labels must be compile-time constants. While `final String LABEL = "my_label";` and `final String LABEL = "my" + "_label";` are compile-time constants, `new String("my_label")` creates a new object at runtime, making it not a compile-time constant, even if the variable `LABEL` itself is `final`.
Q1463easy
What does `HashSet` primarily offer compared to `ArrayList` when managing a collection of items where uniqueness and fast lookups are important?
✅ Correct Answer: B) Automatic removal of duplicate elements and faster constant-time performance for basic operations.
`HashSet` automatically handles uniqueness and provides very efficient, near constant-time performance (O(1)) for `add`, `remove`, and `contains` operations, unlike `ArrayList` which is O(n) for these.
Q1464mediumcode error
What error will occur when compiling and running this Java code?
java
import java.util.HashSet;
import java.util.Set;
public class HashSetError7 {
public static void main(String[] args) {
Set rawSet = new HashSet(); // Raw type
rawSet.add("String Data");
rawSet.add(123); // Add an Integer
for (Object obj : rawSet) {
String s = (String) obj; // ERROR line if obj is Integer
System.out.println(s.toUpperCase());
}
}
}
✅ Correct Answer: B) Runtime Error: java.lang.ClassCastException.
Using a raw type `Set` allows adding heterogeneous objects. However, when iterating and attempting to cast an `Integer` element to a `String`, a `ClassCastException` will be thrown at runtime because an `Integer` cannot be cast to a `String`.
Q1465medium
Consider a `TreeSet<Integer>` named `numbers` containing `{10, 20, 30, 40, 50}`. What would be the result of calling `numbers.headSet(30)`?
✅ Correct Answer: B) A `Set` containing `{10, 20}`
The `headSet(toElement)` method returns a view of the portion of this set whose elements are strictly less than `toElement`. Therefore, it includes elements less than 30 but excludes 30 itself.
Q1466hard
When `clone()` is invoked on a `String[]` array containing references to `String` objects, what is the outcome regarding the array's contents?
✅ Correct Answer: B) A shallow copy is performed, resulting in a new array that contains references to the *same* `String` objects as the original array.
The `clone()` method for arrays performs a shallow copy. For an array of reference types, this means the new array will hold references to the exact same objects that were in the original array.
Q1467hardcode output
What is the output of this code?
java
class CheckedCustomException extends Exception { public CheckedCustomException(String m, Throwable c) { super(m, c); } }
class UncheckedCustomException extends RuntimeException { public UncheckedCustomException(String msg) { super(msg); } }
public class Main {
public static void helperMethod() { throw new UncheckedCustomException("Helper's problem"); }
public static void process() throws CheckedCustomException {
try { helperMethod(); }
catch (UncheckedCustomException e) { System.out.println("Caught Unchecked"); throw new CheckedCustomException("Wrapped as checked", e); }
}
public static void main(String[] args) {
try { process(); }
catch (CheckedCustomException e) {
System.out.println("Caught Checked: " + e.getMessage());
System.out.println("Cause: " + e.getCause().getMessage());
}
}
}
✅ Correct Answer: A) Caught Unchecked
Caught Checked: Wrapped as checked
Cause: Helper's problem
The `helperMethod` throws an `UncheckedCustomException`. The `process` method catches it, prints 'Caught Unchecked', and then wraps it in a `CheckedCustomException` before re-throwing. The `main` method catches this `CheckedCustomException` and retrieves its message and the original cause's message.
Q1468medium
When an `if` statement's condition uses the logical AND operator (`&&`) in Java, what must be true for the entire condition to evaluate to `true`?
✅ Correct Answer: C) Both operands must be `true`.
The logical AND operator (`&&`) requires both its left-hand and right-hand operands to evaluate to `true` for the overall expression to be `true`.
Q1469easy
Can a functional interface contain `default` methods?
✅ Correct Answer: C) Yes, any number of default methods are allowed.
Functional interfaces can contain any number of default methods. These methods have implementations and do not count towards the single abstract method rule.
Q1470medium
What is the outcome of calling the `get()` method on an `Optional` instance that does not contain a value (i.e., `Optional.empty()`)?
✅ Correct Answer: B) It throws a `NoSuchElementException`.
Calling `get()` on an empty `Optional` is an invalid operation and will result in a `NoSuchElementException`. It's crucial to check for presence or use safe retrieval methods.
Q1471easy
Which method is used to add characters or other data types to the end of a `StringBuilder` object?
✅ Correct Answer: C) `append()`
The `append()` method is the primary way to add various types of data to the end of a `StringBuilder`'s character sequence.
Q1472mediumcode error
What is the error in this Java code?
java
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Access an element at an invalid index
System.out.println(numbers.get(numbers.size()));
}
}
✅ Correct Answer: B) Runtime Error: `IndexOutOfBoundsException`.
`numbers.size()` returns the number of elements (3 in this case), but indices are 0 to `size-1`. Accessing `numbers.get(numbers.size())` attempts to access an index out of bounds, leading to an `IndexOutOfBoundsException`.
Q1473mediumcode error
What error occurs when compiling this Java code?
java
public class LoopTest {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
break;
i++;
} while (i < 5);
}
}
✅ Correct Answer: C) error: unreachable statement
The 'break' statement immediately terminates the loop. Any code placed directly after 'break' within the same block is unreachable and will result in a compile-time 'unreachable statement' error.
Q1474hardcode output
What does this code print to the console?
java
public class MultiArrayQ7 {
static void modify(int[][] arr) {
arr[0] = new int[]{10, 20};
arr[1][0] = 50;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2}, {3, 4}};
modify(matrix);
System.out.println(matrix[0][0] + "," + matrix[1][0]);
}
}
✅ Correct Answer: A) 10,50
Java passes array references by value. `arr[0] = new int[]{10, 20}` makes the first element of the `matrix` array (which `arr[0]` refers to) point to a *new* array object. However, `arr[1][0] = 50` modifies the content of the *original* second inner array referenced by both `arr[1]` and `matrix[1]`.
Q1475mediumcode output
What does this code print?
java
import java.io.File;
public class FileCheck {
public static void main(String[] args) {
File file = new File("nonExistentFile.txt");
System.out.println(file.exists() + ", " + file.isFile() + ", " + file.isDirectory());
}
}
✅ Correct Answer: A) false, false, false
The file 'nonExistentFile.txt' does not exist, so `exists()`, `isFile()`, and `isDirectory()` all return `false`.
Q1476mediumcode error
What error will occur when compiling this Java code?
java
public class ConditionCheck {
public static void main(String[] args) {
int x = 10;
if (x = 20) {
System.out.println("Value is 20");
} else {
System.out.println("Value is not 20");
}
}
}
✅ Correct Answer: A) error: incompatible types: int cannot be converted to boolean
In Java, an `if` condition requires a boolean expression. The `=` operator is for assignment, which returns the assigned value (an `int` here), not a `boolean`. The `==` operator is used for comparison.
Q1477hard
Which statement accurately describes a key difference between `volatile` and `synchronized` keywords in Java?
✅ Correct Answer: B) `synchronized` guarantees both visibility and atomicity for compound operations, while `volatile` only guarantees visibility for individual reads/writes.
`synchronized` ensures that only one thread can execute a critical section at a time, providing both visibility of changes and atomicity for operations within the block. `volatile` primarily guarantees visibility of changes to variables across threads and prevents certain types of instruction reordering, but it does not guarantee atomicity for operations involving multiple steps.
Q1478easycode error
What is the result of running this Java code?
java
public class StringError {
public static void main(String[] args) {
String text = "hello";
System.out.println(text.charAt(-1));
}
}
✅ Correct Answer: A) java.lang.StringIndexOutOfBoundsException: String index out of range: -1
The charAt() method requires a non-negative index. Passing a negative index will cause a StringIndexOutOfBoundsException at runtime.
Q1479hard
In a Java program with nested `do-while` loops, if an inner `do-while` loop contains a `break` statement with a label referring to the *outer* `do-while` loop, what is the precise effect?
✅ Correct Answer: B) Both the inner and the labeled outer `do-while` loops are terminated.
A labeled `break` statement transfers control out of the statement specified by the label. In this case, it breaks out of both the inner loop and the labeled outer `do-while` loop.
Q1480mediumcode output
What is the content of 'log.txt' after this code executes?
java
import java.io.FileWriter;
import java.io.IOException;
public class AppendTest {
public static void main(String[] args) {
try {
FileWriter writerA = new FileWriter("log.txt");
writerA.write("Log entry 1.\n");
writerA.close();
FileWriter writerB = new FileWriter("log.txt", true); // Append mode
writerB.write("Log entry 2.\n");
writerB.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: B) Log entry 1.\nLog entry 2.\n
The first FileWriter creates and writes to 'log.txt'. The second FileWriter is opened in append mode (true), so 'Log entry 2.' is added after the existing content, concatenating both entries.