class MyCustomException extends Exception { public MyCustomException(String msg) { super(msg); } }
class MyCustomError extends Error { public MyCustomError(String msg) { super(msg); } }
public class Main {
public static void riskyOperation() throws MyCustomException { throw new MyCustomException("Operation failed"); }
public static void callerMethod() {
try { riskyOperation(); }
catch (MyCustomException e) { System.out.println("Caught Exception in caller: " + e.getMessage()); throw new MyCustomError("Critical failure!"); }
finally { System.out.println("Finally in caller."); }
}
public static void main(String[] args) {
try { callerMethod(); }
catch (MyCustomError e) { System.out.println("Caught Error in main: " + e.getMessage()); }
catch (Throwable t) { System.out.println("Caught general Throwable: " + t.getClass().getSimpleName() + ": " + t.getMessage()); }
}
}
✅ Correct Answer: A) Caught Exception in caller: Operation failed
Finally in caller.
Caught Error in main: Critical failure!
The `riskyOperation` throws `MyCustomException`. This is caught in `callerMethod`, which then prints a message and throws `MyCustomError`. The `finally` block executes immediately after the `catch` block and before `MyCustomError` propagates further. The `main` method then catches `MyCustomError`.
Q1682mediumcode error
Which exception will be thrown when executing this Java code?
java
public class StringError8 {
public static void main(String[] args) {
String line = "apple,banana";
int commaIndex = line.indexOf(';'); // returns -1
String fruit = line.substring(0, commaIndex);
System.out.println(fruit);
}
}
✅ Correct Answer: B) java.lang.StringIndexOutOfBoundsException
The `indexOf(';')` call returns -1 because ';' is not found. Subsequently, `substring(0, -1)` is an invalid range (end index cannot be negative), causing a StringIndexOutOfBoundsException.
Q1683easycode error
What compile-time error will occur in the `Child()` constructor?
java
class Parent {
Parent() { System.out.println("Parent"); }
}
class Child extends Parent {
Child() {
System.out.println("Child");
super(); // Not the first statement
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
}
}
✅ Correct Answer: A) call to super must be first statement in constructor
A call to the superclass constructor using `super()` must be the very first statement in the constructor body. Placing any other statement before it will result in a compile-time error.
Q1684hard
From the `NavigableSet` interface implemented by `TreeSet`, which of the following methods return `null` if no element satisfies the condition, instead of throwing an exception?
✅ Correct Answer: C) `lower()`, `floor()`, `ceiling()`, `higher()`
Methods like `lower()`, `floor()`, `ceiling()`, and `higher()` from the `NavigableSet` interface are designed to return `null` if no element matching the specified condition is found, indicating absence without throwing an error.
Q1685medium
What is the primary condition for successfully overloading a method in Java?
✅ Correct Answer: C) Methods must have different parameter lists (number, type, or order of parameters).
Method overloading is determined solely by the method's signature, which includes its name and parameter list. Different return types, access modifiers, or exception declarations alone are not sufficient.
Q1686hardcode output
What is the output of this code?
java
public class OperatorChallenge {
public static void main(String[] args) {
byte b = 126;
b += 1;
b += 1;
System.out.println(b);
}
}
✅ Correct Answer: B) -128
The compound assignment operator `+=` implicitly casts the result of the addition back to the type of the left-hand operand. `b` becomes 127, then adding 1 causes a byte overflow, wrapping around to -128.
Q1687easy
Which Java primitive data type is used to store whole numbers (integers) without decimal points?
✅ Correct Answer: A) int
`int` is the most commonly used primitive data type for storing whole numbers. `float` and `double` are for floating-point numbers, and `String` is for text.
Q1688medium
If a `switch` statement in Java does not have a `default` case and none of the `case` labels match the `switch` expression, what will happen?
✅ Correct Answer: C) The `switch` statement will simply complete without executing any `case` block.
If no `case` matches and no `default` case is present, the `switch` statement simply completes its execution without executing any code block within it.
Q1689hardcode error
Which exception is thrown when the `main` method of this Java code is executed?
java
public class StringFormatError {
public static void main(String[] args) {
long val = 123L;
try {
String formatted = String.format("Value: %d, Text: %s", "abc", val);
System.out.println(formatted);
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
✅ Correct Answer: A) java.util.IllegalFormatConversionException
The format specifier `%d` expects an integer type (byte, short, int, long, BigInteger), but the first argument provided is a `String` ("abc"). This type mismatch results in an `IllegalFormatConversionException`.
Q1690hardcode error
What is the error encountered when running this Java code?
java
public class ArrayStoreError {
public static void main(String[] args) {
Number[] numbers = new Integer[5];
numbers[0] = 10; // Auto-boxes to Integer, valid
numbers[1] = 3.14; // Auto-boxes to Double
System.out.println(numbers[1]);
}
}
✅ Correct Answer: A) java.lang.ArrayStoreException
Although Double is a subclass of Number, the array `numbers` was actually initialized as `new Integer[5]`. Due to array covariance, an `Integer[]` can be assigned to a `Number[]` reference. However, at runtime, the JVM checks the actual component type of the array, which is Integer. Assigning a Double (3.14) to an array of type Integer at runtime causes an ArrayStoreException.
Q1691medium
When an `int` primitive variable is assigned to another `int` primitive variable, what fundamentally happens?
✅ Correct Answer: C) A copy of the value is made and stored in the new variable.
When primitive variables are assigned, the value itself is copied. Unlike reference variables, they do not point to the same memory location; instead, each holds its own independent copy of the value.
Q1692easycode error
What will happen when this Java code is compiled and executed?
java
class MyClass {
public void doSomething() {
throw new java.io.IOException("Error occurred");
}
}
✅ Correct Answer: A) Compilation Error
The `IOException` is a checked exception. A method that throws a checked exception must either declare it in its `throws` clause or handle it with a `try-catch` block. Since neither is done, it results in a compilation error.
Q1693hardcode error
Analyze the following Java code. What compilation error will it produce?
java
public class BlankFinalInstance {
final int id; // Blank final instance variable
public BlankFinalInstance(int id) {
this.id = id;
}
public BlankFinalInstance() {
// Constructor does not initialize 'id'
}
public static void main(String[] args) {
BlankFinalInstance obj = new BlankFinalInstance();
System.out.println(obj.id);
}
}
✅ Correct Answer: A) Error: variable id might not have been initialized.
A blank final instance variable must be initialized in every constructor (or an instance initializer block). Since the no-argument constructor `BlankFinalInstance()` does not initialize `id`, a compile-time error occurs.
Q1694mediumcode error
What compile-time error will occur in the condition of this Java for loop?
java
public class LoopError {
public static void main(String[] args) {
for (int i = 0; 5; i++) {
System.out.println(i);
}
}
}
✅ Correct Answer: B) Compile-time error: incompatible types: int cannot be converted to boolean.
The second part of a for loop's header must be a boolean expression, but here it's an integer literal '5'. Java requires a boolean for the condition, resulting in an 'incompatible types' compile-time error.
Q1695easycode error
What will happen when this Java code is compiled and executed?
java
class MyClass {
public void readFile() throws java.io.FileNotFoundException {}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.readFile();
}
}
✅ Correct Answer: A) Compilation Error
The `readFile()` method declares that it `throws FileNotFoundException` (a checked exception). The `main` method calls `readFile()` but does not handle this checked exception with a `try-catch` block or declare it with `throws`. This leads to a compilation error.
Q1696easycode output
What is the output of this code?
java
public class StringTest {
public static void main(String[] args) {
String s = "Programming";
System.out.println(s.substring(3));
}
}
✅ Correct Answer: B) gramming
The `substring(int beginIndex)` method returns a new string that is a substring of this string. The substring begins with the character at the specified index (3) and extends to the end of the string.
Q1697mediumcode error
What is the compilation error generated by the following Java code?
java
public class DivisionByZeroLiteral {
public static void main(String[] args) {
int x = 10;
int y = x / 0; // Compile-time error due to constant expression
System.out.println(y);
}
}
✅ Correct Answer: A) Division by zero
Java detects division by a constant zero literal at compile time. Unlike division by a variable which might be zero at runtime (leading to `ArithmeticException`), division by the literal `0` is flagged as a compile-time error.
Q1698easycode output
What will be the output of the following Java program?
java
public class Main {
public static void main(String[] args) {
int count = 5;
int initialCount = count;
System.out.println(initialCount);
}
}
✅ Correct Answer: A) 5
The variable `count` is initialized to 5. Then, `initialCount` is initialized with the current value of `count`, which is 5. Printing `initialCount` outputs its value.
Q1699easycode error
What is the compilation or runtime error in the following Java code?
java
public class Main {
public static void main(String[] args) {
String text = "programming";
int index = text.indexOf('g', -1);
System.out.println(index);
}
}
✅ Correct Answer: C) Runtime error: java.lang.StringIndexOutOfBoundsException
The `indexOf(char, fromIndex)` method requires `fromIndex` to be a non-negative integer. Passing -1 as the `fromIndex` results in a `StringIndexOutOfBoundsException` at runtime.
Q1700medium
When is a traditional `for` loop generally preferred over an enhanced `for` (for-each) loop in Java?
✅ Correct Answer: B) When you need to modify the elements of an array or collection during iteration or access elements by index
A traditional `for` loop is necessary when you need to access the index of an element, modify elements of an array/list, or iterate in a non-sequential order.