What is the compilation error in the following Java code snippet?
java
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<String> stringConsumer = (Integer i) -> {
System.out.println("Consumed: " + i);
};
stringConsumer.accept("Hello");
}
}
✅ Correct Answer: A) Incompatible parameter types in lambda expression: expected String but found Integer
The target type `Consumer<String>` implies that the lambda expression should accept a `String` parameter. However, the lambda explicitly declares its parameter as `(Integer i)`, leading to an 'incompatible parameter types' compilation error.
Q1802easy
When is a constructor invoked in Java?
✅ Correct Answer: B) When an object of the class is created using the 'new' keyword.
A constructor is automatically invoked every time an object of its class is instantiated using the `new` operator.
Q1803easycode error
What error will occur when this code is executed?
java
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Program");
sb.deleteCharAt(7);
System.out.println(sb);
}
}
✅ Correct Answer: C) StringIndexOutOfBoundsException
The `StringBuffer` "Program" has a length of 7, with valid character indices from 0 to 6. Attempting to `deleteCharAt(7)` is out of bounds, causing a `StringIndexOutOfBoundsException`.
Q1804easycode output
What is the output of this Java code?
java
public class ThreadPriorityDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread priority: " + Thread.currentThread().getPriority());
});
thread.start();
}
}
✅ Correct Answer: A) Thread priority: 5
By default, a newly created thread inherits the priority of its parent thread. The main thread typically has a priority of 5 (Thread.NORM_PRIORITY), so the new thread will also have a priority of 5.
Q1805easycode error
What is the output or error of the following Java code?
java
public class ExceptionTest {
public static void main(String[] args) {
try {
System.out.println("No exception here.");
} catch (java.io.IOException e) {
System.out.println("Caught IOException");
}
}
}
✅ Correct Answer: C) Compilation Error: Unreported exception java.io.IOException; must be caught or declared to be thrown.
The 'try' block does not throw an 'IOException' (which is a checked exception). If a 'try' block doesn't throw a checked exception, a 'catch' block for that checked exception is not allowed and will result in a compilation error.
Q1806hard
Consider a class `MyClass<T>` with two constructors: `MyClass(T value)` and `MyClass()`. If you need to create a `Supplier<MyClass<String>>` using a method reference, which reference is valid?
✅ Correct Answer: B) `MyClass::new`
For a `Supplier<MyClass<String>>`, the `get()` method takes no arguments and returns `MyClass<String>`. The method reference `MyClass::new` implicitly selects the no-argument constructor `MyClass()` because the target type `Supplier` expects no arguments. The type argument `String` is inferred from the target type.
Q1807hardcode error
What is the compile-time error in this Java code?
java
public class AnonymousNonEffectivelyFinal {
public static void main(String[] args) {
int data = 100;
Runnable job = new Runnable() {
@Override
public void run() {
// System.out.println("Data: " + data); // Line 7
}
};
data = 200; // This makes 'data' not effectively final for 'job'
new Thread(job).start();
}
}
✅ Correct Answer: A) Compile-time error: local variables referenced from an inner class must be final or effectively final (at Line 7)
An anonymous inner class can only access local variables from its enclosing scope if they are final or effectively final. Since `data` is reassigned after the `Runnable` definition, it is no longer effectively final, causing a compile-time error if accessed inside `run()`.
Q1808easy
Can an `ArrayList` store duplicate elements?
✅ Correct Answer: B) Yes, `ArrayList` can store duplicate elements.
`ArrayList` allows duplicate elements because it maintains insertion order and allows elements at different indices to be identical. This is a characteristic of all `List` implementations.
Q1809medium
What happens if you try to modify an `ArrayList` (e.g., add or remove elements) while iterating over it using a standard `for-each` loop?
✅ Correct Answer: C) A `ConcurrentModificationException` will likely be thrown.
Modifying an `ArrayList` directly during iteration with a fail-fast iterator (like those used by `for-each` loops) typically results in a `ConcurrentModificationException` because the iterator detects a structural change.
Q1810easycode output
What is the output of this Java code?
java
public class WhileLoopDemo {
public static void main(String[] args) {
int x = 0;
int y = 5;
while (x < 2 && y > 3) {
System.out.print(x);
x++;
y--;
}
}
}
✅ Correct Answer: A) 01
The loop continues as long as both conditions (`x < 2` AND `y > 3`) are true. It prints 0 (x=0, y=5) and 1 (x=1, y=4). In the next iteration, x becomes 2 and y becomes 3, making `x < 2` false and `y > 3` false, so the loop terminates.
Q1811medium
If you obtain an `Iterator` from a `LinkedList` and then call the `remove()` method on that `Iterator`, what does it remove?
✅ Correct Answer: C) The element that was last returned by the `next()` method.
According to the `Iterator` contract, the `remove()` method removes the last element that was returned by the `next()` method from the underlying collection. This applies to `LinkedList` iterators as well.
Q1812easycode error
What is the error in this Java code?
java
abstract class Shape {
abstract void draw();
void description() {
System.out.println("This is a shape.");
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Shape(); // Line 10
}
}
✅ Correct Answer: C) Compile-time error: Shape is abstract; cannot be instantiated
Abstract classes cannot be instantiated directly using the `new` keyword. They must be subclassed, and their concrete subclasses are then instantiated.
Q1813mediumcode error
Which compile-time error will this Java code produce?
java
public class Test {
public static void main(String[] args) {
myLoop for (int i = 0; i < 5; i++) {
if (i == 2) {
break myLoop;
}
System.out.print(i);
}
}
}
✅ Correct Answer: A) Compile-time error: illegal start of expression or missing colon after label 'myLoop'.
A label in Java must be followed by a colon (`:`). The syntax `myLoop for` is incorrect; it should be `myLoop: for`. This missing colon makes `myLoop` an identifier followed by an unexpected keyword `for`, leading to a compile-time syntax error.
Q1814easycode error
Which error will occur when compiling this Java code?
java
import java.io.FileReader;
public class FileReaderIssue {
public static void main(String[] args) {
FileReader reader = new FileReader("nonexistent.txt");
System.out.println("File reader created.");
}
}
✅ Correct Answer: B) A compile-time error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown.
The FileReader constructor can throw a FileNotFoundException, which is a checked exception. Since it's not caught or declared in the main method signature, a compile-time error occurs.
Q1815mediumcode output
What does this code print?
java
import java.util.stream.Stream;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
public class StreamTest {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean allEven = numbers.stream()
.filter(n -> n > 1)
.allMatch(n -> n % 2 == 0);
System.out.println(allEven);
}
}
✅ Correct Answer: A) false
The stream first filters numbers greater than 1, resulting in [2, 3, 4, 5]. Then `allMatch(n -> n % 2 == 0)` checks if ALL of these numbers are even. Since 3 and 5 are odd, it returns false.
Q1816hard
When processing data from an external resource (e.g., network stream) using a `while` loop that reads until EOF or an error, what crucial concern must be addressed if `try-with-resources` is *not* used, to prevent resource leaks in case of an unexpected exception within the loop?
✅ Correct Answer: A) Placing the entire `while` loop inside a `try-catch-finally` block, ensuring resource closure in the `finally` block.
A `finally` block guarantees that its code will execute regardless of whether an exception occurs or the loop terminates normally. This makes it ideal for ensuring critical resource closure to prevent leaks.
Q1817mediumcode output
What does this code print?
java
import jakarta.validation.*;
import jakarta.validation.constraints.Min;
import java.util.Set;
public class Test {
static class Part {
@Min(5) public int value;
public Part(int v) { this.value = v; }
}
static class Machine {
@Valid public Part part; // @Valid here
public Machine(Part p) { this.part = p; }
}
public static void main(String[] args) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Machine machine = new Machine(null); // part is null
Set<ConstraintViolation<Machine>> violations = validator.validate(machine);
System.out.println("Violations: " + violations.size());
}
}
✅ Correct Answer: A) Violations: 0
The `@Valid` annotation only cascades validation if the nested object itself is not `null`. If `part` is `null` and there's no explicit `@NotNull` on the `Machine.part` field, no violations will be found because the nested constraints cannot be evaluated.
Q1818easycode error
What error will occur when compiling the following Java code?
java
import java.util.HashSet;
import java.util.Set;
public class MyClass {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
System.out.println(numbers.get(0)); // This line will cause an error
}
}
✅ Correct Answer: B) cannot find symbol method get(int)
The `HashSet` class does not have a `get(int index)` method because it does not maintain elements in a specific order and does not support indexed access. This will result in a compile-time error.
Q1819mediumcode output
What does this code print?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
boolean contains20 = numbers.contains(20);
numbers.remove(new Integer(10));
System.out.println(contains20 + " " + numbers.size());
}
}
✅ Correct Answer: C) true 2
The list initially is [10, 20, 30]. `numbers.contains(20)` returns `true`. `numbers.remove(new Integer(10))` calls the `remove(Object o)` method, removing the first occurrence of 10. The list becomes [20, 30], with a size of 2. So, it prints 'true 2'.
Q1820hardcode error
What is the compilation error in the following Java code?
java
package com.example;
private class TopLevelPrivate {
public void greet() {
System.out.println("Hello from private class");
}
}
public class Main {
public static void main(String[] args) {
// Code to test TopLevelPrivate would go here, but the class itself is the issue.
}
}
✅ Correct Answer: B) Error: Illegal modifier for the class TopLevelPrivate; only public, abstract & final are permitted.
Top-level classes in Java cannot be declared with the `private` access modifier. Only `public`, `abstract`, or `final` are permitted for top-level types, as `private` would make the class inaccessible to all other classes, including within its own package.