What is the compile-time error when attempting to create an instance of the Singleton class?
java
class Singleton {
private Singleton() {
System.out.println("Singleton instance created.");
}
// Assume a static factory method exists for proper instantiation, but we're ignoring it.
}
class Main {
public static void main(String[] args) {
Singleton s = new Singleton();
}
}
✅ Correct Answer: A) Error: `Singleton() has private access in Singleton`
A private constructor prevents direct instantiation of a class from outside its own definition. Attempting to call a private constructor from another class results in a compile-time access error.
Q182medium
What is the implication of declaring a method as `final` in Java?
✅ Correct Answer: C) The method cannot be overridden by subclasses.
A `final` method cannot be overridden by any subclass. This ensures that the method's implementation remains consistent across the inheritance hierarchy.
Q183easycode error
What kind of error will occur when executing the following Java code?
java
public class DualLock {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void performWait() {
synchronized (lockA) { // Synchronizing on lockA
try {
lockB.wait(); // Calling wait() on lockB
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
DualLock dualLock = new DualLock();
new Thread(dualLock::performWait).start();
}
}
✅ Correct Answer: B) Runtime Error: java.lang.IllegalMonitorStateException
The `wait()` method must be called on the same object that the current thread is synchronized on. Here, the thread synchronizes on `lockA` but calls `wait()` on `lockB`, leading to a `java.lang.IllegalMonitorStateException`.
Q184medium
Consider a scenario where multiple `Thread` objects are created using the *same single instance* of a `Runnable` implementation. What is a consequence of this design?
✅ Correct Answer: C) All threads will share the same instance variables of the `Runnable` object.
If multiple threads execute the same `Runnable` instance, they will share its instance variables. This means changes made by one thread to these variables will be visible to other threads, potentially requiring synchronization.
Q185easycode output
What does this code print?
java
import java.io.FileReader;
import java.io.IOException;
public class FileReaderTest {
public static void main(String[] args) {
// Assume test.txt exists and contains a single character '1'
FileReader reader = null;
try {
reader = new FileReader("test.txt");
System.out.print((char) reader.read());
} catch (IOException e) {
System.out.print("Error");
} finally {
try {
if (reader != null) reader.close();
} catch (IOException e) {
System.out.print("Close Error");
}
}
}
}
✅ Correct Answer: A) 1
The code successfully opens 'test.txt', reads the first character '1', prints it, and then safely closes the reader in the `finally` block.
Q186hard
Consider a `for` loop where a complex computation `result = expensiveFunction(constantValue)` is performed repeatedly, but `constantValue` does not change across loop iterations. What is the most likely behavior of a modern Java JIT compiler regarding this computation?
✅ Correct Answer: B) The JIT compiler will likely hoist `expensiveFunction(constantValue)` out of the loop, evaluating it only once before the loop begins.
Modern JIT compilers are adept at 'loop invariant code motion'. If an expression's value does not change throughout the loop's execution, the compiler can hoist it out of the loop and compute it only once, improving performance.
Q187easy
What happens if the condition expression in a `for` loop evaluates to `false` from the very beginning?
✅ Correct Answer: B) The loop body never executes.
If the condition is false from the start, the loop body is never entered or executed. The loop is skipped entirely.
Q188hardcode error
What error will occur when the following Java code snippet is run?
✅ Correct Answer: B) A NullPointerException, because the String filename is null when passed to the constructor.
The `FileWriter` constructor that takes a `String` filename will throw a `NullPointerException` if the provided filename `String` is null. It does not implicitly handle null paths.
Q189hard
Consider the Java snippet: `short s = 5; s += 10.5;`. Which statement accurately describes the compilation outcome and the final value of `s`?
✅ Correct Answer: A) It compiles successfully and `s` becomes `15`.
Compound assignment operators like `+=` implicitly cast the result of the operation back to the type of the left-hand operand. `s = (short)(s + 10.5)` occurs; `s + 10.5` is `15.5`, which truncates to `15` when cast to `short`.
Q190easy
`StringBuffer` in Java is designed to be thread-safe. What mechanism primarily contributes to its thread-safety?
✅ Correct Answer: B) Its methods are synchronized.
`StringBuffer` achieves thread-safety by synchronizing its methods, ensuring that only one thread can modify its content at a time.
Q191medium
Which method of `BufferedReader` is commonly used to read an entire line of text, including the line terminator, and returns `null` at the end of the stream?
✅ Correct Answer: C) readLine()
The `readLine()` method reads a line of text, returning the line as a `String` (without the line terminator), or `null` if the end of the stream has been reached.
Q192easy
Which Java primitive data type can only hold the values `true` or `false`?
✅ Correct Answer: C) boolean
The `boolean` data type is used to represent logical states, accepting only `true` or `false` as its values.
Q193hardcode error
What is the error in this Java code?
java
public class LoopScopeError {
public static void main(String[] args) {
int i = 0;
while (i < 3) {
String message = "Current iteration: " + i;
i++;
}
System.out.println(message);
}
}
✅ Correct Answer: A) A compile-time error: cannot find symbol 'message'
The variable `message` is declared within the scope of the `while` loop. It is not accessible outside the loop, leading to a compile-time error 'cannot find symbol' when `System.out.println(message)` is called.
Q194hard
Consider a method `void outerMethod()` which has a local variable `int x = 10;`. Inside `outerMethod()`, you define both an anonymous inner class and a lambda expression. If you declare another local variable `int x = 20;` inside the anonymous inner class, and attempt to do the same inside the lambda, what would be the outcome?
✅ Correct Answer: B) The anonymous inner class would compile successfully, but the lambda expression would result in a compile-time error due to `x` already being defined in the enclosing scope.
Anonymous inner classes create a new lexical scope, allowing local variable shadowing. Lambda expressions, however, share the same lexical scope as their enclosing environment, meaning they cannot declare a local variable with the same name as one already defined in the enclosing scope.
Q195easycode error
What kind of error will occur when executing the following Java code?
java
public class MyThreadPriority {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("Child thread running with priority: " + Thread.currentThread().getPriority());
});
t.setPriority(Thread.MAX_PRIORITY); // Set priority before start
t.start();
t.setPriority(Thread.MIN_PRIORITY); // Attempt to change priority after starting
System.out.println("Main thread finished.");
}
}
✅ Correct Answer: B) No error, the priority is changed, but the JVM may not honor it.
Changing a thread's priority after it has started does not result in an `IllegalThreadStateException`. While `setPriority()` is often called before `start()`, it can also be called on a running thread. The JVM will attempt to apply the new priority, though the actual effect depends on the operating system's scheduling policies. Therefore, the code runs without an error.
Q196hard
In a scenario with deeply nested loops, what is the precise impact of using `continue label;` compared to a simple `continue;` statement if `label` refers to one of the outer loops?
✅ Correct Answer: C) `continue;` skips the current iteration of the innermost enclosing loop, while `continue label;` skips the current iteration of the specific loop identified by `label` and continues with its next iteration.
An unlabeled `continue` statement skips the rest of the current iteration of the innermost enclosing loop and proceeds to its next iteration. A labeled `continue` statement, however, skips the rest of the current iteration of the *labeled* loop and proceeds to its next iteration, potentially skipping multiple inner loops.
Q197mediumcode error
What kind of error will occur when running this Java code?
java
public class ArrayError {
public static void main(String[] args) {
Number[] nums = new Integer[5];
nums[0] = 3.14;
System.out.println(nums[0]);
}
}
✅ Correct Answer: B) Runtime error: ArrayStoreException
While `Number[]` can hold `Integer` objects, the actual array created is `Integer[]`. Attempting to store a `Double` (3.14 is a double literal) into an `Integer[]` at runtime causes an `ArrayStoreException` because `Double` is not an `Integer` or a subclass of `Integer`.
Q198medium
What is the purpose of the `Thread.yield()` method?
✅ Correct Answer: C) It is a hint to the scheduler that the current thread is willing to yield its current use of a processor.
`Thread.yield()` is a hint to the scheduler that the current thread is willing to yield its current use of a processor to allow other threads to run. However, there's no guarantee that the scheduler will act on this hint.
Q199mediumcode output
What does this Java code print to the console?
java
import java.util.function.Function;
public class Test {
public static void main(String[] args) {
Function<String, Integer> toInt = Integer::parseInt;
Function<Integer, String> toString = String::valueOf;
Function<Integer, Integer> timesTwo = x -> x * 2;
Function<String, String> f1 = toInt.andThen(timesTwo).andThen(toString);
Function<String, String> f2 = toString.compose(timesTwo).compose(toInt);
System.out.println(f1.apply("5"));
System.out.println(f2.apply("5"));
}
}
✅ Correct Answer: A) 10
10
Both `andThen` and `compose` effectively chain the functions in the same logical order for this specific example: parse "5" to int 5, multiply by 2 to get 10, then convert 10 to string "10".
Q200easycode error
Identify the compile-time error in the provided Java code.
java
public class DataTypeFloatError {
public static void main(String[] args) {
float pi = 3.14;
System.out.println(pi);
}
}
✅ Correct Answer: A) Incompatible types: possible lossy conversion from double to float
Floating-point literals in Java are implicitly `double`. To assign a `double` literal to a `float` variable, you must explicitly cast it or append 'f' or 'F' to the literal (e.g., `3.14f`), otherwise, it's a compile-time error.