How does the functionality of the `break` keyword differ when used within a `switch` statement compared to within a `for` loop?
✅ Correct Answer: C) In a `switch`, `break` exits the entire `switch` block; in a `for` loop, it exits the entire loop.
In a `switch` statement, `break` terminates the execution of the `switch` block. In a `for` loop, `break` terminates the execution of the entire `for` loop.
Q342hard
Which statement best describes the thread-safety of `java.util.LinkedList` and appropriate measures for concurrent use?
✅ Correct Answer: B) `LinkedList` is not thread-safe. For concurrent access, it can be wrapped using `Collections.synchronizedList()`, which provides internal synchronization for all methods.
LinkedList is not thread-safe. The `Collections.synchronizedList()` factory method returns a thread-safe wrapper that synchronizes all List methods. While `ConcurrentLinkedQueue` (or `ConcurrentLinkedDeque`) is a good lock-free alternative, the question specifically asks about `LinkedList` and its measures.
Q343mediumcode output
What does this code print?
java
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("key1", 10);
System.out.println(map.getOrDefault("key1", 0) + ", " + map.getOrDefault("key2", 5));
}
}
✅ Correct Answer: A) 10, 5
`getOrDefault("key1", 0)` returns the existing value 10 for 'key1'. `getOrDefault("key2", 5)` returns the default value 5 because 'key2' is not present in the map.
Q344easycode output
What does this Java code print?
java
public class ArrayTest {
public static void main(String[] args) {
int[] numbers = {5, 10, 15};
System.out.println(numbers[numbers.length - 1]);
}
}
✅ Correct Answer: A) 15
`numbers.length` is 3. `numbers.length - 1` evaluates to 2, so `numbers[2]` accesses the last element, which is 15.
Q345mediumcode output
What is the output of the following Java code?
java
import java.io.BufferedWriter;
import java.io.StringWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
bw.write("PartOne");
bw.flush();
bw.write("PartTwo");
bw.close();
System.out.print(sw.toString());
}
}
✅ Correct Answer: A) PartOnePartTwo
The `flush()` method forces any buffered data to be written to the underlying stream but does not close the stream. Subsequent `write()` calls continue to append data, and the final `close()` ensures all remaining data is flushed. Thus, both parts are written consecutively.
Q346easycode error
What is the error in the following Java code snippet?
java
public class ArrayError {
public static void main(String[] args) {
boolean[] flags = new boolean[3];
flags[0] = true;
flags[1] = 1;
}
}
✅ Correct Answer: A) Compile-time error: Incompatible types, int cannot be converted to boolean.
In Java, `boolean` values are `true` or `false`. An integer `1` cannot be directly assigned or implicitly converted to a `boolean` type, leading to a compile-time type mismatch error.
Q347mediumcode error
Which of the following describes the error encountered when compiling the provided Java code using varargs and arrays?
java
public class OverloadChecker {
public void processArgs(int... numbers) {
System.out.println("Varargs count: " + numbers.length);
}
public void processArgs(int[] data) { // This line causes the error
System.out.println("Array length: " + data.length);
}
public static void main(String[] args) {
OverloadChecker oc = new OverloadChecker();
oc.processArgs(1, 2, 3);
}
}
✅ Correct Answer: A) Compile-time error: Method 'processArgs(int[])' is already defined in 'OverloadChecker'.
Varargs (`int...`) is internally treated as an array (`int[]`) by the compiler. Thus, methods with `int...` and `int[]` as their sole parameter have the same signature and cannot be overloaded.
Q348easycode error
What is the expected error when compiling and running the following Java code?
java
import java.util.LinkedList;
public class MyClass {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add(123); // Trying to add an Integer to a String list
}
}
✅ Correct Answer: C) Compile-time error: incompatible types: int cannot be converted to String
The `LinkedList` is generics-typed to hold `String` objects. Attempting to add an `int` (or `Integer`) directly will result in a compile-time error due to incompatible types.
Q349hardcode output
What is the output of this code?
java
interface Loggable {
private String formatMessage(String message) {
return "[" + getClass().getSimpleName() + "] " + message;
}
default void log(String message) {
System.out.println(formatMessage("Default log: " + message));
}
}
class AppLogger implements Loggable {}
public class PrivateInterfaceTest {
public static void main(String[] args) {
new AppLogger().log("Initiating...");
}
}
✅ Correct Answer: A) [AppLogger] Default log: Initiating...
Private interface methods are a Java 9+ feature that can be used by default methods within the same interface. `getClass().getSimpleName()` within the default method correctly refers to the runtime type of the implementing instance, `AppLogger`.
Q350easycode output
What is the output of the following Java program?
java
public class Temperature {
private double celsius;
public Temperature(double initialCelsius) {
this.celsius = initialCelsius;
}
public double getFahrenheit() {
return (celsius * 9/5) + 32;
}
public static void main(String[] args) {
Temperature temp = new Temperature(20.0);
System.out.println(temp.getFahrenheit());
}
}
✅ Correct Answer: A) 68.0
The constructor initializes the Celsius temperature to 20.0. The 'getFahrenheit' method converts this to Fahrenheit using the formula (20.0 * 9/5) + 32, which results in 68.0.
Q351hardcode output
What does this code print?
java
String str = " Java World ";
String result = str.trim().replace(" ", "").toLowerCase();
System.out.println(str);
System.out.println(result);
✅ Correct Answer: A) Java World
javaworld
Java `String` objects are immutable. Methods like `trim()`, `replace()`, and `toLowerCase()` return *new* `String` objects, leaving the original `str` unchanged. `result` captures the chained modifications.
Q352mediumcode error
What error occurs when compiling this Java code?
java
public class LoopTest {
public static void main(String[] args) {
int count = 5;
do {
System.out.println("Counting...");
count--;
} while (count);
}
}
✅ Correct Answer: B) error: incompatible types: int cannot be converted to boolean
The condition in a 'while' loop must be a boolean expression. An 'int' type cannot be implicitly converted to a 'boolean', resulting in a compile-time type mismatch error.
Q353easycode error
What is the result of running this Java code?
java
public class StringError {
public static void main(String[] args) {
String word = "Java";
System.out.println(word.charAt(4));
}
}
✅ Correct Answer: C) java.lang.StringIndexOutOfBoundsException: String index out of range: 4
The String 'Java' has a length of 4, so valid indices are 0 to 3. Attempting to access index 4 will result in a StringIndexOutOfBoundsException.
Q354easy
What is the purpose of curly braces `{}` around the statement(s) following an `if` or `else` keyword in Java?
✅ Correct Answer: C) They define a block of multiple statements to be executed conditionally.
Curly braces group multiple statements into a single block, ensuring all statements within that block are executed together if the condition is met (or the `else` branch is taken).
Q355mediumcode error
What exception will be thrown when executing this Java code snippet?
java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Iterator;
public class QueueError {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("A");
queue.add("B");
Iterator<String> iterator = queue.iterator();
queue.add("C"); // Structural modification while iterating
iterator.next();
}
}
✅ Correct Answer: A) ConcurrentModificationException
Iterators returned by `LinkedList` (and most other non-concurrent Java collections) are fail-fast. If the collection is structurally modified at any time after the iterator is created, the iterator will throw a `ConcurrentModificationException` when `next()` is called.
Q356mediumcode error
What is the outcome when this Java code is executed?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
int value = numbers.get(2);
System.out.println(value);
}
}
✅ Correct Answer: B) IndexOutOfBoundsException
The `LinkedList.get(int index)` method throws an `IndexOutOfBoundsException` if the index is out of range (`index < 0` or `index >= size()`). In this case, the list has 2 elements (indices 0 and 1), so `get(2)` is out of bounds.
Q357medium
Which statement is true regarding `private` methods and polymorphism in Java?
✅ Correct Answer: C) `private` methods cannot be overridden as they are not inherited.
`private` methods are not inherited by subclasses, meaning they are not accessible to be overridden. A method with the same signature in a subclass would be a new, independent method, not an override.
Q358easycode output
What does this Java code print?
java
public class Test {
public static void main(String[] args) {
String[] greetings = {"Hello", "Hi", "Hey"};
String lastGreeting = "";
for (String greeting : greetings) {
lastGreeting = greeting;
}
System.out.println(lastGreeting);
}
}
✅ Correct Answer: C) Hey
The enhanced for loop iterates through each element. `lastGreeting` is successively assigned each value, ending with the last element of the array, 'Hey'.
Q359hardcode error
What error will this code produce at compile time?
java
public class EffectivelyFinalError {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println(i);
}).start();
i = i + 0;
}
}
}
✅ Correct Answer: A) Local variable i defined in an enclosing scope must be final or effectively final
The variable `i` is modified within the loop (`i = i + 0;`), making it not effectively final. This violates the rule that variables accessed from a lambda expression must be final or effectively final.
Q360medium
What is the purpose of the `transient` keyword when applied to an instance variable in Java?
✅ Correct Answer: B) It prevents the variable from being serialized when an object is written to a persistent storage.
The `transient` keyword is used in the context of serialization. When an object is serialized, `transient` fields are skipped and not stored in the persistent state, and they will be initialized to their default values (e.g., 0 for numeric types, null for objects) when the object is deserialized.