What is the compilation error in the following Java code snippet?
java
import java.util.ArrayList;
public class Question7 {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<>();
words.add("hello");
words.add("world");
for (Integer w : words) {
System.out.println(w);
}
}
}
✅ Correct Answer: A) Compile error: Incompatible types, cannot convert from String to Integer.
The `ArrayList` holds `String` objects, but the enhanced for loop attempts to assign each element to an `Integer` variable. This is a compile-time type mismatch.
Q2822easy
What does FIFO stand for in the context of data structures like Queue?
✅ Correct Answer: A) First-In, First-Out
FIFO is an acronym for 'First-In, First-Out,' which describes the order of processing elements in a queue: the element that enters first is the first one to leave.
Q2823hardcode error
Analyze the following Java code. Which error will it produce?
java
import java.io.*;
public class FileWriterError9 {
public static void main(String[] args) {
File nonExistentParentDir = new File("nonexistent_parent_dir/child_dir/file.txt");
try {
FileWriter fw = new FileWriter(nonExistentParentDir);
fw.write("Test data.");
fw.close();
} catch (IOException e) {
System.out.println("Error: " + e.getClass().getSimpleName() + " - " + e.getMessage());
}
}
}
✅ Correct Answer: B) An IOException with a message like 'No such file or directory' because parent directories do not exist and `FileWriter` doesn't create them by default.
Unlike some utility methods, `FileWriter` (and `FileOutputStream`) does not automatically create parent directories. If any parent directory in the path specified does not exist, an `IOException` will be thrown, typically with a message indicating 'No such file or directory'.
Q2824medium
What is the main advantage gained by utilizing method overriding in object-oriented programming with Java?
✅ Correct Answer: C) To achieve runtime polymorphism, allowing specific implementations to be called based on the actual object type.
Method overriding is a core mechanism for achieving runtime polymorphism in Java. It allows a superclass reference variable to point to a subclass object, and when the overridden method is called, the specific implementation from the subclass is executed at runtime.
Q2825medium
Which of the following `Queue` implementations is generally preferred over `LinkedList` when used purely as a FIFO queue, especially for single-threaded environments, due to better performance characteristics?
✅ Correct Answer: C) ArrayDeque
`ArrayDeque` is typically more efficient than `LinkedList` when used as a queue or deque due to its underlying resizable array structure, avoiding the overhead of node objects and pointers. It is not thread-safe, making it suitable for single-threaded use.
Q2826easy
If an instance variable in a Java class is declared `private`, how can other classes access or modify its value in an encapsulated design?
✅ Correct Answer: B) Through public getter and setter methods.
Private variables cannot be accessed directly from outside the class. Encapsulation dictates that public getter and setter methods are used for controlled access and modification.
Q2827easy
Which of the following is NOT a primitive data type in Java?
✅ Correct Answer: C) String
`String` is a class in Java and is therefore a reference data type, not a primitive data type. `boolean`, `char`, and `double` are primitives.
Q2828mediumcode output
What is the output of this Java code?
java
class MyJob implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + " is executing.");
}
}
public class Main {
public static void main(String[] args) {
MyJob job = new MyJob();
Thread t1 = new Thread(job, "Thread-1");
t1.run(); // Call run() directly
System.out.println(Thread.currentThread().getName() + " is done.");
}
}
✅ Correct Answer: B) main is executing.
main is done.
Calling `t1.run()` directly executes the `run()` method in the current thread (the main thread in this case) instead of creating and starting a new thread. Therefore, `Thread.currentThread().getName()` will return 'main'.
Q2829medium
Consider an `Iterator` for a mutable collection. If `iterator.remove()` is called immediately after `iterator.next()`, what is the expected outcome?
✅ Correct Answer: A) The element returned by the preceding `next()` call is removed from the collection.
The `remove()` method is designed to remove the last element returned by `next()`, provided it's called exactly once per `next()` call.
Q2830hardcode error
What compile-time error will this Java code produce?
java
public class OperatorError6 {
public static void main(String[] args) {
byte b1 = 100;
byte b2 = 50;
byte result = b1 + b2; // Error line
System.out.println(result);
}
}
✅ Correct Answer: B) incompatible types: possible lossy conversion from int to byte
During an arithmetic operation like `b1 + b2`, Java performs binary numeric promotion, converting both `byte` operands to `int`. The sum `150` is an `int` and exceeds the maximum value for a `byte` (127), so assigning it back to a `byte` without an explicit cast results in a compile-time error.
Q2831mediumcode error
Which line will cause a compilation error in the following code for an immutable class?
java
public class ProductIdentifier {
private final String id;
private ProductIdentifier(String id) {
this.id = id;
}
public static ProductIdentifier create(String id) {
return new ProductIdentifier(id);
}
public static void main(String[] args) {
ProductIdentifier p = new ProductIdentifier("P123"); // This line causes the error
}
}
✅ Correct Answer: A) ProductIdentifier(java.lang.String) has private access in ProductIdentifier
The constructor `ProductIdentifier(String id)` is declared as `private`. This prevents direct instantiation of the class from outside its own definition, making `new ProductIdentifier("P123")` in `main` a compilation error. Instances must be created via the public factory method `create`.
Q2832easycode output
What does the following code print?
java
public class Test {
public static void main(String[] args) {
double[] prices = {10.5, 20.0, 30.0};
prices[0] = 12.5;
System.out.println(prices[0] + prices[1]);
}
}
✅ Correct Answer: B) 32.5
The value at index 0 is updated from 10.5 to 12.5. So, `prices[0] + prices[1]` becomes `12.5 + 20.0 = 32.5`.
Q2833medium
How does `Thread.interrupt()` typically affect a thread that is currently blocked in methods like `sleep()`, `join()`, or `wait()`?
✅ Correct Answer: B) It causes the blocked method to throw an `InterruptedException`.
When a thread that is blocked in methods like `sleep()`, `join()`, or `wait()` is interrupted, these methods will typically throw an `InterruptedException`, signaling that the thread should handle the interruption.
Q2834medium
What is the primary requirement for a Java interface to be implemented by a lambda expression?
✅ Correct Answer: C) It must be a Functional Interface (contain exactly one abstract method).
Lambda expressions are syntactic sugar for instances of functional interfaces. A functional interface is any interface with exactly one abstract method.
Q2835hardcode error
What will be the result of compiling this Java code?
java
public class Outer {
private int outerValue = 10;
class Inner {
public static int innerStaticValue = 5; // Problematic line
public void display() {
System.out.println(outerValue);
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
✅ Correct Answer: A) Compile-time error: The field innerStaticValue cannot be declared static in a non-static inner type.
Non-static inner classes (like `Inner` here) cannot declare static members, except for `static final` fields initialized with compile-time constant expressions. Since `innerStaticValue` is not `final`, this results in a compile-time error.
Q2836easy
What is the primary characteristic of an `ArrayList` in Java?
✅ Correct Answer: B) It is a resizable array.
An `ArrayList` is a part of the Java Collections Framework that provides a dynamic array functionality, meaning its size can grow or shrink as needed.
Q2837hard
What is the primary effect of marking an instance variable with the `transient` keyword in Java?
✅ Correct Answer: A) The variable's value is not stored when the object containing it is serialized.
The `transient` keyword specifies that a field should be excluded from the default serialization mechanism when an object is written to a byte stream.
Q2838easycode error
What type of error will occur when compiling the following Java code?
✅ Correct Answer: A) Compile-time error: Method 'printMessage(String)' is already defined in 'Printer'.
Method overloading rules depend on the method signature (name and parameter list), not the access modifier. Defining two methods with the exact same name and parameter list, even with different access modifiers, results in a compile-time error because the method is considered already defined.
Q2839mediumcode output
What is the output of this code?
java
import java.util.ArrayList;
import java.util.List;
public class FinalMutable {
public static void main(String[] args) {
final List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
System.out.println(list.size());
}
}
✅ Correct Answer: A) 2
The `final` keyword applied to an object reference means the reference itself cannot be reassigned to point to a different object. It does not make the object it points to immutable, so the `ArrayList` object can still be modified by adding elements.
Q2840medium
If `List<String> mylist = new ArrayList<>();` and `Object obj = mylist;`, what is the correct way to cast `obj` back to `List<String>`?
✅ Correct Answer: B) `List<String> castedList = (List<String>) obj;`
Since `obj` holds an instance of `ArrayList` which implements `List`, it can be safely cast back to the `List` interface type. Casting to `ArrayList` would also be valid, but casting to the interface type is often preferred when the specific implementation is not strictly required.