What error will occur when the `decrementCount` method is called without holding the lock?
java
import java.util.concurrent.locks.StampedLock;
public class StampedLockError {
private StampedLock lock = new StampedLock();
private int count = 0;
public void decrementCount() {
// This method does not acquire any lock before calling unlockWrite
long stamp = 0; // Invalid stamp
lock.unlockWrite(stamp); // Attempt to unlock with an invalid stamp
count--;
}
public static void main(String[] args) {
StampedLockError example = new StampedLockError();
example.decrementCount();
}
}
✅ Correct Answer: A) java.lang.IllegalMonitorStateException
`StampedLock`'s `unlockWrite()` method expects a valid stamp (obtained from a prior `writeLock()` call) and will throw an `IllegalMonitorStateException` if the stamp is invalid or the lock is not held by the current thread in write mode.
Q2422hardcode output
What is the output of this code?
java
public class EnumVars {
public enum Status {
ACTIVE("A"), INACTIVE("I");
private final String code;
Status(String code) { this.code = code; }
public String getCode() { return code; }
}
public static void main(String[] args) {
Status s1 = Status.ACTIVE;
String c1 = s1.getCode();
s1 = Status.INACTIVE;
String c2 = Status.ACTIVE.getCode();
System.out.println(c1 + c2);
}
}
✅ Correct Answer: A) AA
Enum constants (`Status.ACTIVE`, `Status.INACTIVE`) are fixed instances. When `s1` is assigned `Status.ACTIVE`, `c1` captures its code ('A'). Reassigning `s1` to `Status.INACTIVE` only changes the reference held by `s1`, it does not alter the `Status.ACTIVE` constant itself. Thus, `Status.ACTIVE.getCode()` still returns 'A'.
Q2423easycode error
What compile-time error will occur when creating a `MyClass` object?
java
class MyClass {
public My_Class() { // Note the underscore
System.out.println("Init");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
}
}
✅ Correct Answer: A) cannot find symbol constructor MyClass()
The constructor name must exactly match the class name. Since `My_Class` does not match `MyClass`, the defined constructor is not recognized as a constructor for `MyClass`, and no suitable constructor is found when `new MyClass()` is called.
Q2424easy
Which of the following is the most common and efficient way to create a String literal in Java?
✅ Correct Answer: B) String s = "hello";
`String s = "hello";` directly creates a String literal and places it in the String pool, promoting reusability.
Q2425easy
What is a class in Java?
✅ Correct Answer: A) A blueprint or template for creating objects.
A class acts as a blueprint or template that defines the structure (fields) and behavior (methods) of objects that belong to it.
Q2426mediumcode error
What error will prevent this Java code from compiling, specifically concerning the `calculate` method call?
java
public class OverloadChecker {
public void calculate(long l) {
System.out.println("Long: " + l);
}
public void calculate(float f) {
System.out.println("Float: " + f);
}
public static void main(String[] args) {
OverloadChecker oc = new OverloadChecker();
oc.calculate(10); // This line causes the error
}
}
✅ Correct Answer: A) Compile-time error: Reference to 'calculate' is ambiguous, both 'calculate(long)' and 'calculate(float)' match.
The integer literal `10` can be widened to both `long` and `float`. Neither `long` nor `float` is considered more specific than the other for an `int` argument, causing ambiguity at compile time.
Q2427hardcode output
What is the output of this Java code snippet, demonstrating lambda expression closure?
java
public class LambdaRunnableClosure {
private static int staticCounter = 0;
public static void main(String[] args) throws InterruptedException {
int localId = 100;
Runnable lambdaTask = () -> {
staticCounter++;
// localId++; // This would be a compilation error
System.out.println("Runnable Id: " + localId + ", Static Counter: " + staticCounter + ", Thread: " + Thread.currentThread().getName());
};
Thread t1 = new Thread(lambdaTask, "Thread-A");
Thread t2 = new Thread(lambdaTask, "Thread-B");
t1.start();
t2.start();
t1.join();
t2.join();
}
}
✅ Correct Answer: D) The order of output lines for Thread-A and Thread-B is not guaranteed, but both will print 'Runnable Id: 100' and 'Static Counter' will be 1 for one thread and 2 for the other.
Local variables captured by a lambda expression must be final or effectively final (`localId` here). Each thread gets its own copy of the `Runnable` instance, but they share the `staticCounter` which is incremented. The exact order of thread execution (and thus the order of the output lines) is not guaranteed, but `localId` will always be 100, and `staticCounter` will correctly show 1 and 2 in some order for the two threads.
Q2428mediumcode output
What is the output of this code?
java
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alpha", 10);
map.put("Beta", 20);
System.out.println(map.get("Alpha"));
}
}
✅ Correct Answer: A) 10
The `put()` method adds a key-value pair to the HashMap. The `get()` method retrieves the value associated with the specified key. In this case, 'Alpha' is associated with 10.
Q2429medium
In Java, without explicitly using curly braces `{}` for block statements, to which `if` statement does an `else` statement always associate?
✅ Correct Answer: D) To the nearest preceding unmatched `if` statement.
Java resolves the 'dangling else' problem by associating an `else` clause with the nearest preceding `if` statement that does not already have an `else`.
Q2430easycode output
What is the output of this code?
java
public class Main {
public static void main(String[] args) {
boolean x = true;
boolean y = false;
System.out.println(x || y);
}
}
✅ Correct Answer: A) true
The logical OR operator `||` returns `true` if at least one of its operands is `true`. Since `x` is `true`, the expression `x || y` evaluates to `true`.
Q2431easycode output
What does this code print?
java
import java.util.LinkedList;
public class MyClass {
public static void main(String[] args) {
LinkedList<Double> values = new LinkedList<>();
values.add(1.1);
values.add(2.2);
values.add(3.3);
for (Double val : values) {
System.out.print(val + " ");
}
}
}
✅ Correct Answer: A) 1.1 2.2 3.3
The code iterates through the `LinkedList` using a for-each loop. For each element, it prints the value followed by a space. `System.out.print` does not add a new line.
Q2432hardcode error
What is the error in the following Java code?
java
class DataProcessor<T> {
T process() { return null; }
}
class IntegerProcessor extends DataProcessor<Integer> {
@Override
int process() { // Covariant return type mismatch: Integer vs int
return 0;
}
}
✅ Correct Answer: C) Compilation Error: `method does not override or implement a method from a supertype`.
While Java supports covariant return types, `int` is a primitive type and not a subtype of the wrapper class `Integer`. Therefore, `int process()` is not a valid override for `Integer process()`, resulting in a compile-time error.
✅ Correct Answer: A) Illegal combination of modifiers: 'static' and 'abstract'
Static methods in interfaces, introduced in Java 8, must always have a concrete implementation (a body). An abstract method, by definition, lacks a body, making 'static abstract' an illegal combination.
Q2434easy
What is the effect of the `continue` keyword when encountered inside a `for` loop?
✅ Correct Answer: B) It skips the rest of the current iteration and proceeds to the next iteration of the loop.
The `continue` statement skips the remaining statements in the current iteration of a loop and proceeds to the next iteration.
Q2435easycode error
What is the runtime error in the following Java code snippet?
java
import java.util.ArrayList;
import java.util.Iterator;
public class Question10 {
public static void main(String[] args) {
ArrayList<String> items = new ArrayList<>();
items.add("Apple");
items.add("Banana");
for (String item : items) {
if (item.equals("Apple")) {
items.remove(item);
}
}
System.out.println(items);
}
}
✅ Correct Answer: A) Runtime error: java.util.ConcurrentModificationException.
Modifying an `ArrayList` (like removing an element) while iterating over it using an enhanced for loop (which internally uses an iterator) can lead to a `ConcurrentModificationException`.
Q2436hard
What is the outcome if a `break` statement uses a label that identifies a simple code block (i.e., not a loop or a `switch` statement)?
✅ Correct Answer: B) A compile-time error occurs, as labels for `break` must identify an enclosing loop or `switch` statement.
A `break` statement with a label can only be used to exit an enclosing labeled loop or `switch` statement. Using it with a label that identifies a simple code block (without an associated loop or `switch`) results in a compile-time error.
Q2437hard
In Java, what specific object is associated with a `synchronized` block or method and used by the JVM to manage exclusive access?
✅ Correct Answer: C) A monitor lock associated with the object instance (for instance methods/blocks) or the class object (for static methods/blocks).
Every Java object has an intrinsic lock, also known as a monitor. When a thread enters a `synchronized` instance method or block, it attempts to acquire the monitor of the associated object. For static `synchronized` methods or blocks, it acquires the monitor of the class object.
Q2438hard
If a labeled `continue` statement targets an *outer* `do-while` loop from within an *inner* `do-while` loop, what is the exact flow of execution?
✅ Correct Answer: C) The current iteration of the inner loop is skipped, and the outer loop immediately re-evaluates its condition to determine its next iteration.
A labeled `continue` statement skips the rest of the current iteration of the labeled loop and immediately re-evaluates that labeled loop's condition. In this case, the inner loop's current iteration is aborted, and the outer `do-while` loop's condition is checked to decide if it should continue.
Q2439hardcode output
What is the output of this code?
java
abstract class Vehicle {
String type;
public Vehicle(String type) {
this.type = type;
System.out.println("Vehicle constructor: " + type);
}
}
class Car extends Vehicle {
public Car() {
super("Car");
System.out.println("Car constructor.");
}
}
public class ConstructorTest {
public static void main(String[] args) {
new Car();
}
}
✅ Correct Answer: A) Vehicle constructor: Car
Car constructor.
When a subclass constructor is invoked, the superclass constructor is always called first (implicitly or explicitly via `super()`). Thus, the `Vehicle` constructor prints before the `Car` constructor.
Q2440hardcode error
Examine the following Java code. What is the specific compilation error?
java
public class NarrowingConversion {
public static void main(String[] args) {
int largeNum = 200;
byte smallNum = largeNum; // Illegal without explicit cast
System.out.println(smallNum);
}
}
✅ Correct Answer: A) Error: incompatible types: possible lossy conversion from int to byte.
Assigning a value from a larger primitive type (`int`) to a smaller primitive type (`byte`) is a narrowing conversion and requires an explicit cast in Java, as it may result in loss of precision. Without the cast, it's a compile-time error.