What is the compilation error in the following Java code?
java
package com.base;
public class ProtectedResource {
protected String secret = "TopSecret";
protected void reveal() {
System.out.println(secret);
}
}
package com.app;
import com.base.ProtectedResource;
public class AccessAttempt {
public static void main(String[] args) {
ProtectedResource res = new ProtectedResource();
res.reveal(); // Attempt to access protected method from a different package and non-subclass
}
}
✅ Correct Answer: B) Error: The method reveal() from the type ProtectedResource is not visible.
A `protected` member can only be accessed from within its own package, or by subclasses in any package. `AccessAttempt` is in a different package (`com.app`) and is not a subclass of `ProtectedResource`, thus it cannot directly access the `protected` method `reveal()`.
Q2802easy
When does a `StringBuffer` increase its capacity?
✅ Correct Answer: B) When the length of the character sequence exceeds its current capacity.
A `StringBuffer` automatically increases its capacity when the number of characters it contains (its length) becomes greater than its current allocated capacity, to accommodate new characters.
Q2803mediumcode error
What will be the outcome of executing the following Java code?
java
public class Main {
public static void main(String[] args) {
Runnable myRunnable = () -> {
System.out.println("Task is running.");
};
Thread thread = new Thread(myRunnable);
thread.start();
thread.start();
}
}
✅ Correct Answer: A) A runtime error: java.lang.IllegalThreadStateException.
Once a thread has been started, it cannot be started again. Calling `start()` on a `Thread` object that is already running or has completed its execution will throw an `IllegalThreadStateException` at runtime.
Q2804mediumcode error
What is the output of this Java code?
java
import java.io.*;
public class DeserializationError5 {
public static void main(String[] args) {
// Attempt to create ObjectInputStream from a plain text string
String textData = "This is not serialized object data.";
byte[] data = textData.getBytes();
try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bis)) {
Object obj = ois.readObject();
System.out.println("Deserialized: " + obj);
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + ": " + e.getMessage());
}
}
}
✅ Correct Answer: A) Error: java.io.StreamCorruptedException: invalid stream header: 54686973
An `ObjectInputStream` expects the stream to start with a specific magic number and version information (the stream header). Providing plain text data instead of a valid serialized object stream results in a `StreamCorruptedException` because the header is invalid.
Q2805hardcode error
What is the output of this code?
java
import java.util.LinkedList;
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
LinkedList<String> data = new LinkedList<>(Arrays.asList("one", null, "three"));
for (String item : data) {
System.out.println(item.length()); // Dereferencing null
}
}
}
✅ Correct Answer: B) java.lang.NullPointerException
When the loop reaches the `null` element, `item` becomes `null`. Attempting to call `item.length()` on a `null` reference causes a `NullPointerException`.
Q2806easycode error
What is the error in the following Java code?
java
import java.util.TreeSet;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Comparator<Integer> myComparator = (a, b) -> a.compareTo(b);
TreeSet<String> values = new TreeSet<>(myComparator);
values.add("One");
}
}
✅ Correct Answer: B) The code will not compile because the Comparator's generic type does not match the TreeSet's generic type.
The `TreeSet` is declared to hold `String` objects (`TreeSet<String>`), but it is initialized with a `Comparator<Integer>`. This is a generic type mismatch, as a `Comparator` for `Integer` cannot be used with a `TreeSet` of `String`s, causing a compile-time error.
Q2807hardcode error
What kind of compile-time error will you encounter with this Java code?
java
public class CharDoubleArithmetic {
public static void main(String[] args) {
char initialChar = 'A'; // ASCII 65
char nextChar = initialChar + 1.0; // Adding a double literal to a char
System.out.println(nextChar);
}
}
✅ Correct Answer: A) Error: incompatible types: possible lossy conversion from double to char
When 'char' is added to a 'double' literal (1.0), the 'char' is promoted to a 'double'. The result of the addition is a 'double', which cannot be implicitly assigned back to a 'char' variable due to potential loss of precision; an explicit cast is required.
Q2808hard
If an exception is caught in a `catch` block and then explicitly re-thrown (e.g., `throw e;`), how does the `finally` block behave in relation to this re-thrown exception?
✅ Correct Answer: A) The `finally` block will execute, and then the re-thrown exception will propagate up the call stack.
The `finally` block is always executed before control leaves the `try-catch-finally` construct, even if an exception is re-thrown from a `catch` block, allowing the re-thrown exception to then propagate.
Q2809mediumcode output
What is the output of the following code snippet?
java
import java.util.Date;
class DataProvider {
Object getData() {
return new Date();
}
}
class SpecificDataProvider extends DataProvider {
@Override
String getData() { // Covariant return type
return "Specific Data";
}
}
public class Main {
public static void main(String[] args) {
DataProvider provider = new SpecificDataProvider();
System.out.println(provider.getData());
}
}
✅ Correct Answer: A) Specific Data
Java allows covariant return types for overridden methods, meaning the return type can be a subclass of the return type in the superclass method. `String` is a subclass of `Object`, so this is valid. Polymorphism ensures `SpecificDataProvider`'s method is called.
Q2810hardcode error
What is the compile-time error in this Java code?
java
public class InvalidRunSignature implements Runnable {
@Override
public int run() { // Line 3
System.out.println("Running task.");
return 0;
}
public static void main(String[] args) {
new Thread(new InvalidRunSignature()).start();
}
}
✅ Correct Answer: A) Compile-time error: method does not override or implement a method from a supertype (at Line 3)
The `run()` method of the `Runnable` interface has a `void` return type. Overriding it with an `int` return type changes the method signature, making it a new method rather than an override, thus failing to implement the interface correctly.
Q2811medium
Which method of the `java.util.function.Function` interface can be used to compose two functions, applying the current function *after* the provided function?
✅ Correct Answer: A) `andThen(Function<? super R, ? extends V> after)`
The `andThen()` method allows for sequential composition, where the current function's operation is applied after the function passed as an argument has completed its operation.
Q2812medium
In Java, if a subclass defines a `static` method with the exact same signature as a `static` method in its superclass, what concept is illustrated?
✅ Correct Answer: C) Method Hiding (or Shadowing)
Static methods belong to the class, not an object, and therefore cannot be overridden. If a subclass defines a static method with the same signature, it's called method hiding or shadowing, not overriding.
Q2813easycode error
What is the error in the following Java code?
java
class Main {
public static void main(String[] args) {
TreeSet<String> data = new TreeSet<>();
data.add("Item A");
data.add("Item B");
}
}
✅ Correct Answer: B) The code will not compile because `TreeSet` symbol cannot be found.
The `TreeSet` class is part of the `java.util` package and requires an explicit `import java.util.TreeSet;` statement. Without it, the compiler cannot find the `TreeSet` symbol, leading to a compilation error.
Q2814easycode output
What is the output of this code?
java
class BaseClass {
public final void show() {
System.out.print("Base show");
}
}
class ChildClass extends BaseClass {
// This class cannot override the final show() method
}
public class Main {
public static void main(String[] args) {
BaseClass obj = new ChildClass();
obj.show();
}
}
✅ Correct Answer: A) Base show
A `final` method cannot be overridden by subclasses. When `show()` is called on a `ChildClass` object referenced by `BaseClass`, the original `BaseClass`'s `final show()` method is executed.
Q2815hardcode output
What is the output of this code?
java
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
ArrayList<String> originalList = new ArrayList<>();
originalList.add("A");
originalList.add("B");
originalList.add("C");
originalList.add("D");
List<String> subList = originalList.subList(1, 3);
subList.set(0, "X");
originalList.remove(3);
System.out.println(subList.size());
}
}
A `subList` is a view of the original list. If the original list is structurally modified (e.g., by `originalList.remove(3)`) after the subList is created, any subsequent operation on the subList (like `subList.size()`) will throw a `ConcurrentModificationException`.
Q2816hard
A `StringBuffer` is initialized with `new StringBuffer(10)`. If a subsequent `append` operation causes its length to exceed 10, what is the most probable *minimum* new capacity the `StringBuffer` will attempt to ensure, based on the typical `AbstractStringBuilder` growth strategy in Java?
✅ Correct Answer: B) 22
The default growth strategy for `AbstractStringBuilder` (which `StringBuffer` extends) is typically `(oldCapacity * 2) + 2`. Given an old capacity of 10, the new minimum capacity would be `(10 * 2) + 2 = 22`.
Q2817easy
Which keyword would you use if you want to skip only a particular iteration of a loop and move on to the next one, without terminating the loop?
✅ Correct Answer: A) `continue`
`continue` is specifically designed to skip the rest of the current iteration of a loop and proceed with the next iteration.
Q2818easy
What is the primary purpose of Java Lambda Expressions?
✅ Correct Answer: B) To enable functional programming paradigms by providing a concise way to represent anonymous functions.
Lambda expressions provide a compact syntax for anonymous functions, making it easier to implement functional interfaces and promote functional programming styles in Java.
Q2819easy
Which method is generally preferred over `add()` when adding an element to a bounded `Queue` because it doesn't throw an exception if the queue is full?
✅ Correct Answer: C) offer()
The `offer()` method attempts to add an element and returns `true` on success or `false` if the queue is full, providing a non-blocking way to handle bounded queues.
Q2820mediumcode output
What is the output of this code?
java
class DataValidationException extends RuntimeException {
public DataValidationException(String message) {
super(message);
}
}
public class Main {
public static void processData(int value) {
if (value < 0) {
throw new DataValidationException("Negative value not allowed: " + value);
}
System.out.println("Data processed: " + value);
}
public static void main(String[] args) {
try {
processData(-5);
} catch (DataValidationException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Correct Answer: A) Error: Negative value not allowed: -5
The `processData` method throws a `DataValidationException` (a custom unchecked exception) because the input is negative. This exception is caught in the `main` method, and its message is printed.