class Calculator {
public void add(int a, int b) {
System.out.print(a + b);
}
public void add(int a, int b, int c) {
System.out.print(a + b + c);
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(5, 10);
}
}
✅ Correct Answer: A) 15
This is an example of method overloading (compile-time polymorphism). The compiler chooses the `add` method that matches the number and type of arguments provided, which is `add(int a, int b)`.
Q3182easycode error
What kind of error will occur when compiling this Java code?
java
public class Main {
public static void main(String[] args) {
int a = 10;
if (a > 5 && "hello") {
System.out.println("Condition met");
}
}
}
✅ Correct Answer: B) Compile-time Error: Operator '&&' cannot be applied to 'boolean, java.lang.String'.
The logical AND operator '&&' can only be applied to boolean expressions. Here, 'a > 5' is boolean, but '"hello"' is a String. Java does not implicitly convert String to boolean, causing a compile-time error.
Q3183easycode 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("Apple");
String item = list.get(-1); // Accessing negative index
}
}
✅ Correct Answer: B) IndexOutOfBoundsException
Similar to out-of-bounds positive indices, accessing a negative index using `get()` on a `LinkedList` also throws an `IndexOutOfBoundsException` because valid indices must be non-negative.
Q3184easy
What is the primary purpose of a `while` loop in Java?
✅ Correct Answer: B) To execute a block of code repeatedly as long as a condition is true.
A `while` loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.
Q3185easy
Which of these conversions is an example of an implicit (widening) type cast?
✅ Correct Answer: C) int to long
Converting an `int` to a `long` is a widening conversion because `long` has a larger range than `int`, so no data loss occurs and it happens implicitly.
Q3186mediumcode error
What happens when you run this Java code?
java
public class LoopTest {
public static void main(String[] args) {
String text = null;
do {
System.out.println("Attempting to access text...");
} while (text.equals("hello"));
}
}
✅ Correct Answer: B) java.lang.NullPointerException
The 'text' variable is assigned 'null'. Attempting to call a method on a null object, like 'text.equals("hello")', results in a runtime 'java.lang.NullPointerException'.
Q3187mediumcode error
What kind of error will occur when running this Java code?
java
public class ArrayError {
public static void main(String[] args) {
String[] names = new String[3];
System.out.println(names[0].length());
}
}
✅ Correct Answer: C) Runtime error: NullPointerException
When an array of reference types (like `String`) is initialized with `new String[3]`, its elements are automatically set to `null`. Attempting to call a method like `length()` on a `null` reference (e.g., `names[0].length()`) results in a `NullPointerException` at runtime.
Q3188hard
Which statement about the relationship between `this()` and `super()` calls in a constructor is correct?
✅ Correct Answer: C) If a constructor has an explicit `this()` call, the `super()` call will eventually be made by the chained constructor.
A constructor can only have one explicit constructor call (`this()` or `super()`) as its first statement. If `this()` is called, it chains to another constructor within the same class. This chained constructor will then implicitly or explicitly call `super()`, ensuring that a superclass constructor is always invoked at some point in the chain.
Q3189medium
In which of the following contexts is it illegal to use either the `break` or `continue` statement?
✅ Correct Answer: C) Inside an `if` statement that is not enclosed within a loop or `switch`.
Both `break` and `continue` are flow control statements specifically designed for loops (`for`, `while`, `do-while`) and `switch` statements. They cannot be used independently in an `if` statement or any other block not acting as an iteration or selection construct.
Q3190hardcode error
Which compile-time error will this Java code produce?
java
public class TypeTest {
public static void main(String[] args) {
long bigNumber = 2147483648; // Integer literal is 'int' by default
System.out.println(bigNumber);
}
}
✅ Correct Answer: A) Error: integer number too large
Integer literals without a suffix are by default of type 'int'. The value 2147483648 exceeds the maximum value an 'int' can hold (2^31 - 1 = 2147483647), leading to a compile-time error 'integer number too large' even before the assignment to a 'long' variable.
Q3191hardcode error
What is the compile-time error in this Java code snippet involving a lambda expression?
java
import java.io.IOException;
@FunctionalInterface
interface MyFunction {
void execute();
}
public class LambdaProblem {
public static void main(String[] args) {
MyFunction func = () -> {
System.out.println("Executing...");
throw new IOException("Lambda error");
};
}
}
✅ Correct Answer: B) Error: Unhandled exception type IOException; must be caught or declared to be thrown by the lambda expression.
If a lambda expression throws a checked exception, the functional interface method it implements must declare that checked exception in its `throws` clause. Since `MyFunction.execute()` does not declare `throws IOException`, the lambda body cannot throw it without handling it.
Q3192mediumcode output
What does this Java program print?
java
class RethrowExample {
static void riskyOperation() throws Exception {
try {
Integer.parseInt("abc"); // Throws NumberFormatException
} catch (NumberFormatException e) {
System.out.println("NFE caught, rethrowing as generic exception.");
throw new Exception("Failed to parse", e);
}
}
public static void main(String[] args) {
try {
riskyOperation();
} catch (Exception e) {
System.out.println("Caught in main: " + e.getMessage());
}
}
}
✅ Correct Answer: A) NFE caught, rethrowing as generic exception.
Caught in main: Failed to parse
The `riskyOperation` method encounters a `NumberFormatException`, catches it, prints a message, and then rethrows it wrapped in a new `Exception`. The `main` method then catches this new `Exception` and prints its message.
Q3193easy
When adding elements to a `HashSet`, how does it determine if an element is unique?
✅ Correct Answer: C) By using the `hashCode()` and `equals()` methods of the elements.
To ensure uniqueness, `HashSet` relies on the `hashCode()` method for initial element placement and the `equals()` method for checking for exact equality when a hash collision occurs.
Q3194easycode error
Which error will occur when running this Java code?
java
import java.io.FileReader;
import java.io.IOException;
public class FileReaderIssue {
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("nonexistent.txt");
int data = reader.read();
} catch (IOException e) {
System.out.println("Caught an IO Exception.");
} finally {
// Missing null check for reader.close()
// reader.close(); // Problematic line if reader is null
try { if (reader != null) reader.close(); } catch (IOException e) { /* handle */ }
}
}
}
✅ Correct Answer: C) java.lang.NullPointerException at runtime.
If 'nonexistent.txt' does not exist, `new FileReader()` throws `FileNotFoundException`. The `catch` block handles it, but `reader` remains `null`. The `finally` block then attempts to call `reader.close()` on a `null` reference, leading to a `NullPointerException`.
Q3195easycode output
Consider the following Java code. What is its output?
java
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
continue;
}
System.out.print("" + i + j);
}
}
}
}
✅ Correct Answer: A) 00021012
The 'continue' statement skips the current iteration of the inner loop when 'j' is 1. The inner loop proceeds to its next iteration, and the outer loop is unaffected. Thus, values with j=1 are skipped.
Q3196mediumcode error
Which compile-time error will occur when the `changeValue` method attempts to modify `VALUE`?
java
class MyConstant {
final int VALUE;
public MyConstant(int val) {
this.VALUE = val;
}
public void changeValue(int newVal) {
this.VALUE = newVal;
}
}
public class Main {
public static void main(String[] args) {
MyConstant mc = new MyConstant(5);
mc.changeValue(10);
}
}
✅ Correct Answer: B) Compile-time error: 'cannot assign a value to final variable VALUE'.
A `final` instance variable can only be initialized once, either at the point of declaration or within the constructor. Once assigned, its value cannot be changed, and any attempt to reassign it will result in a compile-time error.
Q3197mediumcode output
What is the output of the following Java program?
java
import java.util.stream.Stream;
import java.util.stream.Collectors;
public class StreamTest {
public static void main(String[] args) {
String result = Stream.iterate(1, n -> n + 2)
.limit(3)
.map(String::valueOf)
.collect(Collectors.joining(","));
System.out.println(result);
}
}
✅ Correct Answer: A) 1,3,5
The `iterate` method generates an infinite stream starting with 1 and adding 2 to each subsequent element (1, 3, 5, 7...). `limit(3)` truncates it to the first three elements (1, 3, 5). These are then converted to strings and joined by commas.
Q3198hardcode error
What is the error encountered when running this Java code?
java
import java.util.Arrays;
public class CopyRangeError {
public static void main(String[] args) {
int[] original = {10, 20, 30, 40, 50};
int[] copy = Arrays.copyOfRange(original, 3, 2);
System.out.println(Arrays.toString(copy));
}
}
✅ Correct Answer: A) java.lang.IllegalArgumentException
The `Arrays.copyOfRange(array, from, to)` method requires that the `from` index must be less than or equal to the `to` index. In this case, `from` (3) is greater than `to` (2), which is an invalid range. This condition triggers an `IllegalArgumentException` at runtime.
Q3199hard
In Java, what occurs when a `catch` block attempts to catch a checked exception type that is guaranteed to be unreachable due to a preceding more general `catch` block or the explicit throwing of a narrower exception type?
✅ Correct Answer: C) It results in a compile-time error, specifically 'Unreachable catch block'.
Java's compiler enforces that `catch` blocks must be ordered from most specific to most general exception types. Catching a specific checked exception after a superclass exception (like `catch (Exception e)`) or a type that cannot possibly be thrown due to prior `throw` statements results in a 'Unreachable catch block' compile-time error.
Q3200medium
What is the immediate effect of executing an unlabeled `continue` statement inside a `while` loop?
✅ Correct Answer: C) It skips the remainder of the current iteration's loop body and immediately re-evaluates the loop's boolean condition.
The `continue` statement, when unlabeled, skips the rest of the current iteration of the innermost enclosing loop and proceeds to the next iteration. For a `while` loop, this means re-evaluating the loop condition.