public class CallStartOnRunnable {
public static void main(String[] args) {
Runnable myJob = () -> System.out.println("Job running.");
myJob.start(); // Line 4
}
}
✅ Correct Answer: A) Compile-time error: The method start() is undefined for the type Runnable (at Line 4)
The `start()` method is defined in the `Thread` class, not the `Runnable` interface. To start a new thread of execution for a `Runnable` object, it must be passed to a `Thread` constructor, and then `Thread.start()` must be called.
Q3702easycode output
What does this Java code print?
java
public class LoopTest {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.print(i);
}
}
}
✅ Correct Answer: A) 012
The loop prints i for 0, 1, and 2. When i becomes 3, the `break` statement terminates the loop, so 3 is not printed.
Q3703hard
Which of the following best describes the relationship between `FileReader` and `InputStreamReader` in the Java I/O hierarchy?
✅ Correct Answer: C) `FileReader` is a convenience class that is essentially an `InputStreamReader` built upon a `FileInputStream`, using the default character encoding.
FileReader is a convenience class for reading character files. It is essentially an InputStreamReader that operates on a FileInputStream, implicitly using the platform's default character encoding for character-to-byte conversion.
Q3704medium
What is the primary distinction between a thread in the `WAITING` state and one in the `TIMED_WAITING` state?
✅ Correct Answer: B) TIMED_WAITING threads will automatically return to RUNNABLE after a specified duration, whereas WAITING threads require an external `notify()` or `notifyAll()`.
The key difference is that a TIMED_WAITING thread will eventually wake up on its own after a set period, while a WAITING thread will wait indefinitely until explicitly notified by another thread.
Q3705easycode error
What kind of error will occur when compiling this Java code?
java
public class Main {
public static void main(String[] args) {
int value;
if (true) {
value = 10;
} else {
// value is not initialized here
}
System.out.println(value);
}
}
✅ Correct Answer: B) Compile-time Error: variable value might not have been initialized.
The Java compiler requires that a local variable is definitely assigned a value before it's used. Since there's a path (the 'else' block) where 'value' is not initialized, the compiler reports an error.
Q3706easycode output
What will be the content of the file 'output.txt' after this code executes?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterTest {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("output.txt", true)) {
writer.write("Line 1\n");
} catch (IOException e) {}
try (FileWriter writer = new FileWriter("output.txt", true)) {
writer.write("Line 2");
} catch (IOException e) {}
}
}
✅ Correct Answer: A) Line 1
Line 2
Both `FileWriter` instances are created with the append flag (`true`). The first writes 'Line 1\n', and the second appends 'Line 2' directly after it, resulting in two lines of text.
Q3707medium
Which `java.io` interface does `BufferedWriter` implement, indicating its primary role in handling character output?
✅ Correct Answer: C) `java.lang.Appendable`
While `BufferedWriter` implements `Closeable` (through its parent `Writer`), `Appendable` is a key interface that defines methods like `append(char c)` and `append(CharSequence csq)`, which `BufferedWriter` supports, allowing for efficient character sequence appending.
Q3708easycode error
What kind of error will occur when executing the following Java code?
java
public class MyThread implements Runnable {
@Override
public void run() {
System.out.println("Thread is running and completing.");
}
public static void main(String[] args) throws InterruptedException {
MyThread myRunnable = new MyThread();
Thread t = new Thread(myRunnable);
t.start();
t.join(); // Wait for the thread to complete
t.start(); // Attempt to start the same thread after it finished
}
}
✅ Correct Answer: C) Runtime Error: java.lang.IllegalThreadStateException
Once a thread has completed its execution (entered the TERMINATED state), it cannot be restarted. Attempting to call `start()` on a terminated thread will throw a `java.lang.IllegalThreadStateException`.
Q3709easycode output
What is the output of this code?
java
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println(colors.size());
}
}
✅ Correct Answer: A) 3
The `add()` method adds elements to the HashSet. Since 'Red', 'Green', and 'Blue' are distinct elements, the size of the set becomes 3.
Q3710easycode error
What error occurs during compilation for the following code snippet?
java
public class Main {
public static void main(String[] args) {
System.out.println("Before sleep");
Thread.sleep(1000); // Attempting to sleep without handling InterruptedException
System.out.println("After sleep");
}
}
✅ Correct Answer: A) Compilation Error: Unhandled exception type InterruptedException
The `Thread.sleep()` method throws a checked `InterruptedException`, which must be caught or declared in the method's `throws` clause. Since it's not handled, a compile-time error occurs.
Q3711easy
Is the order of elements guaranteed in a Java HashMap?
✅ Correct Answer: C) No, HashMap does not guarantee any specific order of elements.
HashMap does not maintain any specific order (like insertion order or sorted order) for its elements.
Q3712easy
Can an `else` statement exist in Java without being immediately preceded by an `if` statement?
✅ Correct Answer: B) No, an `else` clause must always be paired with an `if` or `else if` clause.
An `else` statement is an extension of an `if` or `else if` statement, providing an alternative path when the preceding condition(s) are false, and cannot exist on its own.
Q3713medium
When is the `this()` keyword used within a constructor in Java?
✅ Correct Answer: C) To invoke another constructor within the same class.
The `this()` keyword is used for constructor chaining, allowing one constructor to call another constructor within the same class, often to avoid code duplication.
Q3714hardcode output
What is the output of this code?
java
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("ABCDEF");
CharSequence cs = "1234567890";
sb.append(cs, 2, 5);
System.out.println(sb);
}
}
✅ Correct Answer: A) ABCDEF345
`append(CharSequence s, int start, int end)` appends a subsequence from the given `CharSequence`. The `start` index is inclusive (2, '3'), and the `end` index is exclusive (5, up to but not including '6'). Therefore, '345' is appended.
Q3715medium
If you instantiate a `FileWriter` with `new FileWriter("existingFile.txt");` and "existingFile.txt" already exists, what happens by default?
✅ Correct Answer: C) The existing file is truncated (its content is deleted) and new data is written from the beginning.
By default, the `FileWriter(String fileName)` constructor truncates an existing file to zero length before writing, effectively overwriting its previous content.
Q3716medium
Which static method of the String class is used to construct a new String by concatenating elements from an `Iterable` or array, separated by a specified delimiter?
✅ Correct Answer: D) `String.join()`
The `String.join()` method (introduced in Java 8) provides a convenient way to concatenate multiple strings with a specified delimiter, especially useful with collections or arrays of strings.
Q3717hardcode error
What is the specific compilation error in this Java code snippet?
java
public class VarAsField {
// 'var' keyword is only for local variables
private var data = "hello";
public static void main(String[] args) {
System.out.println("Attempting to compile...");
}
}
✅ Correct Answer: A) Error: 'var' is not allowed in a field declaration.
The `var` keyword (local variable type inference) can only be used for local variables inside methods, constructors, or initializer blocks, not for declaring fields (instance or static variables).
Q3718hard
Consider a `Serializable` class `A` that contains an instance of `Serializable` class `B`. If the `serialVersionUID` of class `B` is changed, and then an object of class `A` (which contains an instance of the *old* `B`) is deserialized with the *new* `B` class definition, what is the most likely outcome?
✅ Correct Answer: B) A `java.io.InvalidClassException` will be thrown during the deserialization of the `B` instance within `A`.
A mismatch in `serialVersionUID` for a `Serializable` class during deserialization explicitly indicates an incompatible class change, leading to `InvalidClassException` when attempting to deserialize that specific class's instance.
Q3719mediumcode output
What does this code print?
java
public class StringTest {
public static void main(String[] args) {
String text = "Java programming is fun.";
String sub = text.substring(5, 16);
System.out.println(sub);
}
}
✅ Correct Answer: A) programming
The `substring(beginIndex, endIndex)` method extracts characters from `beginIndex` up to, but not including, `endIndex`. Index 5 is 'p', and index 16 is the 'g' in 'programming' plus the space, so it extracts 'programming'.
Q3720hard
When considering performance, what is the primary trade-off associated with using immutable objects extensively, especially for operations that involve frequent modifications (e.g., string concatenation in a loop)?
✅ Correct Answer: B) Higher memory consumption and increased garbage collection activity due to the creation of many intermediate objects.
Operations that logically 'modify' an immutable object actually create a new object with the new state, leading to frequent object creation, higher memory usage, and increased garbage collection load.