What error will occur when compiling the following Java code snippet?
java
public class Main {
public static void main(String[] args) {
Runnable r = new Runnable();
System.out.println("Runnable created.");
}
}
✅ Correct Answer: A) Compilation error: Runnable is abstract; cannot be instantiated.
The Runnable interface is an abstract type and cannot be instantiated directly using 'new Runnable()'. It must be implemented by a class or a lambda expression.
Q3862mediumcode error
What is the compile-time error in the following Java code?
java
import java.io.IOException;
class DataProcessor {
private String data;
public DataProcessor(String filePath) { // Missing throws IOException
// Simulate an operation that could throw IOException
if (filePath == null || filePath.isEmpty()) {
throw new IOException("File path cannot be empty");
}
this.data = filePath;
System.out.println("DataProcessor created for: " + filePath);
}
}
public class ConstructorError7 {
public static void main(String[] args) {
new DataProcessor("my_file.txt");
}
}
✅ Correct Answer: A) Error: unreported exception IOException; must be caught or declared to be thrown
If a constructor's body throws a checked exception (like `IOException`), it must either handle the exception (using a `try-catch` block) or declare that it `throws` that exception in its signature. Since `IOException` is a checked exception and it's neither caught nor declared, a compile-time error occurs.
Q3863hard
What kind of copy is performed by `ArrayList.clone()` for the elements stored within the list?
✅ Correct Answer: B) A shallow copy, where references to the original elements are copied.
`ArrayList.clone()` performs a shallow copy. It creates a new `ArrayList` instance and copies the references to the original elements into the new list's internal array, rather than creating new instances of the elements themselves.
Q3864medium
Which method would you use to remove characters from a `StringBuffer` within a specified range (start and end index)?
✅ Correct Answer: A) `delete(int start, int end)`
The `delete()` method in `StringBuffer` allows you to remove a substring of characters from the sequence, specified by a start and end index (exclusive of the end index).
Q3865mediumcode output
What is the output of this Java code?
java
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
List<Boolean> addResults = new ArrayList<>();
addResults.add(numbers.add(1));
addResults.add(numbers.add(3));
addResults.add(numbers.add(1));
addResults.add(numbers.add(2));
System.out.println(addResults + " " + numbers);
}
}
The `add()` method returns `true` if the element was successfully added (i.e., not already present) and `false` if it was a duplicate. `TreeSet` maintains natural ordering and does not allow duplicates.
Q3866mediumcode error
What is the result of attempting to run the following Java code?
java
class MyTask implements Runnable {
public void run() {
System.out.println("Task running");
}
}
public class Main {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
thread.start(); // This line
}
}
✅ Correct Answer: B) A runtime exception: java.lang.IllegalThreadStateException.
A thread can only be started once. Calling start() on a thread that is not in the NEW state will throw an IllegalThreadStateException at runtime.
Q3867hardcode output
What is the output of this code?
java
public class SwitchTest {
public static void main(String[] args) {
Integer num = null;
String result = "";
switch (num) {
case 1:
result = "One";
break;
case 2:
result = "Two";
break;
default:
result = "Other";
}
System.out.println(result);
}
}
✅ Correct Answer: C) java.lang.NullPointerException
When an `Integer` wrapper type is used in a traditional `switch` statement, it is auto-unboxed to an `int`. If the `Integer` reference is `null`, attempting to unbox it results in a `NullPointerException`.
Q3868mediumcode error
What is the error in the following Java code?
java
class Parent {
private int secretCode = 1234;
}
class Child extends Parent {
public void revealSecret() {
// Attempt to access private field of superclass
System.out.println("Secret: " + secretCode);
}
public static void main(String[] args) {
Child c = new Child();
c.revealSecret();
}
}
✅ Correct Answer: A) Compilation error: The field Parent.secretCode is not visible.
Private members of a superclass are not inherited and cannot be accessed directly by a subclass. The 'secretCode' field is private in Parent, so Child cannot access it, leading to a compilation error.
✅ Correct Answer: B) On file object: true
On non-existent object: true
On parent directory: true
The `listFiles()` method returns `null` if the `File` object does not denote a directory or if an I/O error occurs. Both a regular file and a non-existent path are not directories, so `listFiles()` returns `null` for them. For the actual directory, it returns an array.
Q3870hardcode output
What is the output of this code?
java
public class Main {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer c = 200;
Integer d = 200;
System.out.println(a == b);
System.out.println(c == d);
}
}
✅ Correct Answer: B) true\nfalse
Java caches `Integer` objects created by autoboxing for values between -128 and 127 (inclusive). For `a` and `b`, both 100 fall within this range, so they refer to the same cached `Integer` object, making `a == b` true. For `c` and `d`, 200 is outside this cache range, so autoboxing creates new `Integer` objects for each, making `c == d` false. This demonstrates the immutability of `Integer` objects, where operations return new objects rather than modifying existing ones, but also the nuance of object identity due to caching.
Q3871easycode 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 writer1 = new FileWriter("output.txt")) {
writer1.write("Data A\n");
} catch (IOException e) {}
try (FileWriter writer2 = new FileWriter("output.txt", true)) {
writer2.write("Data B");
} catch (IOException e) {}
}
}
✅ Correct Answer: A) Data A
Data B
The first FileWriter creates the file with 'Data A\n'. The second FileWriter uses the append constructor (`true`), so it adds 'Data B' to the end of the existing content.
Q3872easy
What is the primary benefit of using `BufferedWriter` in Java?
✅ Correct Answer: B) To write character data more efficiently by buffering output.
`BufferedWriter` adds buffering capabilities to an underlying `Writer`, improving efficiency by reducing the number of actual writes to the destination.
Q3873hardcode error
What compilation error will occur when compiling the following Java code?
java
import java.util.function.Consumer;
public class LambdaWildcardInference {
public static void processConsumer(Consumer<?> consumer) {
// consumer.accept(new Object()); // Would not compile here
}
public static void main(String[] args) {
processConsumer(s -> System.out.println(s.length()));
}
}
✅ Correct Answer: A) Error: cannot find symbol method length()
The method `processConsumer` takes a `Consumer<?>`. When the lambda `s -> System.out.println(s.length())` is passed, `s` is inferred as `Object` due to the wildcard `?`. The `Object` class does not have a `length()` method, resulting in a 'cannot find symbol' compilation error.
Q3874medium
To accumulate elements of a Stream into a `Set` while preserving distinct elements, which `Collectors` method would you typically use?
✅ Correct Answer: B) Collectors.toSet()
`Collectors.toSet()` is a convenient predefined collector that gathers all input elements into a new `Set`, automatically handling distinctness.
Q3875mediumcode error
What error occurs when compiling this Java code?
java
public class MyClass {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("apple");
StringBuffer sb2 = new StringBuffer("banana");
System.out.println(sb1.compareTo(sb2));
}
}
✅ Correct Answer: B) Compile-time error: cannot find symbol method compareTo(java.lang.StringBuffer)
The `StringBuffer` class does not implement the `Comparable` interface, and therefore does not have a `compareTo()` method for comparing `StringBuffer` objects. This leads to a compile-time error, as the method cannot be found.
Q3876mediumcode error
What will be the compilation error in this code?
java
class Producer {
public String produceItem() {
return "Item A";
}
}
class SpecialProducer extends Producer {
@Override
public Integer produceItem() {
return 123;
}
}
✅ Correct Answer: A) Error: incompatible return type: Integer cannot be converted to String
In method overriding, the return type of the overriding method can be the same as, or a subclass of, the return type of the overridden method (covariant return types). 'Integer' is not a subclass of 'String', leading to an incompatible return type error.
Q3877easycode error
What is the error in this Java code?
java
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, Integer> myMap = new HashMap<>();
myMap.put("number", "123");
System.out.println(myMap.get("number"));
}
}
✅ Correct Answer: C) A compile-time error because the value type for 'put' does not match the map's generic type.
The HashMap is declared to hold Integer values, but a String value is being passed to the 'put' method, leading to a compile-time type mismatch error.
Q3878easycode error
What is the compilation or runtime error in the following Java code?
java
public class Main {
public static void main(String[] args) {
String prefix = null;
String data = "program";
boolean starts = data.startsWith(prefix);
System.out.println(starts);
}
}
✅ Correct Answer: C) Runtime error: java.lang.NullPointerException
The `startsWith()` method expects a non-null `String` argument. Passing `null` as the argument causes a `NullPointerException` at runtime.
Q3879mediumcode error
What is the compile-time error in the following Java code?
java
class MyClass {
private int value;
public static MyClass(int value) { // Illegal static modifier
this.value = value;
}
public static void main(String[] args) {
MyClass obj = new MyClass(10);
}
}
✅ Correct Answer: A) Error: Illegal modifier for the constructor; only public, protected, private, or no modifier are permitted
Constructors cannot be declared `static`. The `static` keyword applies to members that belong to the class itself, not to instances. Constructors are inherently tied to instance creation, hence declaring one as `static` is a compilation error.
Q3880hard
A `TreeSet` is created using a custom `Comparator` that is defined as an anonymous inner class and is NOT `Serializable`. If this `TreeSet` instance is then attempted to be serialized to a file, what is the most likely outcome?
✅ Correct Answer: B) A `NotSerializableException` is thrown because the `Comparator` is not `Serializable`.
For a `TreeSet` with a custom `Comparator` to be successfully serialized, the `Comparator` itself must implement the `java.io.Serializable` interface. Otherwise, a `NotSerializableException` will occur during the serialization process.