class MyProcessor {
public static void process(int value) throws Exception {
if (value < 0) {
throw new Exception("Negative value not allowed");
}
System.out.println("Processing: " + value);
}
public static void main(String[] args) {
try {
process(-10);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Program finished.");
}
}
✅ Correct Answer: A) Error: Negative value not allowed
Program finished.
The `process` method throws a checked exception if the value is negative. The `main` method catches this exception and prints its message, then continues to execute the final `println` statement.
Q1842mediumcode error
What is the compilation error in the provided Java code?
java
abstract class ServiceConfig {
public abstract static void setup(); // ERROR: abstract static method
public void load() {
System.out.println("Loading configuration.");
}
}
class MyService extends ServiceConfig {
// Must implement setup(), but it's static in parent
// public static void setup() { ... }
}
public class Main {
public static void main(String[] args) {
// ServiceConfig.setup();
}
}
✅ Correct Answer: A) ServiceConfig.java:2: error: illegal combination of modifiers: abstract and static
Abstract methods are meant to be implemented by subclasses, relying on polymorphism. Static methods, however, belong to the class itself and cannot be overridden. Therefore, a method cannot be both `abstract` and `static` as these modifiers are contradictory in their nature and purpose.
Q1843easycode output
What is the output of this code?
java
public class StringTest {
public static void main(String[] args) {
String s = "Hello";
System.out.println(s.length());
}
}
✅ Correct Answer: A) 5
The `length()` method returns the number of characters in the string. The string "Hello" has 5 characters.
Q1844hard
Which of the following is a *valid* way to create an instance of a class `MyClass` that has *only* a private constructor, *without* adding a public static factory method within `MyClass` itself?
✅ Correct Answer: C) Using `Constructor constructor = MyClass.class.getDeclaredConstructor(); constructor.setAccessible(true); MyClass obj = (MyClass) constructor.newInstance();`
Reflection allows bypassing access modifiers. `getDeclaredConstructor()` can retrieve private constructors, and `setAccessible(true)` allows their invocation, circumventing the private restriction.
Q1845medium
The `exists()` method of the `File` class can return `true` for which of the following file system entities?
✅ Correct Answer: C) Regular files, directories, and symbolic links.
The `exists()` method checks if the file or directory denoted by the abstract pathname exists. This includes regular files, directories, and symbolic links that point to existing targets.
Q1846mediumcode error
What error does this Java code snippet produce when executed?
java
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<String, Integer> map = new TreeMap<>();
map.put("Apple", 10);
map.put(null, 5);
System.out.println(map.size());
}
}
✅ Correct Answer: A) java.lang.NullPointerException
TreeMap does not allow null keys by default, as it relies on keys being naturally comparable or a custom Comparator. Attempting to add a null key without a custom Comparator that explicitly handles nulls results in a NullPointerException.
Q1847hard
What is the consequence if a constructor explicitly throws a *checked exception* without declaring it in its `throws` clause?
✅ Correct Answer: B) The compiler will report an "unreported exception" error.
Just like methods, a constructor that throws a checked exception must declare it in its `throws` clause. Failure to do so results in a compile-time error.
Q1848easycode output
What does this code print?
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Double> ts = new TreeSet<>();
boolean added1 = ts.add(1.1);
boolean added2 = ts.add(2.2);
boolean added3 = ts.add(1.1);
System.out.println(added1 + ", " + added2 + ", " + added3);
}
}
✅ Correct Answer: B) true, true, false
The add() method of TreeSet returns true if the element was added successfully (it's new) and false if the element was already present (a duplicate).
Q1849easy
Does the `run()` method defined in the `Runnable` interface return any value?
✅ Correct Answer: B) No, its return type is `void`.
The `run()` method signature is `public void run()`, indicating that it does not return any value. For returning values, `Callable` interface is used.
Q1850easycode output
What is the output of this code?
java
interface First {
void methodOne();
}
interface Second {
void methodTwo();
}
class MyClass implements First, Second {
@Override
public void methodOne() {
System.out.println("Method One executed.");
}
@Override
public void methodTwo() {
System.out.println("Method Two executed.");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.methodOne();
obj.methodTwo();
}
}
✅ Correct Answer: A) Method One executed.
Method Two executed.
A class can implement multiple interfaces, providing concrete implementations for all their abstract methods. Both `methodOne()` and `methodTwo()` are called sequentially, printing their respective messages.
Q1851hard
Beyond automatic resource closure, what significant advantage does `try-with-resources` offer over using a traditional `try-finally` block for managing `AutoCloseable` resources, particularly concerning multiple exceptions?
✅ Correct Answer: C) It automatically handles and suppresses exceptions that occur during resource closure, preventing them from obscuring the primary exception.
`try-with-resources` elegantly handles scenarios where both the `try` block and the resource's `close()` method throw exceptions, by making the `close()` exception suppressed on the primary exception, preventing loss of context.
Q1852hard
A method `A.method()` declares `throws IOException`. A subclass method `B.method()` overrides it. Which exception declaration is *invalid* for `B.method()`?
✅ Correct Answer: C) `public void method() throws Exception`
An overriding method cannot declare to throw broader checked exceptions than the superclass method. `Exception` is broader than `IOException`, making option C invalid. Options A and B are valid (narrower or fewer checked exceptions), and option D is valid as `RuntimeException` is unchecked.
Q1853easycode error
What is the error in this code?
java
import java.util.TreeMap;
class MyKey { /* No Comparable implementation */ }
public class Test {
public static void main(String[] args) {
TreeMap<MyKey, String> map = new TreeMap<>();
map.put(new MyKey(), "Value1");
map.put(new MyKey(), "Value2");
}
}
✅ Correct Answer: A) java.lang.ClassCastException
When no custom Comparator is provided, TreeMap uses the natural ordering of keys. This requires keys to implement the Comparable interface. Since MyKey does not, a ClassCastException occurs when the first element is inserted and TreeMap attempts to cast it to Comparable.
Q1854easy
If the condition in a do-while loop is initially false, what happens?
✅ Correct Answer: A) The loop body executes once, then the loop terminates.
Even if the condition is initially false, the 'do' block executes first. After that single execution, the condition is evaluated, found false, and the loop terminates.
Q1855hardcode output
What is the output of this Java code?
java
String a = new String("abc");
String b = "abc";
String c = "a" + "bc";
String d = a.intern();
System.out.println(a == b);
System.out.println(b == c);
System.out.println(d == b);
✅ Correct Answer: A) false
true
true
`new String("abc")` creates a new object on the heap, so `a == b` is `false`. `"a" + "bc"` is a compile-time constant, so `c` refers to the same string pool literal as `b`, making `b == c` `true`. `a.intern()` returns the reference from the string pool, which is the same as `b`, so `d == b` is `true`.
Q1856medium
Consider two object reference variables, `obj1` and `obj2`. If `obj2 = obj1;` is executed, what is the outcome?
✅ Correct Answer: C) Both `obj1` and `obj2` now refer to the exact same object in memory.
In Java, object reference assignments do not create new objects or copy object data. Instead, both reference variables will point to the same object in memory.
Q1857easy
What is the primary characteristic of method overloading in Java?
✅ Correct Answer: A) Methods with the same name but different parameter lists.
Method overloading allows multiple methods within the same class to have the same name, as long as their parameter lists (number, type, or order of parameters) are different.
Q1858hardcode error
What is the runtime error encountered when executing this Java code snippet?
java
import java.util.HashSet;
import java.util.Objects;
class DisposableKey {
String id;
boolean disposed = false;
public DisposableKey(String id) { this.id = id; }
public void dispose() { this.disposed = true; }
@Override
public int hashCode() {
if (disposed) { throw new IllegalStateException("Hashed a disposed key!"); }
return Objects.hashCode(id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DisposableKey that = (DisposableKey) o;
if (this.disposed || that.disposed) { throw new IllegalStateException("Compared disposed keys!"); }
return Objects.equals(id, that.id);
}
}
public class Main {
public static void main(String[] args) {
HashSet<DisposableKey> set = new HashSet<>();
DisposableKey key1 = new DisposableKey("data1");
set.add(key1);
key1.dispose(); // Key state changes after being added
set.contains(new DisposableKey("data1")); // Triggering hashCode/equals on potentially disposed key
}
}
✅ Correct Answer: B) java.lang.IllegalStateException
After `key1` is added to the `HashSet`, its `dispose()` method is called, changing its internal state. When `set.contains()` is subsequently called, it will invoke `hashCode()` and/or `equals()` on objects in the set, including the now-disposed `key1`. This triggers the explicit `IllegalStateException` defined in the `hashCode` and `equals` methods.
Q1859easycode output
What is the output of the following Java program?
java
public class Test {
public static void main(String[] args) {
int[] arr1 = {10, 20};
int[] arr2 = arr1;
arr2[0] = 5;
System.out.println(arr1[0]);
}
}
✅ Correct Answer: C) 5
Arrays are reference types. When `arr2 = arr1;` is executed, both `arr1` and `arr2` refer to the *same* array object in memory. Modifying `arr2[0]` also changes `arr1[0]`.
Q1860easy
Does `java.util.HashSet` allow `null` elements?
✅ Correct Answer: C) Yes, it allows exactly one `null` element.
`HashSet` permits the `null` element, but like any other element, only one `null` value can be stored in the set to maintain uniqueness.