Consider the following code snippet with a custom class `BuggyPerson`. What error will occur when running this code?
java
import java.util.HashSet;
import java.util.Set;
class BuggyPerson {
String name;
public BuggyPerson(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BuggyPerson that = (BuggyPerson) o;
return name.equals(that.name); // Potentially ERROR here if name is null
}
@Override
public int hashCode() {
return name.hashCode(); // Potentially ERROR here if name is null
}
}
public class HashSetError8 {
public static void main(String[] args) {
Set<BuggyPerson> people = new HashSet<>();
people.add(new BuggyPerson("Alice"));
BuggyPerson pNull = new BuggyPerson(null); // Create person with null name
people.add(pNull); // ERROR line
}
}
✅ Correct Answer: A) Runtime Error: java.lang.NullPointerException.
When `pNull` (which has a `null` name) is added to the `HashSet`, the `HashSet` will call `pNull.hashCode()`. Inside `hashCode()`, `name.hashCode()` will attempt to dereference `null.hashCode()`, leading to a `NullPointerException`.
Q3102easycode error
What compile-time error will this code produce?
java
public class Main {
public static void main(String[] args) {
Runnable myRunnable = new Runnable(); // Attempt to instantiate an interface
Thread thread = new Thread(myRunnable);
thread.start();
}
}
✅ Correct Answer: A) Error: Runnable is abstract; cannot be instantiated
Interfaces in Java are abstract and cannot be instantiated directly using `new Runnable()`. To create a `Runnable` object, you must provide an implementation, typically via a class or an anonymous inner class.
Q3103mediumcode output
What does this code print?
java
public class StringBufferTest {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.insert(4, " is fun");
sb.insert(0, "Learning ");
System.out.print(sb);
}
}
✅ Correct Answer: A) Learning Java is fun
Initially, sb is 'Java'. `sb.insert(4, " is fun")` inserts ' is fun' at index 4 (end), making it 'Java is fun'. Then `sb.insert(0, "Learning ")` inserts 'Learning ' at index 0, resulting in 'Learning Java is fun'.
Q3104easycode output
What does this code print?
java
public class DataTypeTest {
public static void main(String[] args) {
double price = 99.99;
System.out.println(price);
}
}
✅ Correct Answer: A) 99.99
A double variable `price` is initialized with the floating-point value 99.99. `System.out.println()` outputs the exact double value.
Q3105mediumcode output
What is the output of this code?
java
class Book {
String title;
String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public String toString() {
return "Book [Title: " + title + ", Author: " + author + "]";
}
}
public class Main {
public static void main(String[] args) {
Book book = new Book("The Lord of the Rings", "J.R.R. Tolkien");
System.out.println(book);
}
}
✅ Correct Answer: A) Book [Title: The Lord of the Rings, Author: J.R.R. Tolkien]
When an object is printed using `System.out.println(object)`, its `toString()` method is implicitly invoked. Since the `Book` class overrides `toString()`, the custom string representation is printed.
Q3106medium
Which of the following is a defining characteristic of an immutable object in Java?
✅ Correct Answer: B) Its state cannot be changed after it has been created, ensuring its values remain constant.
An immutable object's state, once initialized, cannot be altered. Any operation that appears to modify it will instead return a new object with the desired changes.
Q3107easycode output
What does this Java code print to the console?
java
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(50, "Fifty");
treeMap.put(10, "Ten");
treeMap.put(70, "Seventy");
System.out.println(treeMap.lastKey());
}
}
✅ Correct Answer: A) 70
TreeMap maintains keys in natural sorted order. For integers, `lastKey()` returns the highest key present in the map, which is 70.
Q3108hard
Which statement accurately describes the use of covariant return types in Java method overriding?
✅ Correct Answer: A) An overridden method can return a subtype of the return type declared in the superclass method, provided the original method is not `final` or `static`.
Covariant return types, introduced in Java 5, allow an overridden method to return a more specific type (a subtype) than the method in the superclass, enhancing flexibility and type safety. This applies only to instance methods that are not `final`.
Q3109mediumcode output
What does this code print?
java
import jakarta.validation.*;
import jakarta.validation.constraints.*;
import java.util.Set;
public class Test {
static class PersonInfo {
@NotNull public String name; @Min(18) public Integer age;
public PersonInfo(String n, Integer a) { this.name = n; this.age = a; }
}
static class Application {
@Valid public PersonInfo info;
public Application(PersonInfo i) { this.info = i; }
}
public static void main(String[] args) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Application app = new Application(new PersonInfo(null, 15));
Set<ConstraintViolation<Application>> violations = validator.validate(app);
System.out.println("Violations: " + violations.size());
}
}
✅ Correct Answer: A) Violations: 2
The `@Valid` annotation triggers validation on `PersonInfo`. Both `name` (due to `@NotNull`) and `age` (due to `@Min(18)`) are invalid, resulting in two distinct violations.
Q3110mediumcode error
What is the compilation error in the following Java code (Java 10+)?
java
public class VarKeyword {
public static void main(String[] args) {
var count;
count = 10;
System.out.println(count);
}
}
✅ Correct Answer: A) Cannot infer type for local variable; an initializer is required
When using the `var` keyword for local variable type inference in Java, the variable must be initialized immediately so the compiler can infer its type from the initializer.
Q3111easycode error
What is the compilation or runtime error in the following Java code?
java
public class Main {
public static void main(String[] args) {
String data = "banana";
String modifiedData = data.replace('a', "x");
System.out.println(modifiedData);
}
}
✅ Correct Answer: B) Compilation error: no suitable method found for replace(char,java.lang.String)
The `replace()` method has overloads for `(char, char)` or `(CharSequence, CharSequence)`. Passing a `char` and a `String` (like 'a' and "x") does not match any existing signature, leading to a compilation error.
Q3112hard
What is the specific behavior regarding a traditional `for` loop's iteration variable (e.g., `int i`) being 'effectively final' when referenced inside a lambda expression or anonymous inner class in Java 8 and later?
✅ Correct Answer: A) The variable `i` is effectively final *within each iteration*, meaning a new `i` is conceptually created for each pass, allowing its capture by lambdas without explicit `final`.
Java 8 introduced a special rule for `for` loop variables, treating them as effectively final for each iteration. This means a new, distinct variable is considered for each pass, allowing its value to be captured by lambdas or anonymous inner classes.
Q3113hard
Which statement correctly describes the behavior of `System.arraycopy` when used to copy a multi-dimensional array?
✅ Correct Answer: B) It performs a shallow copy, copying references to the inner arrays, not the inner arrays themselves.
`System.arraycopy` always performs a shallow copy. For multi-dimensional arrays, it copies the references to the inner arrays from the source to the destination, meaning both arrays will point to the same inner array objects.
Q3114easycode error
What exception will be thrown when executing the following Java code?
java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class MyClass {
public static void main(String[] args) {
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
for (String fruit : fruits) {
if (fruit.equals("Banana")) {
fruits.remove("Banana"); // This line causes a runtime error
}
}
System.out.println(fruits.size());
}
}
✅ Correct Answer: C) java.util.ConcurrentModificationException
Modifying a collection (adding or removing elements) directly while iterating over it using an enhanced for-loop (which internally uses an iterator) will throw a `ConcurrentModificationException`.
Q3115hard
A developer is building a cross-platform application that needs to read text files reliably across different operating systems. They choose to use `FileReader` for its simplicity. Which of the following statements most accurately describes a significant pitfall of using `FileReader` in this scenario?
✅ Correct Answer: B) FileReader implicitly uses the platform's default character encoding, which can vary across operating systems, leading to character corruption or incorrect interpretation if the file's actual encoding doesn't match.
FileReader uses the default character encoding of the JVM, which is platform-dependent. This can lead to issues when reading files created on a system with a different default encoding, causing data corruption or misinterpretation of characters.
Q3116hardcode error
What error occurs when attempting to compile the following Java code?
java
public class ReturnUnreachableCode {
public static void process(int value) {
if (value > 0) {
if (value < 10) {
System.out.println("Value is small positive.");
return; // Exits the method
int unreachableVar = 100; // This line is unreachable
System.out.println(unreachableVar);
}
}
System.out.println("Value is not small positive or not positive.");
}
public static void main(String[] args) {
process(5);
}
}
✅ Correct Answer: B) Compilation error: unreachable statement
The `return;` statement inside the nested `if` block causes the method `process` to exit immediately. Any code following `return;` within the same execution path is considered unreachable by the Java compiler, leading to a compile-time error.
Q3117easy
A thread in the RUNNABLE state might transition to the BLOCKED state under which circumstance?
✅ Correct Answer: C) It tries to acquire a monitor lock that is currently held by another thread
A thread becomes BLOCKED when it attempts to enter a synchronized block or method but the associated monitor lock is unavailable because another thread holds it.
Q3118easycode output
What is the output of this code?
java
class Printer {
boolean printed = false;
public synchronized void printA() {
System.out.print("A");
printed = true;
notify();
}
public synchronized void printB() throws InterruptedException {
while(!printed) {
wait();
}
System.out.print("B");
}
}
public class MyProgram {
public static void main(String[] args) throws InterruptedException {
Printer p = new Printer();
Thread t1 = new Thread(() -> { try { p.printB(); } catch(InterruptedException e) {} });
Thread t2 = new Thread(() -> { try { p.printA(); } catch(InterruptedException e) {} });
t1.start();
t2.start();
t1.join();
t2.join();
}
}
✅ Correct Answer: A) AB
Thread `t1` calls `printB`, which immediately calls `wait()` because `printed` is false. Thread `t2` calls `printA`, prints 'A', sets `printed` to true, and calls `notify()`. This wakes up `t1`. `t1` then re-checks `printed` (which is now true), exits the loop, and prints 'B'. This ensures 'B' is printed after 'A'.
Q3119mediumcode error
What compilation error will this Java code produce?
java
public class UnaryOperatorError {
public static void main(String[] args) {
String text = "Hello";
int len = -text;
System.out.println(len);
}
}
✅ Correct Answer: A) Bad operand type for unary operator '-'
The unary minus operator (`-`) can only be applied to numeric types (integers and floating-point numbers). Applying it to a `String` results in a 'bad operand type' compilation error.
Q3120medium
What is the primary characteristic of how elements are stored in a `TreeSet`?
✅ Correct Answer: C) Elements are stored in ascending natural order or by a specified `Comparator`.
`TreeSet` maintains its elements in ascending order, either according to their natural ordering or by a `Comparator` provided at set creation time.