Which error will occur when compiling this Java code?
java
import java.io.FileReader;
import java.io.FileNotFoundException;
public class FileReaderIssue {
public static void main(String[] args) throws FileNotFoundException {
FileReader reader = new FileReader("existing.txt"); // Assume existing.txt exists
int data = reader.read(); // Potential IOException
System.out.println(data);
}
}
✅ Correct Answer: B) A compile-time error: unreported exception java.io.IOException; must be caught or declared to be thrown.
The `read()` method of FileReader can throw an `IOException`, which is a checked exception. Even though `FileNotFoundException` is declared to be thrown, `IOException` from `read()` is not, leading to a compile-time error.
Q742hard
FileWriter is a character stream designed for convenience. Which statement accurately describes its default character encoding behavior?
✅ Correct Answer: B) It uses the platform's default character encoding, which can be retrieved via `Charset.defaultCharset()` or `System.getProperty("file.encoding")`.
FileWriter is a convenience class built on OutputStreamWriter that defaults to using the platform's default character encoding. This can lead to encoding issues if the file is read on a system with a different default charset.
Q743hard
Consider an `ArrayList` named `originalList`. A `List` `subList` is created using `originalList.subList(0, 5)`. If `originalList.add(10)` is called after `subList` is created, what happens when you then try to perform an operation on `subList`?
✅ Correct Answer: C) A `ConcurrentModificationException` is likely thrown because `originalList` was structurally modified.
A `SubList` provides a view of a portion of the original list. Structural modifications to the backing list (e.g., `originalList.add(10)`) invalidate the `SubList` view, and subsequent operations on the `SubList` will typically result in a `ConcurrentModificationException`.
Q744hardcode output
What does this code print?
java
public class ArrayFieldInitialization {
static int[] staticArr;
int[] instanceArr;
public static void main(String[] args) {
ArrayFieldInitialization obj = new ArrayFieldInitialization();
System.out.println(staticArr == null);
System.out.println(obj.instanceArr == null);
int[] localArr = new int[0];
System.out.println(localArr.length);
staticArr = new int[]{1, 2, 3};
System.out.println(staticArr[0]);
}
}
✅ Correct Answer: A) true
true
0
1
Static and instance array fields are initialized to `null` by default. Local variables (like `localArr`) are not automatically initialized but are explicitly assigned an empty array here. Finally, `staticArr` is reassigned, and its first element `staticArr[0]` is 1.
Q745medium
What is the primary difference in behavior when creating an `Optional` using `Optional.of(value)` versus `Optional.ofNullable(value)`?
✅ Correct Answer: A) `Optional.of(value)` throws a `NullPointerException` if `value` is `null`, while `Optional.ofNullable(value)` returns an empty `Optional`.
`Optional.of()` expects a non-null value and throws an exception if `null` is passed. `Optional.ofNullable()` is designed to handle potentially null values gracefully by returning an empty `Optional` for `null`.
Q746medium
What is the primary benefit of using `BufferedReader` over a plain `FileReader` for reading text files?
✅ Correct Answer: C) It buffers input, reducing the number of direct I/O operations and improving performance.
BufferedReader's main advantage is buffering. It reads larger blocks of data into memory at once, reducing the frequency of slower disk I/O operations and improving overall read performance.
Q747hardcode error
What is the runtime error when executing this Java code snippet?
java
import java.util.TreeSet;
import java.util.Collections;
import java.util.SortedSet;
public class Main {
public static void main(String[] args) {
TreeSet<String> originalSet = new TreeSet<>();
originalSet.add("Alpha");
originalSet.add("Beta");
SortedSet<String> unmodifiableSet = Collections.unmodifiableSortedSet(originalSet);
unmodifiableSet.add("Gamma");
System.out.println(unmodifiableSet.size());
}
}
✅ Correct Answer: B) java.lang.UnsupportedOperationException
Collections.unmodifiableSortedSet returns a view of the original set that prohibits modification. Attempting to add an element to this unmodifiable view results in an UnsupportedOperationException at runtime.
Q748hardcode output
What is the output of this code?
java
class Base {
void foo() {
System.out.println("Base foo");
}
Base() {
foo(); // Call to an overridden method in constructor
}
}
class Derived extends Base {
String message = "Derived foo";
@Override
void foo() {
System.out.println(message);
}
}
public class Main {
public static void main(String[] args) {
new Derived();
}
}
✅ Correct Answer: C) null
When `new Derived()` is called, `Base`'s constructor runs first. Inside `Base`'s constructor, `foo()` is called polymorphically, executing `Derived`'s `foo()`. At this point, `Derived`'s fields (like `message`) have not yet been initialized, so `message` is `null`, resulting in 'null' being printed.
Q749easycode output
What does this code print?
java
public class StringTest {
public static void main(String[] args) {
String s = "Sunshine";
System.out.println(s.startsWith("Sun"));
}
}
✅ Correct Answer: A) true
The `startsWith(String prefix)` method tests if this string starts with the specified prefix. Since "Sunshine" begins with "Sun", it returns `true`.
Q750hardcode output
What is the output of this code?
java
class Animal { public Animal getSelf() { return this; } }
class Dog extends Animal { @Override public Dog getSelf() { return this; } }
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
Animal returnedAnimal = a.getSelf();
System.out.println(returnedAnimal instanceof Dog);
System.out.println(returnedAnimal instanceof Animal);
}
}
✅ Correct Answer: A) true
true
The `getSelf()` method in `Dog` uses a covariant return type, returning `Dog`. When called on an `Animal` reference pointing to a `Dog` object, the `Dog`'s overridden method is invoked, returning a `Dog` instance. Thus, it is an instance of both `Dog` and `Animal`.
Q751easycode output
What does this Java code print?
java
public class StringReassignmentTest {
public static void main(String[] args) {
String message = "Start";
message = message + " End";
System.out.println(message);
}
}
✅ Correct Answer: A) Start End
Although String is immutable, the variable `message` is not final. The line `message = message + " End";` creates a new String object with the concatenated value and reassigns the `message` reference to point to this new object.
Q752mediumcode error
What is the compile-time error in this Java code?
java
import java.util.function.Consumer;
public class LambdaError {
public static void main(String[] args) {
int counter = 0;
Consumer<String> printer = s -> {
System.out.println(s + counter);
counter++; // Attempt to modify counter
};
printer.accept("Count: ");
}
}
✅ Correct Answer: A) The lambda expression causes a 'Local variable counter defined in an enclosing scope must be final or effectively final' error.
Lambda expressions can only access local variables that are final or effectively final. Modifying 'counter' within the lambda violates this rule, leading to a compile-time error.
Q753easycode output
What does this Java code print?
java
class Person {
String name;
Person(String n) {
name = n;
System.out.println("Hello, " + name + "!");
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Alice");
}
}
✅ Correct Answer: A) Hello, Alice!
The constructor `Person(String n)` takes a string argument and assigns it to the `name` instance variable. The print statement then uses this initialized `name`.
Q754medium
To create a jagged (or irregular) 2D array in Java where each row can have a different number of columns, which initialization step is essential after declaring the outer array?
✅ Correct Answer: A) Explicitly declare the size of each inner array individually.
For a jagged array, you first declare the outer array's size, then you must loop through or individually initialize each inner array with its specific size.
Q755hardcode output
What does this code print?
java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
class Person {
String name;
int age;
double height;
public Person(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
public String getName() { return name; }
public int getAge() { return age; }
public double getHeight() { return height; }
@Override
public String toString() {
return name + " (" + age + ", " + height + ")";
}
}
public class ComparatorChaining {
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("Alice", 30, 1.65),
new Person("Bob", 25, 1.80),
new Person("Charlie", 30, 1.70),
new Person("David", 25, 1.75),
new Person("Alice", 28, 1.60)
));
Comparator<Person> byName = Comparator.comparing(Person::getName);
Comparator<Person> byAge = Comparator.comparingInt(Person::getAge);
Comparator<Person> byHeight = Comparator.comparingDouble(Person::getHeight);
Comparator<Person> complexComparator = byName
.thenComparing(byAge.reversed())
.thenComparing(byHeight);
List<Person> sortedPeople = people.stream()
.sorted(complexComparator)
.collect(Collectors.toList());
sortedPeople.forEach(System.out::println);
}
}
✅ Correct Answer: A) Alice (30, 1.65)
Alice (28, 1.6)
Bob (25, 1.8)
Charlie (30, 1.7)
David (25, 1.75)
The list is sorted first by name in ascending order. For people with the same name, it then sorts by age in descending order. Finally, for people with the same name and age, it sorts by height in ascending order. The output reflects this multi-level sorting logic.
Q756medium
Which statement best describes the purpose of the Java Virtual Machine's (JVM) Garbage Collector?
✅ Correct Answer: A) To automatically deallocate memory for objects that are no longer referenced by any part of the program.
The Garbage Collector's main role is automatic memory management. It identifies and reclaims memory occupied by objects that are no longer reachable or used by the application, freeing developers from manual memory deallocation.
Q757hard
When comparing the iterators provided by `ArrayList` and `CopyOnWriteArrayList`, which statement accurately describes a key difference in their fail-safe/fail-fast behavior and performance characteristics during concurrent modification?
✅ Correct Answer: B) `CopyOnWriteArrayList` iterators are fail-safe as they operate on a snapshot of the array, potentially returning stale data but avoiding `ConcurrentModificationException`.
`CopyOnWriteArrayList`'s iterators are fail-safe because they operate on an immutable snapshot of the list taken at the time the iterator was created. This means they will not throw `ConcurrentModificationException` but may return stale data, whereas `ArrayList` iterators are fail-fast.
Q758hard
Given a class with a static initializer block, an instance initializer block, and a constructor, what is the correct order of execution when a *new* object of this class is created for the *first time* in the JVM?
When a class is first loaded, its static initializer blocks run. Then, for each object creation, instance initializer blocks execute before the constructor.
Q759medium
Which scenario is best suited for using an interface over an abstract class?
✅ Correct Answer: B) When you need to define a contract for behaviors that different, unrelated classes might implement, allowing for multiple inheritance of type.
Interfaces are ideal for defining contracts or capabilities that diverse classes can implement, enabling multiple inheritance of type without the complexities of multiple inheritance of implementation found in abstract classes.
Q760easycode error
What compile-time error will occur in the `MyClass` definition?
java
class MyClass {
public void MyClass() {
System.out.println("Hello");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
}
}
✅ Correct Answer: A) invalid method declaration; return type required
A constructor cannot have a return type, including `void`. If a return type is present, it's considered a regular method with the same name as the class, not a constructor. The compiler expects a return type for a method named `MyClass`.