public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abacaba");
int idx1 = sb.indexOf("a", 1);
int idx2 = sb.indexOf("b", 3);
System.out.println(idx1 + " " + idx2);
}
}
✅ Correct Answer: A) 2 5
`sb.indexOf("a", 1)` searches for 'a' starting from index 1, finding it at index 2. `sb.indexOf("b", 3)` searches for 'b' starting from index 3, finding it at index 5.
Q2722easycode output
What is the output of this Java code?
java
import java.util.LinkedList;
public class MyClass {
public static void main(String[] args) {
LinkedList<Integer> nums = new LinkedList<>();
nums.add(1);
nums.add(2);
nums.add(3);
nums.remove(1);
System.out.println(nums.size());
}
}
✅ Correct Answer: A) 2
The list initially has 3 elements: [1, 2, 3]. `remove(1)` removes the element at index 1 (which is 2). The list becomes [1, 3], and its size is 2.
Q2723mediumcode error
What is the exception printed to the console when the following Java code is executed, assuming 'nonwritable_dir' is a path where the user lacks write permissions?
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
String filePath = "/path/to/nonwritable_dir/output.txt"; // Assume this path causes permission issues
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write("Attempt to write");
} catch (IOException e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
✅ Correct Answer: C) IOException: Permission denied
When `FileWriter` attempts to create or open a file at a path where the program lacks write permissions, it typically throws an `IOException` with a message indicating 'Permission denied' (or similar system-level error message).
Q2724easy
How do you find the number of elements in a single-dimensional array named `myArray`?
✅ Correct Answer: A) myArray.length
Arrays in Java have a public `length` field that stores the number of elements they can hold.
Q2725hardcode output
What is the output of this code?
java
import java.io.IOException;
class MyResource implements AutoCloseable {
public void close() throws IOException {
System.out.print("Closing ");
throw new IOException("Resource close failed");
}
}
public class Test {
public static void main(String[] args) {
try (MyResource res = new MyResource()) {
System.out.print("In try ");
throw new RuntimeException("Try block failed");
} catch (Exception e) {
System.out.print("Caught: " + e.getMessage());
if (e.getSuppressed().length > 0) {
System.out.print(" Suppressed: " + e.getSuppressed()[0].getMessage());
}
}
}
}
✅ Correct Answer: A) In try Closing Caught: Try block failed Suppressed: Resource close failed
In a try-with-resources statement, if both the try block and the resource's `close()` method throw exceptions, the exception from the try block is the primary one, and the exception from `close()` is suppressed. Both print statements execute.
Q2726hardcode error
What error occurs when attempting to compile the following Java code?
java
public class InvalidIfConditionType {
public static void main(String[] args) {
boolean active = true;
int count = 5;
if (active && count) { // 'count' (int) cannot be implicitly converted to boolean
System.out.println("Active and count present.");
} else {
System.out.println("Inactive or no count.");
}
}
}
✅ Correct Answer: B) Compilation error: operator `&&` cannot be applied to boolean, int
The logical AND operator `&&` requires both its operands to be of type `boolean`. In this code, `count` is an `int`, which cannot be implicitly converted to `boolean` in Java. This results in a compile-time error due to incompatible types for the operator.
Q2727hardcode output
What is the output of this Java program?
java
public class SleepInterruptStatus {
public static void main(String[] args) throws InterruptedException {
Thread sleeper = new Thread(() -> {
try {
System.out.println("Sleeper: Going to sleep.");
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Sleeper: Interrupted while sleeping!");
System.out.println("Sleeper: Is interrupted after catch: " + Thread.currentThread().isInterrupted());
}
System.out.println("Sleeper: Finishing.");
});
sleeper.start();
Thread.sleep(100);
sleeper.interrupt();
sleeper.join();
}
}
✅ Correct Answer: A) Sleeper: Going to sleep.
Sleeper: Interrupted while sleeping!
Sleeper: Is interrupted after catch: false
Sleeper: Finishing.
When `Thread.sleep()` is interrupted, it throws `InterruptedException` and *clears* the interrupted status of the thread. Thus, inside the `catch` block, `Thread.currentThread().isInterrupted()` returns `false`.
Q2728hard
Which of the following `Spliterator` characteristics would a `java.util.LinkedList`'s spliterator generally possess?
✅ Correct Answer: C) ORDERED, SIZED, SUBSIZED
A `LinkedList`'s spliterator is `ORDERED` because its elements have a defined encounter order. It is `SIZED` and `SUBSIZED` because the size is known and can be accurately reported for itself and its sub-spliterators.
Q2729hard
Why does `TreeSet` rely on the `compareTo()` (or `compare()`) method for ordering and uniqueness rather than the `equals()` and `hashCode()` methods, unlike `HashSet`?
✅ Correct Answer: A) Because `TreeSet` implements `SortedSet` and `NavigableSet`, which require a total ordering of elements, a functionality that `equals()` and `hashCode()` do not provide.
`TreeSet` needs a consistent way to order elements to build its Red-Black tree structure and maintain sorted order. The `compareTo()`/`compare()` methods provide this total ordering, which `equals()` and `hashCode()` cannot guarantee for ordering purposes.
Q2730easy
Which method of `BufferedWriter` is used to write a platform-independent new line character?
✅ Correct Answer: B) `newLine()`
The `newLine()` method of `BufferedWriter` writes a line separator string. This string is specific to the operating system, ensuring platform independence.
Q2731mediumcode error
What is the error in the following Java code?
java
package com.example;
class Car {
private String model;
public Car(String model) {
this.model = model;
}
private void displayModel() {
System.out.println("Model: " + model);
}
}
public class Showroom {
public static void main(String[] args) {
Car myCar = new Car("Tesla Model 3");
myCar.displayModel();
}
}
✅ Correct Answer: A) Compilation error: The method displayModel() is not visible.
The 'displayModel()' method is declared as private, meaning it cannot be invoked directly from outside the Car class, even by an instance of Car in another class. This leads to a compilation error.
Q2732hard
What happens if a `continue` statement is placed directly inside a `case` block of a `switch` statement that is not itself enclosed within any loop?
✅ Correct Answer: B) A compile-time error occurs because `continue` is only valid within loops.
The `continue` statement is specifically designed to skip the rest of the current iteration of a loop and proceed to the next iteration. It has no meaning outside of a loop context, so using it directly in a `switch` statement that is not inside a loop will result in a compile-time error.
Q2733easycode output
What does this Java code print?
java
public class LoopTest {
public static void main(String[] args) {
int count = 2;
for (int i = 0; i < count; i++) {
System.out.print("*");
}
}
}
✅ Correct Answer: A) **
The loop iterates for i = 0 and i = 1 because the condition `i < count` (i < 2) is true for these values, printing '*' twice.
Q2734hardcode error
What is the result of executing this Java code snippet?
java
interface Shape { }
class Circle implements Shape { }
class Square implements Shape { }
public class CastingPuzzle {
public static void main(String[] args) {
Shape s = new Circle();
Square sq = (Square) s;
System.out.println("No error");
}
}
✅ Correct Answer: A) A ClassCastException occurs at runtime.
The variable 's' references a Circle object. Although 's' is declared as type Shape (which both Circle and Square implement), a Circle object cannot be cast directly to a Square object at runtime, as they are unrelated classes in the inheritance hierarchy. This leads to a ClassCastException.
Q2735hard
If a constructor in a superclass declares a checked exception, e.g., `public SuperClass() throws IOException`, what must be true for a subclass constructor?
✅ Correct Answer: B) The subclass constructor must also declare `throws IOException` or a superclass of `IOException`.
When a superclass constructor declares a checked exception, any subclass constructor that implicitly or explicitly calls `super()` must also declare that checked exception (or a superclass of it) in its `throws` clause, or handle it within a `try-catch` block.
Q2736hardcode error
What is the compilation error, if any, for the provided Java code snippet?
java
class Overloader {
public void inspect(String s) {}
public void inspect(String[] arr) {}
public static void main(String[] args) {
Overloader o = new Overloader();
o.inspect(null); // Line X
}
}
✅ Correct Answer: B) error: reference to inspect is ambiguous
Both `String` and `String[]` are reference types, and `null` can be assigned to either. Neither type is considered more specific than the other when `null` is the argument, causing the compiler to report an ambiguous method call.
Q2737easycode output
What does this Java code print?
java
public class TypeCast {
public static void main(String[] args) {
char letter = 'C';
int asciiValue = letter;
System.out.println(asciiValue);
}
}
✅ Correct Answer: A) 67
When a char is assigned to an int, it undergoes widening (implicit) casting, converting the character to its corresponding ASCII/Unicode integer value.
Q2738hard
Under what circumstances might it be beneficial to explicitly create a `BufferedReader` with a custom, significantly larger buffer size (e.g., `new BufferedReader(reader, 65536)`), rather than relying on the default buffer size?
✅ Correct Answer: B) When the underlying stream is known to be very slow, and reads are performed in very large, contiguous blocks.
A larger buffer can be beneficial when underlying I/O operations are expensive (e.g., network streams), and the application consistently reads data in large, contiguous chunks, as it reduces the number of costly calls to the underlying stream.
Q2739hard
The Liskov Substitution Principle (LSP) is a core principle underpinning robust polymorphism. Which statement best captures the essence of LSP in object-oriented design?
✅ Correct Answer: A) Derived classes must be completely interchangeable with their base classes without altering the desirable properties or correctness of the program.
The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. It ensures that polymorphism is used in a way that preserves the contract of the base type.
Q2740easy
How must a constructor be named in Java?
✅ Correct Answer: B) It must be named the same as its class.
A constructor's name must exactly match the name of the class in which it is defined.