What is the problem with this Java code during compilation?
java
class Animal {
private String species = "Mammal";
}
class Dog extends Animal {
public void printSpecies() {
System.out.println("Species: " + species);
}
}
public class Zoo {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.printSpecies();
}
}
✅ Correct Answer: A) Compile-time error: 'species' has private access in 'Animal'
Private members are not directly accessible by subclasses, even though they are inherited. The 'species' field is private in 'Animal', so 'Dog' cannot directly refer to it.
Q2182medium
When an unlabeled `continue` statement is executed within a `for` loop, what is the next step in the loop's execution sequence?
✅ Correct Answer: C) The loop's update (increment/decrement) expression is executed, followed by the condition check.
In a `for` loop, after `continue` is executed, the update expression (e.g., `i++`) is performed, and then the loop's boolean condition is re-evaluated to determine if the next iteration should proceed.
Q2183medium
What is "type erasure" in the context of Java Generics?
✅ Correct Answer: B) The removal of generic type information during compilation, replacing it with their raw types (or upper bounds).
Type erasure is how Java implements generics. The generic type information is present only at compile time and is removed during compilation, replacing generic type parameters with their raw types (usually `Object`) or their first bound if specified.
Q2184medium
Which statement correctly describes the primary difference between `getAbsolutePath()` and `getCanonicalPath()` methods of the `File` class?
✅ Correct Answer: A) `getAbsolutePath()` returns the path as given, while `getCanonicalPath()` normalizes it to remove redundant elements (e.g., `.` or `..`) and resolves symbolic links.
`getAbsolutePath()` returns the absolute form of the pathname, which might still contain redundant elements or unresolved symbolic links. `getCanonicalPath()` returns the absolute and unique (canonical) pathname by resolving all path components, including symbolic links, and removing redundant elements.
Both `new File(".")` and `new File("")` refer to the current working directory. The current working directory always exists and is a directory. Therefore, their canonical paths will also be identical.
Q2186medium
How do interfaces contribute to polymorphism in Java?
✅ Correct Answer: B) They allow defining a common contract that different classes can implement.
Interfaces define a set of methods that implementing classes must provide, establishing a common contract or 'type' that can be handled polymorphically. This allows objects of different classes to be treated uniformly if they implement the same interface.
Q2187easycode output
What does this Java code print?
java
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(5, "Apple");
treeMap.put(2, "Banana");
treeMap.put(8, "Cherry");
for (Integer key : treeMap.keySet()) {
System.out.print(key + " ");
}
}
}
✅ Correct Answer: A) 2 5 8
TreeMap stores its keys in natural ascending order. When iterating over the `keySet()`, the keys are returned in this sorted order: 2, 5, 8.
Q2188easy
If you need to build a string by appending many small pieces in a single-threaded environment, which class would generally offer better performance than `StringBuffer`?
✅ Correct Answer: C) StringBuilder
`StringBuilder` is also mutable like `StringBuffer` but is not synchronized, making it faster in single-threaded environments because it avoids the overhead of locking.
Q2189hardcode output
What is the output of this code?
java
public class StringFormatTest {
public static void main(String[] args) {
String message = String.format("Values: %2$d, %1$s.", "Hello", 123);
System.out.println(message);
}
}
✅ Correct Answer: A) Values: 123, Hello.
The format specifier `%2$d` refers to the second argument (123) and formats it as a decimal integer. The specifier `%1$s` refers to the first argument ('Hello') and formats it as a string.
Q2190hard
Consider a custom class `MyKey` used as a `HashMap` key. If `MyKey` overrides `equals()` but *not* `hashCode()`, what is the primary consequence when attempting to retrieve an entry?
✅ Correct Answer: B) `put()` operations might appear to work, but `get()` operations might fail to find an existing entry even if `equals()` returns `true`.
If `hashCode()` is not overridden, `Object.hashCode()` (often based on memory address) is used. Even if `equals()` correctly identifies two objects as logically equal, their `hashCode()` values might differ, causing `get()` to look in the wrong bucket and fail to find the entry.
Q2191easycode output
What is the output of this Java code?
java
import java.util.LinkedList;
public class MyClass {
public static void main(String[] args) {
LinkedList<String> colors = new LinkedList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.removeFirst();
colors.removeLast();
System.out.println(colors);
}
}
✅ Correct Answer: A) [Green]
Initially, the list is [Red, Green, Blue]. `removeFirst()` removes 'Red', making it [Green, Blue]. Then `removeLast()` removes 'Blue', leaving [Green].
Q2192easycode output
What is printed to the console when this code is executed?
java
import java.io.*;
class NonSerializableClass {
private String message;
public NonSerializableClass(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
NonSerializableClass obj = new NonSerializableClass("Hello");
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(obj);
} catch (IOException e) {
System.out.println(e.getClass().getName());
}
}
}
✅ Correct Answer: A) java.io.NotSerializableException
To be serializable, a class must implement the `java.io.Serializable` interface. Attempting to serialize an object of a class that does not implement this interface will throw a `NotSerializableException`.
Q2193easycode error
What is the compilation error in the `Main` class?
java
class Calculator {
int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
int result = Calculator.add(5, 3);
System.out.println(result);
}
}
✅ Correct Answer: A) Cannot make a static reference to the non-static method `add(int, int)`
The `add` method is an instance method, meaning it must be called on an object of the `Calculator` class, not directly on the class name itself from a static context.
Q2194easycode output
What is the output of this code?
java
public class Test {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers[2]);
}
}
✅ Correct Answer: C) 30
Array indexing starts from 0. So, `numbers[2]` refers to the third element in the array, which is 30.
Q2195easycode output
What does this code print?
java
class MyCustomRuntimeException extends RuntimeException {
public MyCustomRuntimeException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
// No try-catch block here
throw new MyCustomRuntimeException("This is an unchecked error!");
}
}
✅ Correct Answer: C) An uncaught exception stack trace including 'MyCustomRuntimeException: This is an unchecked error!'
Since `MyCustomRuntimeException` extends `RuntimeException`, it's an unchecked exception. It is thrown but not caught, leading to the program terminating with an uncaught exception stack trace printed to the console.
Q2196mediumcode error
What is the compilation error in the provided Java code?
✅ Correct Answer: A) Cannot reduce the visibility of the inherited method from Logger
When overriding an inherited method (including default methods from interfaces), the access modifier cannot be more restrictive than that of the method in the supertype. Here, `public` (implicit for interface default methods) is reduced to `protected`.
Q2197easycode error
What is the error in this code?
java
import java.util.Comparator;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
Comparator<String> customComparator = (s1, s2) -> s1.compareTo(s2);
TreeMap<String, String> map = new TreeMap<>(customComparator);
map.put("key1", "value1");
map.put(null, "value2"); // Inserting a null key
System.out.println(map.size());
}
}
✅ Correct Answer: A) java.lang.NullPointerException
When a custom `Comparator` is provided, it is responsible for handling comparisons, including potential null values. The lambda `(s1, s2) -> s1.compareTo(s2)` does not check for `null`s. When `map.put(null, "value2")` is called, the comparator will be invoked with a null `s1` or `s2`, leading to a NullPointerException when `s1.compareTo(s2)` is executed.
Q2198easycode output
What does this Java code print?
java
class Book {
String title;
Book(String t) {
title = t;
}
void displayTitle() {
System.out.println("Title: " + title);
}
}
public class Main {
public static void main(String[] args) {
Book myBook = new Book("Java Basics");
myBook.displayTitle();
}
}
✅ Correct Answer: A) Title: Java Basics
The constructor `Book(String t)` initializes the `title` instance variable with "Java Basics". The `displayTitle()` method then correctly prints this initialized value.
Q2199easy
Which of the following is generally true about the memory footprint of `LinkedList` compared to `ArrayList` for the same number of elements?
✅ Correct Answer: B) `LinkedList` typically uses more memory.
Each node in a `LinkedList` stores data along with references to the previous and next nodes, leading to higher memory overhead per element compared to `ArrayList`.
Q2200mediumcode error
What error will occur when compiling this Java code?
java
public class ConditionCheck {
public static void main(String[] args) {
int flag = 1;
if (flag) {
System.out.println("Flag is true");
} else {
System.out.println("Flag is false");
}
}
}
✅ Correct Answer: A) error: incompatible types: int cannot be converted to boolean
In Java, `if` conditions require a boolean value. Unlike some other languages (e.g., C++), an `int` value cannot be implicitly converted to a `boolean`.