How do bounded wildcards (`? extends T` and `? super T`) specifically facilitate or restrict polymorphism when working with Java Generics?
✅ Correct Answer: C) `? extends T` allows reading objects of type `T` or its subtypes (producer), while `? super T` allows writing objects of type `T` or its supertypes (consumer), enabling safe polymorphic operations on generic collections.
Bounded wildcards (`? extends T` for producers, `? super T` for consumers) are essential for achieving safe and flexible polymorphism with generic types. They allow generic type arguments to vary while enforcing type safety for operations like reading from or writing to collections.
Q3142easycode output
What is the output of this code?
java
class Item {
static void getType() {
System.out.println("Generic Item");
}
}
class Book extends Item {
static void getType() {
System.out.println("Book Item");
}
}
public class Main {
public static void main(String[] args) {
Item myItem = new Book();
myItem.getType();
}
}
✅ Correct Answer: B) Generic Item
Static methods cannot be overridden; they are hidden. The method that is called depends on the reference type, not the actual object type. Since `myItem` is declared as `Item`, `Item.getType()` is invoked.
Q3143medium
How must a `final` instance variable of a class be initialized in Java?
✅ Correct Answer: B) It must be initialized within every constructor of the class that could lead to an object's creation, or at the point of declaration/instance initializer.
A `final` instance variable must be assigned a value exactly once. This can be done at the point of declaration, in an instance initializer block, or in all constructors, ensuring it's initialized before object construction completes.
Q3144easycode error
What exception will be thrown when executing the following Java code?
java
import java.util.HashSet;
import java.util.Set;
public class MyClass {
public static void main(String[] args) {
Set<String> words = new HashSet<>();
words.add("Hello");
words.add(null);
words.add("World");
for (String word : words) {
if (word != null && word.equals("Hello")) {
// Do nothing
} else if (word != null && word.equals("World")) {
// Do nothing
} else {
System.out.println(word.toUpperCase()); // This line causes an error when word is null
}
}
}
}
✅ Correct Answer: C) java.lang.NullPointerException
The HashSet contains a `null` element. When the loop iterates to this `null` element, the `else` block will execute, attempting to call `toUpperCase()` on `null`, which throws a `NullPointerException`.
Q3145medium
Why does Java not support multiple inheritance of implementation for classes?
✅ Correct Answer: B) To simplify the class hierarchy and avoid the 'diamond problem'.
Java avoids multiple inheritance of implementation to prevent the complexities of the 'diamond problem' where a class inherits conflicting method implementations from two different parent classes. It favors composition and interfaces.
Q3146mediumcode error
What is the outcome when this Java code is executed?
java
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Character> chars = new LinkedList<>();
chars.add('A');
chars.add(0, 'B');
chars.add(3, 'C');
System.out.println(chars);
}
}
✅ Correct Answer: B) IndexOutOfBoundsException
After `chars.add('A')` and `chars.add(0, 'B')`, the list is `[B, A]` and its size is 2. The method `add(int index, E element)` requires `0 <= index <= size()`. Attempting `chars.add(3, 'C')` throws an `IndexOutOfBoundsException` because 3 is greater than the current size (2).
Q3147medium
A class `Configuration` has a field `String settings;` (without any explicit access modifier). This field is accessible by:
✅ Correct Answer: D) Within `Configuration` and any other class in the same package.
When no access modifier is specified, the field has 'default' or 'package-private' access, meaning it is accessible only within its own package.
Q3148hardcode error
What compile-time error will this Java code produce?
java
public class OperatorError9 {
public static void main(String[] args) {
double d = 10.5;
double result = ~d; // Error line
System.out.println(result);
}
}
✅ Correct Answer: B) bad operand type for unary ~: double
The bitwise complement operator `~` is defined only for integral types (byte, short, char, int, long). Applying it to a `double` (a floating-point type) is an illegal operation and will result in a compile-time error.
Q3149easy
Can an abstract class implement an interface in Java without implementing all of its methods?
✅ Correct Answer: A) Yes, an abstract class can implement an interface without implementing all its methods, but it must remain abstract itself.
An abstract class can implement an interface and choose not to implement all interface methods, effectively passing the responsibility to its concrete subclasses.
Q3150mediumcode error
What will be printed to the console when the following Java code is executed?
java
import java.io.BufferedReader;
import java.io.Reader;
import java.io.IOException;
public class TestClass {
public static void main(String[] args) {
Reader r = null;
try (BufferedReader br = new BufferedReader(r)) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
} catch (NullPointerException e) {
System.err.println("NPE Caught!");
}
}
}
✅ Correct Answer: B) NPE Caught!
The `BufferedReader` constructor expects a non-null `Reader` object. Passing `null` to its constructor will immediately result in a `NullPointerException` at runtime. This specific `NullPointerException` is caught by the second `catch` block.
Q3151easycode output
What does this code print?
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<>();
ts.add(100);
ts.add(50);
ts.add(200);
System.out.println(ts.first() + " " + ts.last());
}
}
✅ Correct Answer: A) 50 200
The first() method returns the lowest element currently in this set, and last() returns the highest element.
Q3152easy
Which interface in the Java Collections Framework represents a Queue?
✅ Correct Answer: D) java.util.Queue
The `java.util.Queue` interface defines the core contract for queue-like data structures in Java, providing methods for insertion, extraction, and inspection.
Q3153easycode error
What is the error in the following Java code?
java
import java.util.TreeSet;
class MyObject {
int id;
public MyObject(int id) { this.id = id; }
}
public class Main {
public static void main(String[] args) {
TreeSet<MyObject> mySet = new TreeSet<>();
mySet.add(new MyObject(1));
mySet.add(new MyObject(2));
}
}
✅ Correct Answer: B) The code will compile but throw a ClassCastException at runtime.
TreeSet stores elements in sorted order. For custom objects like `MyObject`, it requires them to either implement the `Comparable` interface or for a `Comparator` to be provided. Since `MyObject` does neither, adding the second element will result in a `ClassCastException`.
Q3154mediumcode output
What is the output of this code?
java
import java.util.LinkedList;
import java.util.Queue;
import java.util.NoSuchElementException;
public class QueueErrorHandling {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(10);
queue.poll();
try {
System.out.println(queue.remove());
} catch (NoSuchElementException e) {
System.out.println("Queue Empty");
}
}
}
✅ Correct Answer: C) Queue Empty
After `offer(10)` and `poll()`, the queue becomes empty. Calling `remove()` on an empty queue throws a `NoSuchElementException`, which is caught and prints "Queue Empty".
Q3155easycode error
What is the error in this Java code?
java
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, Integer> myMap = new HashMap<>();
myMap.put(101, 200);
System.out.println(myMap.get(101));
}
}
✅ Correct Answer: C) A compile-time error because the key type (Integer) does not match the map's generic key type (String).
The HashMap is declared with String keys, but an Integer key is being used in the 'put' method. This causes a compile-time type mismatch error.
Q3156hardcode output
What does this program print?
java
interface MyInterface {
default void greet() { System.out.println("Hello from MyInterface"); }
}
class ParentClass {
public void greet() { System.out.println("Hello from ParentClass"); }
}
class MyClass extends ParentClass implements MyInterface {
// No explicit override
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.greet();
}
}
✅ Correct Answer: A) Hello from ParentClass
When a class inherits a method from a superclass and also from an interface (as a default method) with the same signature, the method from the superclass always takes precedence. This is often called 'classes win'.
Q3157medium
What happens if a thread calls `object.wait()` without owning the monitor (lock) of `object`?
✅ Correct Answer: C) An `IllegalMonitorStateException` will be thrown at runtime.
The `wait()`, `notify()`, and `notifyAll()` methods must be called on an object whose monitor (lock) is currently held by the calling thread. If not, an `IllegalMonitorStateException` is thrown.
Q3158easy
If a non-static method `myMethod()` in an object `obj` is declared `synchronized`, which lock is acquired when a thread calls `obj.myMethod()`?
✅ Correct Answer: B) The lock associated with the `obj` instance itself.
When an instance method is `synchronized`, it acquires the intrinsic lock of the object instance on which the method is invoked, ensuring mutual exclusion for that specific object.
Q3159hardcode error
What compilation error will occur when compiling this Java code?
java
public class ParallelLabelBreak {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
if (i == 1) {
break myLabel;
}
System.out.println("Inner loop i: " + i);
}
myLabel: {
System.out.println("This is myLabel block");
}
}
}
✅ Correct Answer: A) `label myLabel not found`
Labels must be declared and within scope *before* they are referenced. In this code, `myLabel` is declared after the `break` statement attempts to use it, leading to a "label not found" error because it's not yet known.
Q3160hardcode output
What is the output of this code?
java
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
public class Test {
public static void main(String[] args) throws IOException {
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw); // Default buffer size is 8192 chars
String longString = "A".repeat(8191);
bw.write(longString);
bw.flush();
bw.write('B');
bw.close();
System.out.println(sw.toString().length());
}
}
✅ Correct Answer: A) 8192
The longString (8191 chars) fills the buffer but doesn't exceed it, so no automatic flush occurs. The explicit bw.flush() writes these 8191 characters. Then 'B' (1 char) is written to the now empty buffer. Finally, bw.close() flushes 'B'. The total length is 8191 + 1 = 8192.