public class ArrayOutOfBoundsLoop {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
✅ Correct Answer: A) java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
The loop condition `i <= numbers.length` allows `i` to reach `3`. When `i` is `3`, `numbers[3]` is accessed, which is beyond the valid indices `0, 1, 2`, causing an `ArrayIndexOutOfBoundsException`.
Q1162easycode error
What is the compilation error in the following Java code snippet?
java
public class LoopError {
public static void main(String[] args) {
int counter = 5;
do; {
System.out.println(counter);
counter--;
} while (counter > 0);
}
}
✅ Correct Answer: B) A semicolon immediately after `do` makes it an empty statement, leading to a syntax error with the subsequent block.
Placing a semicolon directly after `do` (`do;`) creates an empty `do` statement. The subsequent `{...}` block is then treated as a standalone block of code, not part of a `do-while` loop, leading to a syntax error when the `while` keyword is expected later.
Q1163hardcode error
What type of error will this Java code generate during compilation?
java
class Test {
public static void main(String[] args) {
int count = 0;
do {
count++;
} while (count); // 'count' is an int
System.out.println("Done.");
}
}
✅ Correct Answer: C) Incompatible types: int cannot be converted to boolean
The `while` condition of a `do-while` loop must evaluate to a boolean type. Here, `count` is an `int`, which cannot be implicitly converted to a `boolean`, resulting in an "incompatible types" error.
Q1164medium
If you attempt to add an element that already exists (based on its comparison) in a `TreeSet`, what will be the outcome?
✅ Correct Answer: B) The `add()` method will return `false`, and the set will remain unchanged.
Like all `Set` implementations, `TreeSet` does not allow duplicate elements. If an element equivalent to one already in the set is added, `add()` returns `false`.
Q1165hardcode output
What is the output of this code?
java
public class VarShadowing {
public static void main(String[] args) {
String value = "Outer";
{
// This line attempts to redeclare 'value' in an inner scope.
// Local variable type inference (var) does not change scoping rules.
var value = "Inner";
System.out.println(value);
}
System.out.println(value);
}
}
✅ Correct Answer: C) Compilation Error
A local variable cannot be declared twice in the same scope or in an inner block if it's already visible in the outer scope. The `var` keyword does not bypass this Java scoping rule, leading to a compilation error due to redeclaration.
Q1166hardcode output
What does this code print?
java
abstract class Elem {
String tag = "generic";
void render() { System.out.println("Render: " + tag); paint(); }
abstract void paint();
}
class Button extends Elem {
Button(String t) { this.tag = t; }
@Override void paint() { System.out.println("Paint Button: " + tag); }
}
public class Main {
public static void main(String[] args) {
Elem e = new Button("Submit");
e.render();
}
}
✅ Correct Answer: A) Render: Submit
Paint Button: Submit
The `Button` constructor sets the `tag` field inherited from `Elem`. The `render()` method, called on the `Button` instance, prints the updated `tag` and then invokes the overridden `paint()` method, which also uses the updated `tag`.
Q1167easycode error
What is the error in this code?
java
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
TreeMap<int, String> map = new TreeMap<>();
map.put(10, "Ten");
System.out.println(map.get(10));
}
}
✅ Correct Answer: A) Compilation Error: unexpected type, found int, required reference
Java generics do not support primitive types. When declaring a `TreeMap`, its key and value types must be reference types (objects). `int` is a primitive type, so it causes a compilation error. `Integer` (the wrapper class) should be used instead.
Q1168easycode error
What type of error will this Java code produce when executed?
java
import java.util.Queue;
import java.util.LinkedList;
public class QueueError {
public static void main(String[] args) {
Queue rawQueue = new LinkedList();
rawQueue.offer("Hello");
rawQueue.offer(123);
Integer value = (Integer) rawQueue.peek();
System.out.println(value);
}
}
✅ Correct Answer: A) ClassCastException
The `peek()` method returns the head of the queue without removing it. In this case, 'Hello' (a String) is at the head. Attempting to cast it to `Integer` will cause a `ClassCastException`.
Q1169hard
Consider the following code:
java
import java.util.function.Function;
Function<String, Integer> f1 = Integer::parseInt;
Function<Integer, String> f2 = i -> "Value: " + i;
Function<String, String> f3 = f1.andThen(f2);
Function<Integer, Integer> f4 = i -> i * 2;
Which of the following chained functional interface operations will compile successfully?
✅ Correct Answer: D) Function<Integer, String> result = f2.compose(f4);
`f2.compose(f4)` means `f4` is applied first, then `f2`. `f4` (Integer -> Integer) output type matches `f2` (Integer -> String) input type, resulting in a `Function<Integer, String>`, which matches the declared type.
Q1170mediumcode error
What error occurs when compiling this Java code?
java
public class MyClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
String s = sb;
System.out.println(s);
}
}
✅ Correct Answer: C) Compile-time error: incompatible types: StringBuffer cannot be converted to String
A `StringBuffer` object cannot be directly assigned to a `String` reference because `StringBuffer` and `String` are distinct, non-hierarchical types. This will cause a compile-time error due to incompatible types. To convert, `sb.toString()` must be used.
Q1171mediumcode output
What is printed when this Java code is executed?
java
public class FinallyUncaughtException {
public static void main(String[] args) {
try {
System.out.println("In try block");
Integer.parseInt("abc"); // Throws NumberFormatException
} finally {
System.out.println("In finally block");
}
System.out.println("Program finished");
}
}
✅ Correct Answer: A) In try block
In finally block
(followed by NumberFormatException stack trace)
The `try` block prints its message and then throws a `NumberFormatException`. Since there is no `catch` block to handle it, the `finally` block still executes before the program terminates due to the uncaught exception. The `Program finished` line is never reached.
Q1172hard
Consider the method `file.setWritable(true, false)`. What is the precise effect of the second argument (`false`) on a Unix-like operating system?
✅ Correct Answer: A) The file will be made writable only for the owner of the file, revoking write permissions for the group and others if they previously had them.
The second argument (`ownerOnly`) controls whether the change applies only to the owner (`false`) or to all users (`true`). Thus, `setWritable(true, false)` sets the file writable for the owner only.
Q1173easycode error
What compile-time error will this code produce?
java
class MyJob {
public void execute() {
System.out.println("Executing job...");
}
}
public class Main {
public static void main(String[] args) {
MyJob job = new MyJob();
Thread thread = new Thread(job);
thread.start();
}
}
✅ Correct Answer: A) Error: no suitable constructor found for Thread(MyJob)
The `Thread` constructor that accepts an object expects an instance of a class that implements the `Runnable` interface. `MyJob` does not implement `Runnable`, so there is no suitable constructor for `Thread`.
Q1174hardcode output
What is the output of this Java code snippet, assuming the process has initial write permissions to the created file?
✅ Correct Answer: A) Initial canWrite: true
setWritable(false) result: true
After setWritable(false) canWrite: false
setWritable(true, true) result: true
After setWritable(true, true) canWrite: true
Initially, a newly created file is writable. `setWritable(false)` successfully removes write permissions for all, making `canWrite()` false. `setWritable(true, true)` then restores write permissions *for the owner only*. Since the current process is the owner, `canWrite()` becomes true again.
Q1175hard
When converting an `ArrayList<String>` to a `String[]` array, what is the crucial difference and potential advantage of using `toArray(T[] a)` over `toArray()`?
✅ Correct Answer: B) `toArray()` returns an `Object[]`, requiring a downcast and risking `ClassCastException` at runtime; `toArray(T[] a)` returns a type-safe `T[]`.
`toArray()` returns an `Object[]`, which then requires a cast to `String[]` that can fail at runtime if the list elements are not `String`s. `toArray(T[] a)` allows you to provide a pre-sized array of the correct type (`new String[0]`), ensuring a type-safe `String[]` is returned directly, avoiding the `ClassCastException` risk and often being more efficient by potentially reusing the provided array.
Q1176mediumcode output
What is the output of this code?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("C");
list.remove(1);
list.add(1, "D");
System.out.println(list.get(2));
}
}
✅ Correct Answer: C) C
Initially, the list is [A, B, C]. `list.remove(1)` removes 'B', making the list [A, C]. `list.add(1, "D")` inserts 'D' at index 1, resulting in [A, D, C]. Finally, `list.get(2)` retrieves the element at index 2, which is 'C'.
Q1177mediumcode error
What is the error in this Java code snippet?
java
public class MyClass {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.deleteCharAt(4);
System.out.println(sb);
}
}
✅ Correct Answer: B) A runtime error: StringIndexOutOfBoundsException.
The length of 'Java' is 4, so valid indices are 0 to 3. Attempting to delete a character at index 4 (which is out of bounds) will result in a StringIndexOutOfBoundsException at runtime.
Q1178hardcode output
What is the output of this code?
java
public class Test {
public static void main(String[] args) {
String result = "";
outer: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 0) continue outer;
if (i == 2 && j == 1) break;
result += i + "" + j;
}
}
System.out.print(result);
}
}
✅ Correct Answer: B) 00010220
For i=1, j=0, `continue outer` skips to the next iteration of the outer loop, preventing '10', '11', '12' from being printed. For i=2, j=1, `break` exits the inner loop, preventing '21', '22' from being printed.
Q1179hardcode error
Which exception is thrown when the `main` method of this Java code is executed?
java
public class GetBytesUnsupportedEncoding {
public static void main(String[] args) {
String s = "Hello World";
try {
byte[] bytes = s.getBytes("UTF-160000"); // An intentionally invalid encoding name
System.out.println(new String(bytes));
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
✅ Correct Answer: A) java.io.UnsupportedEncodingException
The `getBytes(String charsetName)` method requires `charsetName` to be a valid, supported encoding. Providing an invalid or unrecognized name like "UTF-160000" will cause an `UnsupportedEncodingException`.
Q1180easy
Which method of `BufferedReader` is commonly used to read an entire line of text?
✅ Correct Answer: B) `readLine()`
The `readLine()` method in `BufferedReader` reads a line of text, returning a String, or `null` if the end of the stream has been reached.