What compile-time error will be produced when accessing `account.balance` in the `main` method?
java
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0);
System.out.println(account.balance);
}
}
✅ Correct Answer: B) Compile-time error: 'balance has private access in BankAccount'.
The `balance` field is declared as `private` within the `BankAccount` class. Private members are only accessible from within their own class, thus attempting to access `account.balance` directly from `Main` (another class) causes a compile-time error.
Q582easy
How can you specify a custom sorting order for a `TreeMap`?
✅ Correct Answer: B) By passing a `Comparator` object to its constructor.
A custom sorting order for a `TreeMap` can be achieved by providing a `Comparator` instance to its constructor when the map is created. This comparator will then be used to order the keys.
Q583mediumcode output
What is the output of this Java code?
java
import java.util.function.Consumer;
public class LambdaBasic {
public static void main(String[] args) {
Consumer<String> printer = s -> System.out.println("Hello " + s);
printer.accept("World");
}
}
✅ Correct Answer: A) Hello World
The lambda expression `s -> System.out.println("Hello " + s)` implements the `Consumer` functional interface, taking a String and printing a greeting. Calling `accept("World")` results in 'Hello World' being printed.
Q584mediumcode output
What does this code print?
java
public class StringBuilderTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.insert(2, "va");
System.out.println(sb);
}
}
✅ Correct Answer: A) Javava
The insert(offset, String) method inserts the specified string at the given offset. For 'Java', inserting 'va' at index 2 (before the second 'v') results in 'Javava'.
Q585hard
How does the `final` keyword for a field contribute to immutability, and what is its limitation in guaranteeing immutability?
✅ Correct Answer: B) `final` ensures the reference itself cannot be reassigned after initialization, but it does not prevent modifications to the object that the reference points to if that object is mutable.
The `final` keyword only ensures that the reference itself cannot be changed to point to a different object. It does not prevent the state of the object it refers to from being modified if that object is mutable.
Q586easycode output
What does this Java code print?
java
public class ArrayTest {
public static void main(String[] args) {
String[] names = new String[3];
System.out.println(names.length);
}
}
✅ Correct Answer: A) 3
The `.length` property of an array returns the total number of elements it can hold. In this case, the array `names` is initialized to hold 3 elements.
Q587easy
Which package contains the `java.util.HashSet` class?
✅ Correct Answer: D) java.util
The `HashSet` class, along with many other collection classes like `ArrayList`, `HashMap`, and `LinkedList`, is part of the `java.util` package.
Q588easy
Which of the following is a correct usage of the `throw` keyword in Java?
✅ Correct Answer: A) `throw new NullPointerException();`
The `throw` keyword must be followed by an actual object instance of an exception, which is created using the `new` keyword and a constructor.
Q589hard
Consider a `do-while` loop where the `while` condition uses a post-increment or post-decrement operator on a variable (e.g., `while (x++ < 10)`). When is the modification to the variable `x` performed relative to the condition's evaluation?
✅ Correct Answer: B) The modification happens *after* the condition (`x < 10`) is evaluated, but *before* the loop potentially continues to the next iteration.
With post-increment/decrement (e.g., `x++`), the original value of `x` is used in the expression (`x < 10`), and *then* `x` is incremented/decremented. This modified value of `x` will then be used if the loop continues to its next potential iteration.
Q590hard
What is the typical direct consequence of attempting to modify a `java.util.Collection` (e.g., `ArrayList`) by adding or removing elements *directly* within an enhanced `for` (for-each) loop that is iterating over it?
✅ Correct Answer: C) It typically throws a `java.util.ConcurrentModificationException` at an unpredictable point during iteration.
Modifying a collection directly while iterating over it using an enhanced `for` loop (which uses an implicit `Iterator`) typically triggers a `ConcurrentModificationException`. This is a fail-fast mechanism to detect inconsistencies.
Q591easycode error
What kind of error will occur when compiling this Java code?
java
class Vehicle {
public Vehicle() {
System.out.println("Vehicle constructor");
}
}
class Bike extends Vehicle {
public Bike() {
System.out.println("Bike constructor");
super(); // Incorrect position
}
}
public class Main {
public static void main(String[] args) {
Bike myBike = new Bike();
}
}
✅ Correct Answer: A) Compile-time error: call to super must be first statement in constructor
The call to `super()` or `this()` in a constructor must always be the very first statement. Placing it after any other statement will result in a compile-time error.
Q592mediumcode error
What is the result when compiling and running the following Java code?
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"))) {
writer.write("Line 1");
writer.newLine();
writer.close();
writer.newLine(); // Call newLine() after close
} catch (IOException e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
✅ Correct Answer: B) IOException: Stream closed
The `writer.close()` method closes the underlying stream. Subsequent calls to methods like `newLine()` or `write()` on a closed `BufferedWriter` will result in an `IOException` with the message 'Stream closed'.
Q593easycode output
What will be the content of the file 'output.txt' after this code executes?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterTest {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Initial");
} catch (IOException e) {}
try (FileWriter writer = new FileWriter("output.txt")) {
// No explicit write operation here
} catch (IOException e) {}
}
}
✅ Correct Answer: A) An empty file
The first `FileWriter` writes 'Initial'. The second `FileWriter` is constructed without the append flag, so it truncates the file, effectively clearing its content. Since no subsequent write operations occur, the file remains empty.
Q594easycode output
What does this code print?
java
public class Counter implements Runnable {
private int count;
public Counter(int initialCount) {
this.count = initialCount;
}
@Override
public void run() {
System.out.println("Count: " + count);
}
public static void main(String[] args) {
Counter c1 = new Counter(5);
Thread t1 = new Thread(c1);
t1.start();
}
}
✅ Correct Answer: A) Count: 5
The `Counter` class correctly implements `Runnable` and its constructor initializes the `count` variable. The `run()` method then accesses and prints this instance variable. When `t1.start()` is called, 'Count: 5' is printed from the new thread.
Q595mediumcode error
What is the compile-time error in the following Java code?
java
class SingletonClass {
private SingletonClass() {
System.out.println("Singleton instance created");
}
// Assume there's a getInstance() method here for actual singleton pattern
}
public class ConstructorError5 {
public static void main(String[] args) {
SingletonClass instance = new SingletonClass(); // Error here
}
}
✅ Correct Answer: A) Error: SingletonClass() has private access in SingletonClass
A constructor declared as `private` can only be called from within the class itself. Attempting to create an instance of `SingletonClass` using `new SingletonClass()` from an external class (like `ConstructorError5`) violates its access modifier, resulting in a compile-time error.
Q596hardcode output
What is the output of this code?
java
public class DataTypeChallenge {
public static void main(String[] args) {
double d1 = Double.NaN;
double d2 = Double.NaN;
System.out.println(d1 == d2);
System.out.println(d1 != d1);
System.out.println(Double.isNaN(d1));
}
}
✅ Correct Answer: B) false
true
true
`Double.NaN` is a special floating-point value that is not equal to itself or any other value, including another `NaN`. Thus, `d1 == d2` is `false`. Consequently, `d1 != d1` is `true`. The `Double.isNaN()` method is the correct way to check if a `double` value is `NaN`.
Q597hardcode output
What is the output of this code?
java
public class Test {
public static void main(String[] args) {
String result = "";
outer: for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (i == 0) {
if (j == 1) { result += "X"; continue outer; }
result += "A" + j;
} else {
result += "B" + j;
}
}
}
System.out.print(result);
}
}
✅ Correct Answer: B) A0XB0B1
When `i` is 0 and `j` is 1, 'X' is added, and `continue outer` skips the rest of the inner loop and the remaining statements of the current outer loop iteration, moving to `i=1`. Then the loop continues normally for `i=1`.
Q598easy
How does an `if-else` statement differ from a simple `if` statement in Java?
✅ Correct Answer: B) `if-else` provides an alternative block of code to execute if the `if` condition is false.
An `if-else` statement ensures that exactly one of two code blocks will execute: the `if` block if the condition is true, or the `else` block if the condition is false.
Q599easycode error
What is the error in this Java code?
java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterError4 {
public static void main(String[] args) {
FileWriter writer;
try {
writer = new FileWriter("data.txt");
writer.write("Some data.");
} catch (IOException e) {
e.printStackTrace();
}
writer.close(); // Attempting to close outside the try block
}
}
✅ Correct Answer: A) The `writer` variable might not have been initialized if an `IOException` occurs during its instantiation, leading to a compile-time error.
If an `IOException` occurs during `new FileWriter("data.txt")`, the `writer` variable would not be initialized within the `try` block. Subsequently, `writer.close()` outside the `try-catch` (and not in a `finally` block where it's correctly handled) would lead to a compile-time error: 'variable writer might not have been initialized'.
Q600mediumcode error
What compilation error will this Java code produce?
java
public class SwitchError {
public static void main(String[] args) {
int limit = 5;
switch (2) {
case limit:
System.out.println("Two");
break;
default:
System.out.println("Other");
}
}
}
✅ Correct Answer: A) Error: case expressions must be constant expressions
Case labels in a switch statement must be constant expressions that can be evaluated at compile time. A non-final variable, even if initialized, is not a constant expression.