Which of the following Java 7+ constructs is the most recommended way to ensure a `BufferedWriter` is properly closed, even if exceptions occur?
✅ Correct Answer: C) Using the `try-with-resources` statement.
The `try-with-resources` statement automatically closes any resources that implement `java.lang.AutoCloseable` (which `BufferedWriter` does) when the `try` block exits, whether normally or due to an exception, making it the safest and most concise approach.
Q1942mediumcode error
What error will occur when compiling or running this Java code?
java
public class ArrayError {
public static void main(String[] args) {
int[] values = new int[3];
// This is a re-initialization attempt with initializer list syntax
values = new int[]{1, 2, 3, 4};
}
}
✅ Correct Answer: A) Compilation Error: Array initializer is not allowed here
An array initializer list (`{...}`) can only be used in the declaration of an array or with the `new type[] {...}` syntax. Without `new int[]`, direct re-assignment using `{...}` is a compile-time error.
Q1943medium
What happens when you try to cast an `Integer` object to a `Long` object directly in Java (e.g., `Long l = (Long) someIntegerObject;`)?
✅ Correct Answer: C) It results in a compile-time error.
Wrapper classes like `Integer` and `Long` are distinct classes. You cannot directly cast an `Integer` object reference to a `Long` object reference; they are not in a direct inheritance hierarchy that allows such a cast. This will result in a compile-time error.
Q1944mediumcode error
What error will occur when compiling and running this Java code?
java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class HashSetError2 {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
for (Integer num : numbers) {
if (num == 2) {
numbers.remove(num); // ERROR line
}
}
System.out.println(numbers);
}
}
✅ Correct Answer: B) Runtime Error: java.util.ConcurrentModificationException.
Modifying a collection (like `HashSet`) directly while iterating over it using an enhanced for-loop (which internally uses an iterator) can lead to a `ConcurrentModificationException`. To safely remove elements during iteration, the iterator's `remove()` method should be used.
Q1945easycode error
What is the compilation or runtime error in the following Java code?
java
public class Main {
public static void main(String[] args) {
String s1 = null;
String s2 = " World";
String result = s1.concat(s2);
System.out.println(result);
}
}
Calling the `concat()` method on a `null` string reference (`s1`) will result in a `NullPointerException` at runtime.
Q1946easycode output
What does this code print?
java
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> letters = new HashSet<>();
letters.add("C");
letters.add("A");
letters.add("B");
System.out.println(letters.contains("A") && letters.contains("B") && letters.contains("C"));
}
}
✅ Correct Answer: A) true
The `HashSet` successfully adds 'C', 'A', and 'B' as distinct elements. The `contains()` method returns `true` for each of them, so the logical AND of these three `true` values results in `true`.
Q1947medium
What is the typical time complexity for adding or removing an element at the beginning or end of a `java.util.LinkedList`?
✅ Correct Answer: A) O(1)
Due to its doubly linked nature, LinkedList can directly update the head or tail pointers, making addFirst(), addLast(), removeFirst(), and removeLast() operations constant time (O(1)).
Q1948hard
Which statement about the runtime overhead and object creation of lambda expressions is generally FALSE?
✅ Correct Answer: A) Each invocation of a lambda expression always creates a new object instance on the heap, similar to anonymous inner classes.
The statement is false. The JVM often optimizes lambda expressions. Stateless lambdas or those capturing effectively final variables can frequently be optimized to avoid creating new object instances for each invocation, sometimes becoming singletons or even inlined.
Q1949easycode error
What compilation error will occur when compiling this Java code?
java
import java.io.BufferedReader;
public class MyClass {
public static void main(String[] args) {
BufferedReader br = new BufferedReader("Some text");
}
}
✅ Correct Answer: A) constructor BufferedReader in class BufferedReader cannot be applied to given types
The `BufferedReader` constructor expects a `Reader` object (like `StringReader` or `FileReader`), not a `String` directly. This results in a compilation error because no matching constructor exists.
Q1950medium
Given an array `String[] names = {"Alice", "Bob", "Charlie"};`, what is the most concise way to iterate through and print each name?
✅ Correct Answer: B) for (String name : names) { System.out.println(name); }
The enhanced for-loop (for-each loop) provides the most concise and readable way to iterate over all elements of an array. Option A is correct but less concise, C requires streams, and D uses incorrect syntax for arrays.
Q1951easycode error
What is the primary issue that prevents this Java code from compiling?
java
public class LoopError10 {
public static void main(String[] args) {
int count = 0;
while count < 3 { // Missing parentheses around condition
System.out.println("Current count: " + count);
count++;
}
}
}
✅ Correct Answer: A) Compile-time error: `illegal start of expression` or `';' expected`.
In Java, the condition of a `while` loop must be enclosed in parentheses. Omitting them will result in a compile-time syntax error as the compiler expects an expression within parentheses.
Q1952hard
What is the final value of `a` and `b` after the following Java code executes?
java
int a = 5;
int b = ++a * 2 + a--;
✅ Correct Answer: D) a = 5, b = 18
`++a` increments `a` to `6` (value `6`). So `b = 6 * 2 + a--`. `6 * 2` is `12`. Then `a--` uses `a`'s current value (`6`) for the expression and then decrements `a` to `5`. So `b = 12 + 6 = 18`.
Q1953hardcode output
What is the output of this Java program?
java
public class MultiArrayQ8 {
public static void main(String[] args) {
int[][] table = new int[3][3];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (i == j) table[i][j] = i + j;
else if (i > j) table[i][j] = i - j;
else table[i][j] = i + j + 1;
}
}
System.out.println(table[1][2]);
}
}
✅ Correct Answer: A) 4
For `table[1][2]`, we have `i=1` and `j=2`. Since `i < j`, the condition `else table[i][j] = i + j + 1;` is met. Therefore, `table[1][2] = 1 + 2 + 1 = 4`.
Q1954hardcode error
What is the compilation error in the following Java code?
java
public class OuterClass {
private int outerValue = 100;
public static class StaticNestedClass {
public void display() {
// Attempt to access a non-static outer field from a static nested class
System.out.println("Outer value: " + outerValue);
}
}
}
✅ Correct Answer: B) Error: Cannot make a static reference to the non-static field outerValue.
A `static` nested class does not implicitly hold a reference to an instance of its enclosing class. Therefore, it cannot directly access non-static members (like `outerValue`) of the outer class without an explicit outer class instance, leading to a 'static reference to non-static field' compile-time error.
Q1955mediumcode output
What is the output of this code?
java
import java.util.LinkedList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("One");
list.add("Two");
list.add("Three");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("Two")) {
it.remove();
}
}
System.out.println(list.size());
}
}
✅ Correct Answer: B) 2
The code iterates through the list. When the element 'Two' is encountered, `it.remove()` is called, which safely removes the current element from the list. The list initially has 3 elements, and one is removed, leaving 2 elements.
Q1956hardcode error
What is the compilation error in the following Java code?
java
class UserProfile {
private String username = "guest";
public String getUsername() {
return username;
}
}
public class AdminPanel {
public static void main(String[] args) {
UserProfile profile = new UserProfile();
System.out.println(profile.username); // Direct access to private field
}
}
✅ Correct Answer: A) Error: The field UserProfile.username is not visible.
The `username` field in `UserProfile` is declared as `private`. This means it can only be accessed from within the `UserProfile` class. Direct access from `AdminPanel` violates encapsulation and causes a compile-time error.
Q1957hardcode error
What is the output of this code?
java
import java.util.LinkedList;
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>(Arrays.asList("A", "B", "C", "D"));
for (String s : list) {
if (s.equals("B")) {
list.remove("B");
}
}
System.out.println(list);
}
}
✅ Correct Answer: B) java.util.ConcurrentModificationException
Modifying a collection directly while iterating over it using an enhanced for-each loop causes a `ConcurrentModificationException`. The `remove("B")` call structurally modifies the list.
Q1958easy
In which of the following contexts can the `break` keyword be used in Java?
✅ Correct Answer: A) Within loops (for, while, do-while) and `switch` statements.
`break` can be used to exit loops prematurely and to exit a `switch` statement after a matching case is found.
Q1959easycode error
Which error will be reported when compiling the following Java program?
java
class Singleton {
private Singleton() { }
}
public class TestSingleton {
public static void main(String[] args) {
Singleton instance = new Singleton();
}
}
✅ Correct Answer: A) Compile-time error: 'Singleton()' has private access in 'Singleton'
The constructor of the 'Singleton' class is declared as private. This prevents direct instantiation of the class from outside, which is a common pattern for implementing the Singleton design principle, and results in a compile-time error here.
Q1960easy
Which of the following is a valid way to overload a method named `process(int data)`?
✅ Correct Answer: C) public void process(String data) { /* ... */ }
Overloading is achieved by changing the number, type, or order of parameters. Changing the parameter type from `int` to `String` creates a distinct method signature.