What is the compilation or runtime error in the following Java code?
java
public class Main {
public static void main(String[] args) {
String str = "Java";
char c = str.charAt(str.length());
System.out.println(c);
}
}
✅ Correct Answer: B) Runtime error: java.lang.StringIndexOutOfBoundsException
The `charAt()` method expects an index from 0 to `length() - 1`. Calling `str.charAt(str.length())` attempts to access an index beyond the valid range, leading to a `StringIndexOutOfBoundsException` at runtime.
Q3022hardcode error
What is the error in the logic of this Java code snippet that prevents it from terminating as expected?
java
public class ContinueInfiniteLoop {
public static void main(String[] args) {
int counter = 0;
while (counter < 5) {
System.out.println("Current counter: " + counter);
if (counter % 2 == 0) {
continue; // Skips counter++ if even
}
counter++; // This line is skipped for even numbers
}
System.out.println("Loop finished.");
}
}
✅ Correct Answer: A) The program will hang indefinitely because 'counter' will not increment for even numbers.
When `counter` is an even number (e.g., 0, 2, 4), the `if (counter % 2 == 0)` condition is true, and `continue` is executed. This immediately skips the `counter++` statement, causing `counter` to never increment beyond an even value, leading to an infinite loop.
Q3023mediumcode output
What is the output of this Java code?
java
class StatusThread extends Thread {
public void run() {
System.out.println(getName() + " running.");
try { Thread.sleep(20); } catch (InterruptedException e) {}
System.out.println(getName() + " finished.");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
StatusThread t = new StatusThread();
System.out.println("Initial state: " + t.isAlive());
t.start();
// No sleep here, child might not have started printing yet.
System.out.println("After start state: " + t.isAlive());
t.join(); // Wait for child to complete
System.out.println("Final state: " + t.isAlive());
}
}
✅ Correct Answer: B) Initial state: false
After start state: true
StatusThread-0 running.
StatusThread-0 finished.
Final state: false
Initially, before `t.start()`, `isAlive()` is `false`. After `start()`, the thread becomes alive, so `isAlive()` returns `true`. The main thread continues immediately, printing 'After start state: true', *before* the child thread necessarily gets CPU time to print its 'running' message. The main thread then waits using `t.join()` for the child thread to finish its execution. Once the child thread completes, `isAlive()` returns `false` again.
Q3024hard
A developer needs to read a file that is known to contain only ASCII characters. They are concerned about optimal performance and minimal resource usage. Which statement about `FileReader` and its interaction with charsets for ASCII files is most accurate?
✅ Correct Answer: B) Even for ASCII, `FileReader` still performs character encoding conversions using the default platform charset, which adds overhead compared to direct byte reading.
FileReader always performs character encoding conversions based on the default platform charset. Even for ASCII files, this conversion process adds overhead compared to direct byte reading, as it still involves the charset decoder.
Q3025easycode error
What kind of error will occur when compiling this Java code?
java
import java.io.BufferedWriter;
import java.io.FileWriter;
public class Main {
public static void main(String[] args) {
// The BufferedWriter constructor can throw IOException
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
try {
bw.write("Hello");
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Correct Answer: A) Compile-time error: unreported exception IOException; must be caught or declared to be thrown (for BufferedWriter constructor)
The `BufferedWriter` constructor `new BufferedWriter(new FileWriter("output.txt"))` can throw an `IOException`, which is a checked exception. Since this constructor call is not wrapped in a `try-catch` block that handles `IOException` or declared with `throws IOException` in the `main` method signature, a compile-time error occurs.
Q3026mediumcode output
What is the output of this Java code?
java
@FunctionalInterface
interface StringTransformer {
String transform(String s);
}
public class Test {
public static void main(String[] args) {
StringTransformer upperCase = String::toUpperCase;
StringTransformer reverse = s -> new StringBuilder(s).reverse().toString();
System.out.println(upperCase.transform("hello"));
System.out.println(reverse.transform("world"));
}
}
✅ Correct Answer: A) HELLO
dlrow
The `upperCase` lambda converts "hello" to "HELLO". The `reverse` lambda converts "world" to its reverse, "dlrow".
Q3027medium
What role do abstract methods in an abstract class play in polymorphism?
✅ Correct Answer: C) They define a contract that concrete subclasses *must* implement, thereby enforcing specific behavior.
Abstract methods in an abstract class declare a method signature without an implementation, forcing concrete subclasses to provide their own specific implementations. This enforces a common behavior or contract across a hierarchy while allowing for diverse implementations.
Q3028hard
What is the fundamental difference between using `yield` and `return` inside a `switch` *expression*?
✅ Correct Answer: A) `yield` exits the `switch` expression and provides a value, while `return` exits the enclosing method.
`yield` is a contextual keyword specific to `switch` expressions used to provide a value for the expression and complete its execution. `return`, on the other hand, is a general-purpose keyword that exits the entire method in which it is called, not just the `switch` expression.
Q3029hardcode error
What error occurs when running this Java code?
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class IteratorCMEBetweenOps {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Iterator<Integer> it = numbers.iterator();
it.next(); // 1
it.remove(); // Removes '1', list is now [2, 3, 4, 5]
numbers.add(0, 0); // External structural modification: list is now [0, 2, 3, 4, 5]
it.next(); // Expect CME here
}
}
✅ Correct Answer: A) java.util.ConcurrentModificationException
While iterator.remove() itself is allowed, the subsequent structural modification to the underlying list (numbers.add(0, 0)) invalidates the iterator. The next attempt to use the iterator (it.next()) detects this modification and throws a ConcurrentModificationException.
Q3030mediumcode output
What is the output of this code?
java
public class StringBuilderTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append("World");
System.out.println(sb);
}
}
✅ Correct Answer: A) HelloWorld
The append method concatenates strings without adding spaces. toString() is implicitly called by System.out.println().
Q3031easycode error
What type of error will occur when compiling or running this Java code snippet?
java
public class ArrayTest {
public static void main(String[] args) {
int[] numbers = new int[-5];
System.out.println(numbers.length);
}
}
✅ Correct Answer: C) NegativeArraySizeException
Attempting to create an array with a negative size at runtime will result in a NegativeArraySizeException. Array sizes must be non-negative integers.
Q3032hard
If a `RuntimeException` occurs within a `finally` block, and there was already an exception pending from the `try` or `catch` block, which exception takes precedence and propagates?
✅ Correct Answer: C) The `RuntimeException` from the `finally` block will take precedence and propagate, effectively discarding the original pending exception.
Any exception thrown from a `finally` block takes precedence over (and effectively discards) any exception that was pending from the `try` or `catch` block, becoming the exception that propagates up the call stack.
Q3033easycode output
What is the output of this Java code?
java
class MyThread extends Thread {
public void run() {
System.out.println("Thread started: " + Thread.currentThread().getName());
}
}
public class TestThread {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
System.out.println("Main thread: " + Thread.currentThread().getName());
}
}
✅ Correct Answer: C) The output order is not guaranteed, but both messages will appear.
The `start()` method creates a new thread and calls its `run()` method. Since `main` and the new thread (`t`) run concurrently, the exact order of their `System.out.println` calls is not guaranteed, though both will print.
Q3034medium
Why are getter and setter methods (accessor and mutator methods) crucial for maintaining proper encapsulation?
✅ Correct Answer: C) They provide controlled and validated access to private fields, allowing the class to enforce invariants.
Getters and setters act as controlled interfaces to an object's internal state, enabling validation logic or computed values before data is accessed or modified, thus protecting encapsulation.
Q3035medium
What is the primary purpose of a constructor in Java?
✅ Correct Answer: B) To initialize the state of an object.
Constructors are special methods used to initialize new objects. They ensure an object is in a valid state immediately after creation.
Q3036easycode output
What does this code snippet print to the console?
java
class Product {
String name;
double price;
public Product(String name) {
this.name = name;
this.price = 0.0;
}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
}
public class Main {
public static void main(String[] args) {
Product p = new Product("Keyboard");
System.out.print("Name: " + p.name + ", Price: " + p.price);
}
}
✅ Correct Answer: A) Name: Keyboard, Price: 0.0
The `Product` object is created using the constructor `Product(String name)`. This constructor explicitly sets the `name` to 'Keyboard' and the `price` to 0.0, which are then printed.
Q3037medium
What is the primary purpose of the `intern()` method for a `String` object?
✅ Correct Answer: B) To add the string to the String pool if it's not already present and return a reference to the pooled string.
The `intern()` method can be used to explicitly add a string (even if created with `new String()`) to the String pool. If a string with the same content already exists in the pool, a reference to the pooled string is returned; otherwise, the string is added to the pool and its reference is returned.
Q3038hardcode error
What is the compilation error, if any, for the provided Java code snippet?
java
class Overloader {
public void process(long l, Integer... args) {}
public void process(Long l, int... args) {}
public static void main(String[] args) {
Overloader o = new Overloader();
o.process(10, 20); // Line X
}
}
✅ Correct Answer: B) error: reference to process is ambiguous
For `o.process(10, 20)`:
1. `process(long l, Integer... args)`: `10` (int) widens to `long`, `20` (int) autoboxes to `Integer` for the varargs.
2. `process(Long l, int... args)`: `10` (int) autoboxes to `Integer` then widens to `Long`, `20` (int) matches `int...`.
Both conversions are valid and neither sequence of conversions (widening, boxing, varargs) is demonstrably more specific than the other according to Java's method resolution rules, thus leading to an ambiguous method call.
Q3039medium
What is the primary purpose of creating custom exception classes in Java?
✅ Correct Answer: B) To represent specific application-level error conditions with more context
Custom exceptions allow developers to define domain-specific error types, providing clearer context about what went wrong in an application compared to generic exceptions.
Q3040easycode output
What is the output of this Java code?
java
public class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Task is running in a new thread.");
}
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
}
}
✅ Correct Answer: A) Task is running in a new thread.
The `main` method creates an instance of `MyTask` (which implements `Runnable`), wraps it in a `Thread` object, and then calls `start()`. The `start()` method invokes the `run()` method of the `Runnable` in a new thread, causing the message to be printed.