What will be the result of compiling and running this Java code?
java
public class A {
public static final int VALUE = B.OTHER_VALUE + 1;
}
public class B {
public static final int OTHER_VALUE = A.VALUE + 1;
public static void main(String[] args) {
System.out.println(A.VALUE);
}
}
✅ Correct Answer: B) Runtime error: java.lang.ExceptionInInitializerError (often wrapping StackOverflowError).
This code creates a cyclic dependency in static initialization. Class `A` needs `B.OTHER_VALUE` to initialize `A.VALUE`, and Class `B` needs `A.VALUE` to initialize `B.OTHER_VALUE`. This leads to an `ExceptionInInitializerError` at runtime, often caused by a `StackOverflowError` as the JVM tries to resolve the infinite recursion during class loading.
Q3242hardcode error
Which compile-time error will occur when compiling this Java snippet?
java
public class ByteArithmetic {
public static void main(String[] args) {
byte a = 50;
byte b = 80;
byte c = a + b; // Arithmetic operations on byte/short/char promote to int
System.out.println(c);
}
}
✅ Correct Answer: A) Error: incompatible types: possible lossy conversion from int to byte
When performing arithmetic operations on 'byte', 'short', or 'char' types, the operands are automatically promoted to 'int'. The result of 'a + b' is an 'int', which cannot be implicitly assigned back to a 'byte' variable without an explicit cast, hence the compile-time error.
Q3243easycode error
What is the error in this Java code?
java
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, String> myMap = HashMap<>();
myMap.put("city", "London");
System.out.println(myMap.get("city"));
}
}
✅ Correct Answer: C) A compile-time error because the 'new' keyword is missing for object instantiation.
In Java, objects must be instantiated using the 'new' keyword followed by the constructor call. Omitting 'new' results in a compile-time error.
Q3244medium
If a constructor in a subclass does not explicitly call `super()` or `this()`, what action does the Java compiler take?
✅ Correct Answer: B) It inserts an explicit call to `super()` with no arguments as the first statement.
If neither `this()` nor `super()` is explicitly called in a constructor, the compiler automatically inserts `super()` as the first statement to invoke the no-argument constructor of the immediate superclass.
Q3245hard
Why is `FileWriter` almost universally recommended to be wrapped in a `BufferedWriter` for writing significant amounts of text data, especially when performing numerous small `write()` operations?
✅ Correct Answer: B) Each call to `FileWriter.write()` can trigger a direct write operation to the underlying operating system's file system, leading to excessive system calls and I/O overhead.
`FileWriter` is unbuffered, meaning each `write()` call might result in a direct system call to write data to disk. `BufferedWriter` significantly improves performance by buffering characters in memory and writing them to the underlying `Writer` (or `FileWriter`) in larger, more efficient chunks.
Q3246mediumcode output
What does this code print?
java
class A {
A() {
System.out.print("A");
}
}
class B extends A {
B() {
System.out.print("B");
}
}
public class Main {
public static void main(String[] args) {
new B();
}
}
✅ Correct Answer: A) AB
When an object of class `B` is created, its constructor is called. Before executing the `B` constructor's body, the `super()` call (implicitly added by the compiler if not explicit) invokes the `A` class constructor first, printing 'A', then 'B'.
Q3247hardcode error
What runtime error will this Java code snippet throw?
java
public class Test {
public static void main(String[] args) {
int[][] matrix = new int[2][];
matrix[0] = new int[3];
matrix[1] = new int[2];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j <= matrix[1].length; j++) {
matrix[i][j] = i * 10 + j;
}
}
System.out.println(matrix[0][0]);
}
}
✅ Correct Answer: A) java.lang.ArrayIndexOutOfBoundsException
The inner loop's condition `j <= matrix[1].length` is incorrect. `matrix[1]` has a length of 2, so valid indices are 0 and 1. When `j` becomes 2, attempting to access `matrix[i][2]` will cause an `ArrayIndexOutOfBoundsException` for both `matrix[0]` (length 3, max index 2) and `matrix[1]` (length 2, max index 1).
Q3248hardcode error
What is the error in the execution of this Java code snippet?
java
public class BuilderError {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Example");
String sub = sb.substring(-1, 3);
System.out.println(sub);
}
}
✅ Correct Answer: A) StringIndexOutOfBoundsException
The `substring` method (both `String`'s and `StringBuilder`'s) requires `start` and `end` indices to be non-negative. A negative `start` index, such as -1, directly causes a `StringIndexOutOfBoundsException` at runtime.
Q3249hardcode error
Which line causes a compilation error?
java
class Base {
public final void print() {
System.out.println("Base final");
}
}
class Derived extends Base {
public void print() { // Line 7
System.out.println("Derived print");
}
}
public class Test {
public static void main(String[] args) {
Derived d = new Derived();
d.print();
}
}
✅ Correct Answer: C) Line 7: `public void print() {`
A `final` method in a superclass cannot be overridden by a subclass. Attempting to do so results in a compile-time error on Line 7.
Q3250easycode output
What output does the following Java code produce?
java
public class Main {
public static void main(String[] args) {
String result = "";
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
continue;
}
result += i;
}
System.out.print(result);
}
}
✅ Correct Answer: A) 135
The loop iterates from 1 to 5. The 'continue' statement is executed when 'i' is an even number, skipping the concatenation to 'result'. Therefore, only odd numbers (1, 3, 5) are added.
Q3251hardcode error
What is the most likely error when compiling this Java code snippet?
java
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new FileOutputStream("output.txt"));
bw.write("Data");
bw.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Compile-time error: incompatible types: FileOutputStream cannot be converted to Writer
The `BufferedWriter` constructor expects a `Writer` object. `FileOutputStream` is an `OutputStream` (byte-based), not a `Writer` (character-based). This type mismatch is caught by the compiler, requiring an `OutputStreamWriter` in between.
Q3252hard
How does `java.util.LinkedList` handle `null` elements?
✅ Correct Answer: B) `LinkedList` can store `null` elements, and methods like `add(null)` and `contains(null)` behave as expected.
`java.util.LinkedList` allows `null` elements to be stored, just like `ArrayList`. Operations such as `add(null)`, `contains(null)`, and `remove(null)` will work as expected, treating `null` as any other valid element.
Q3253hardcode output
What does this code print?
java
String s = null;
Object o = null;
System.out.println(String.valueOf(s));
System.out.println(String.valueOf(o));
try {
System.out.println(s.toString());
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
}
✅ Correct Answer: A) null
null
NullPointerException
`String.valueOf(null)` (for both `String` and `Object` types) returns the string literal "null". Calling `toString()` on a `null` reference, however, results in a `NullPointerException`.
Q3254easy
How do you initialize an integer variable named `counter` to the value 10?
✅ Correct Answer: A) int counter = 10;
Variables are initialized using the assignment operator `=` to assign an initial value. This can be done at the time of declaration.
Q3255easy
Which of the following is NOT a valid Java variable name?
✅ Correct Answer: C) for
Java keywords like `for` are reserved and cannot be used as variable names. Valid names can contain letters, digits, `_`, or `$`, but not start with a digit, and cannot be keywords.
Q3256hard
What is the primary implication of declaring a reference variable as `final` in Java?
✅ Correct Answer: B) The reference itself cannot be reassigned to point to another object after its initial assignment.
Declaring a reference variable `final` means its value (the reference) cannot be changed after initialization, ensuring it always points to the same object. It does not make the object itself immutable.
Q3257hard
In the context of `BlockingQueue` operations, what is the fundamental difference between calling `queue.take()` and `queue.poll()` without a timeout?
✅ Correct Answer: B) `take()` blocks indefinitely if the queue is empty, while `poll()` returns `null` immediately if the queue is empty.
`take()` is a blocking operation that waits until an element becomes available if the queue is empty. `poll()` is a non-blocking operation that returns `null` immediately if the queue is empty.
Q3258hardcode error
What error will be thrown when `Worker` thread attempts to call `condition.await()`?
java
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class SharedData {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void waitForSignal() {
// This thread does not hold 'lock'
try {
condition.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class Main {
public static void main(String[] args) {
SharedData data = new SharedData();
Thread worker = new Thread(data::waitForSignal);
worker.start();
}
}
✅ Correct Answer: C) java.lang.IllegalMonitorStateException
Similar to `Object.wait()`, calling `Condition.await()` requires the current thread to hold the lock associated with that `Condition` object. Since `waitForSignal()` does not acquire `lock` before calling `await()`, an `IllegalMonitorStateException` is thrown.
Q3259easycode output
What does this code print?
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<>();
ts.add("apple");
ts.add("banana");
ts.add("apple");
System.out.println(ts.size());
}
}
✅ Correct Answer: B) 2
TreeSet does not allow duplicate elements. When 'apple' is added a second time, it is ignored, so the size remains 2.
Q3260easycode output
Analyze the Java code and determine its output.
java
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
if (i == 1) {
System.out.print("X");
continue;
}
if (i == 2) {
System.out.print("Y");
break;
}
System.out.print(i);
}
}
}
✅ Correct Answer: A) 0XY
When i=0, '0' is printed. When i=1, 'X' is printed and 'continue' skips to the next iteration. When i=2, 'Y' is printed and 'break' terminates the entire loop.