interface MyInterfaceA { default void foo() { System.out.println("MyInterfaceA::foo"); } }
interface MyInterfaceB { default void foo() { System.out.println("MyInterfaceB::foo"); } }
class Parent { public void foo() { System.out.println("Parent::foo"); } }
class MyClass extends Parent implements MyInterfaceA, MyInterfaceB {
}
public class Test {
public static void main(String[] args) {
MyInterfaceA objA = new MyClass();
objA.foo();
}
}
✅ Correct Answer: A) Parent::foo
When a class inherits a method from a superclass and also implements an interface that provides a default method with the same signature, the class's method (from the superclass) always takes precedence. Thus, `Parent::foo` is invoked.
Strings are immutable. The concat method and '+' operator create new String objects. s1 first points to 'Java', then 'Java Program'. s2 points to 'Java Developer' at creation and doesn't change.
Q3463medium
What is a potential drawback of extensively using immutable objects in scenarios where an object's state needs to be updated frequently?
✅ Correct Answer: B) Higher object creation overhead and increased garbage collection activity.
Because every 'modification' to an immutable object results in a new object being created, frequent changes can lead to a large number of temporary objects, potentially increasing memory usage and garbage collection load.
Q3464medium
Which of the following statements about `PriorityQueue` in Java is true?
✅ Correct Answer: B) Elements are ordered according to their natural ordering or by a `Comparator` provided at queue construction time.
`PriorityQueue` does not maintain FIFO order; instead, it orders elements based on natural ordering or a `Comparator`. It does not permit `null` elements and is not thread-safe.
Q3465easy
In Java, which of the following is an example of an immutable class?
✅ Correct Answer: C) java.lang.String
`java.lang.String` is a well-known immutable class in Java. Operations on a String that appear to modify it actually return a new String object.
Q3466easycode error
What is the error in the following Java code?
java
interface MyPrintable {
void print();
}
class MyData {
int value = 10;
}
java
public class Main {
public static void main(String[] args) {
MyData data = new MyData();
MyPrintable printable = (MyPrintable) data;
System.out.println(printable);
}
}
✅ Correct Answer: A) Compile-time error: Incompatible types: MyData cannot be converted to MyPrintable.
You can only cast an object to an interface type if the class of the object actually implements that interface. Since MyData does not implement MyPrintable, this results in a compile-time error.
Q3467easy
What is the default initial capacity of a Java HashMap when no capacity is specified?
✅ Correct Answer: B) 16
The default initial capacity for a HashMap, if not specified in the constructor, is 16.
Q3468medium
Consider a method that throws a `RuntimeException`. Which statement about declaring `throws RuntimeException` in the method signature is true?
✅ Correct Answer: B) It is optional for the method to declare `throws RuntimeException`.
`RuntimeException` is an unchecked exception. While a method can declare `throws RuntimeException`, it is not mandatory because unchecked exceptions do not require declaration or handling by the caller.
Q3469hard
Which statement accurately describes a key characteristic of a loop invariant specific to a `do-while` loop, especially contrasting it with a standard `while` loop?
✅ Correct Answer: B) The loop invariant must be true *immediately after* each execution of the `do` block, and *prior* to the evaluation of the `while` condition.
For a `do-while` loop, the `do` block executes at least once without the condition being checked first. Therefore, the invariant typically isn't established *before* the first `do` execution, but must hold *after* each `do` execution and before the `while` condition is evaluated.
Q3470easycode output
What is the output of this Java code snippet?
java
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.print(i + " ");
}
}
}
✅ Correct Answer: A) 0 1 2
The loop iterates from 0. When i becomes 3, the 'break' statement is executed, terminating the loop immediately. So, only 0, 1, and 2 are printed.
Q3471mediumcode output
What is the result of executing this code?
java
public class StringTest {
public static void main(String[] args) {
String message = "Java is awesome";
System.out.println(message.indexOf("is") + message.indexOf('a', 2));
}
}
✅ Correct Answer: D) 8
`message.indexOf("is")` returns 5 (index of 'i' in "is"). `message.indexOf('a', 2)` searches for 'a' starting from index 2; the first 'a' is at index 1, the next one is at index 3. So, it returns 3. The sum is 5 + 3 = 8.
Q3472mediumcode error
Which exception will be thrown when executing this Java code?
java
public class StringError5 {
public static void main(String[] args) {
String data = "java"; // Length is 4
String sub = data.substring(2, 5);
System.out.println(sub);
}
}
✅ Correct Answer: B) java.lang.StringIndexOutOfBoundsException
The `substring(beginIndex, endIndex)` method's `endIndex` must be less than or equal to the string's length. For 'java' (length 4), index 5 is out of bounds, causing a StringIndexOutOfBoundsException.
Q3473hardcode output
What is the output of this Java code?
java
import java.util.Comparator;
import java.util.TreeMap;
class TrickyComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
// Compare by length first, then alphabetically
int lenCompare = Integer.compare(s1.length(), s2.length());
if (lenCompare != 0) {
return lenCompare;
}
return s1.compareTo(s2); // Secondary sort
}
}
public class Test {
public static void main(String[] args) {
TreeMap<String, Integer> map = new TreeMap<>(new TrickyComparator());
map.put("abc", 1);
map.put("a", 2);
map.put("abcd", 3);
map.put("ab", 4);
map.put("aa", 5); // Length 2, comes before "ab" alphabetically
System.out.println(map.keySet());
}
}
✅ Correct Answer: A) [a, aa, ab, abc, abcd]
The `TrickyComparator` sorts strings primarily by length in ascending order. If lengths are equal, it then sorts alphabetically. 'a' (length 1) comes first. Then 'aa' and 'ab' (both length 2), sorted alphabetically. Then 'abc' (length 3), and finally 'abcd' (length 4).
Q3474mediumcode error
What will be the compilation error in this code?
java
class Animal {
private void eat() {
System.out.println("Animal eats.");
}
}
class Dog extends Animal {
@Override
public void eat() {
System.out.println("Dog eats bones.");
}
}
✅ Correct Answer: A) Error: Method does not override method from its superclass
Private methods are not inherited by subclasses and therefore cannot be overridden. The '@Override' annotation causes a compilation error because no method is being overridden.
Q3475easycode error
What is the error in the following Java code snippet?
java
public class ArrayError {
public static void main(String[] args) {
int[] values = new int[-5];
System.out.println(values.length);
}
}
✅ Correct Answer: B) Runtime error: NegativeArraySizeException.
In Java, an array cannot be created with a negative size. This specific error (NegativeArraySizeException) is a runtime error, not a compile-time error.
Q3476easy
Which of the following is a valid Java variable name?
✅ Correct Answer: A) _myVariable
Variable names can start with a letter, dollar sign (`$`), or an underscore (`_`). They cannot start with a digit, contain hyphens, or be a Java keyword.
Q3477medium
What is the primary purpose of using the `java.util.Optional` class in Java?
✅ Correct Answer: B) To provide a type-safe way to handle potentially absent values and avoid `NullPointerException`s.
`Optional` is specifically designed to represent the presence or absence of a value, helping developers to explicitly deal with nullability and reduce the incidence of `NullPointerException`s.
Q3478easy
What is the default initial capacity of a `StringBuffer` when it is created using the no-argument constructor (e.g., `new StringBuffer()`)?
✅ Correct Answer: C) 16 characters
By default, a `StringBuffer` created with no arguments has an initial capacity of 16 characters. This capacity grows automatically when needed.
Q3479mediumcode output
What is the content of 'flushed.txt' after this code executes?
java
import java.io.FileWriter;
import java.io.IOException;
public class FlushTest {
public static void main(String[] args) {
FileWriter writer = null;
try {
writer = new FileWriter("flushed.txt");
writer.write("Data to be flushed.");
writer.flush(); // Explicitly flush
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
// writer.close(); // Intentionally omitted for this question
}
}
}
✅ Correct Answer: B) Data to be flushed.
Calling `flush()` ensures that any buffered data is immediately written to the underlying stream. Even without `close()`, the data will be present in the file after `flush()` is invoked.
Q3480hard
When designing a Java application to process a log file continuously as new lines are appended, which approach concerning `FileReader` is generally considered problematic for efficiency and resource management?
✅ Correct Answer: B) Repeatedly opening a new `FileReader` and closing it after reading a small chunk of data, then reopening for the next chunk.
Repeatedly opening and closing a FileReader for small reads is highly inefficient due to the overhead of creating new file descriptors, performing OS-level file opening/closing, and resource allocation. It's better to keep one FileReader (often buffered) open and read from it as needed.