Programming Concepts using Java · End Term · May 2026 · FN
Programming Concepts using Java · End Term · May 2026 FN
← Course papers · Start practice / exam
Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.
23 / 23 published solutions
Consider the Java code given below.
Immediately after the execution of Line 8, the activation record of which method is at the top of
the stack of activation records?
**1. Trace the call stack of activation records step by step:**
- Execution starts in `main` (pushed onto the call stack: `[main]`).
- Line 17 calls `execute()` (pushed onto the call stack: `[main, execute]`).
- Line 14 calls `c.compute()` (pushed onto the call stack: `[main, execute, compute]`).
- Line 7 calls `square(a)` (pushed onto the call stack: `[main, execute, compute, square]`), which executes Line 3 (`return x * x;`) and pops `square`, returning to `compute` (`[main, execute, compute]`).
- Line 8 (`return b;`) is the `return` statement of `compute()`.
**2. Determine what is at the top of the stack *immediately after* Line 8 executes:**
Executing `return b;` at Line 8 completes `compute()` and **pops the activation record of `compute()`** off the call stack, returning control to Line 14 inside **`execute()`**. Therefore, immediately after Line 8 finishes, the activation record of **`execute`** is at the top of the stack.
**Answer: B — execute.**
A: **Incorrect:** `main` is at the bottom of the call stack underneath `execute`.
B: **Correct:** Line 8 (`return b;`) pops `compute()` from the stack and returns control to its caller `execute()`, leaving `execute` at the top of the stack.
C: **Incorrect:** The activation record of `compute` is popped when its `return b;` statement at Line 8 finishes executing.
D: **Incorrect:** `square` already returned and was popped at the end of Line 7.
Question 3 MCQ · 4.0 marks
Consider the Java code given below.
What will the output be?
Published solution
**1. Trace the object construction and copy constructor in `Showroom.main`:**
- `Vehicle v1 = new Car("Sedan", 5);`
Creates a `Car` instance with `model = "Sedan"` and `seating_capacity = 5`.
- `Vehicle v2 = new Car((Car) v1);`
Calls the copy constructor `Car(Car c)`, which creates a **brand-new, separate `Car` object** initialized with `c.model` (`"Sedan"`) and `c.seating_capacity` (`5`).
- `v2.model = "SUV";`
Modifies the `model` field of the second object `v2` to `"SUV"`, while `v1.model` remains `"Sedan"`.
**2. Trace the `toString()` calls via dynamic method dispatch:**
Because `v1` and `v2` both reference `Car` objects at runtime, printing `v1` and `v2` invokes `Car.toString()`, which returns `super.toString() + ", seating_capacity = " + seating_capacity`:
- For `v1`: `model = Sedan, seating_capacity = 5`
- For `v2`: `model = SUV, seating_capacity = 5`
**Answer: C — model = Sedan, seating_capacity = 5 and model = SUV, seating_capacity = 5.**
A: **Incorrect:** `v1` and `v2` are distinct `Car` instances, and `Car.toString()` also prints `, seating_capacity = 5`.
B: **Incorrect:** Modifying `v2.model = "SUV"` does not affect the separate object `v1` (`v1.model` stays `"Sedan"`).
C: **Correct:** The copy constructor creates an independent `Car` object for `v2`, and dynamic dispatch calls `Car.toString()` on both `v1` and `v2`.
D: **Incorrect:** Because `v1` and `v2` point to `Car` instances, `Car.toString()` is invoked at runtime rather than `Vehicle.toString()` alone.
Question 4 MCQ · 4.0 marks
Consider the code given below.
Choose the correct option regarding the code.
Compiler error at
because the method
cannot be
invoked on
object
Compiler error at
because the method
cannot be invoked
on
object
The code generates the output:
Compiler error at
because method
is not defined in class
Published solution
**1. Check the inheritance and interface implementation hierarchy:**
- Interface `Evaluable` declares `void evaluate();`.
- `abstract class Course implements Evaluable` (Line 1): Because `Course` is declared **`abstract`**, it is **not required** to provide a concrete implementation of `evaluate()`, and it also declares `public abstract void conductClass();`.
- Both concrete subclasses `ProgrammingCourse` and `MathCourse` extend `Course` and implement both `evaluate()` and `conductClass()` with `public` visibility.
**2. Trace `showDetails(Course obj)`:**
- At Line 2 (`obj.evaluate();`): Valid at compile time because `Course implements Evaluable`, so `Course` inherits the abstract declaration of `evaluate()`.
- At Line 3 (`obj.conductClass();`): Valid at compile time because `conductClass()` is declared in `Course`.
- At runtime, passing `new ProgrammingCourse()` and `new MathCourse()` invokes their respective overridden methods, printing:
```
Programming course evaluation
Programming course class
Math course evaluation
Math course class
```
**Answer: C — The code generates the output: Programming course evaluation / Programming course class / Math course evaluation / Math course class.**
A: **Incorrect:** `conductClass()` is declared in `Course`, so calling `obj.conductClass()` on a `Course` reference is completely valid.
B: **Incorrect:** Because `Course implements Evaluable`, any `Course` reference is guaranteed to have the `evaluate()` method from `Evaluable`.
C: **Correct:** The code compiles cleanly and uses dynamic polymorphism to invoke the overridden methods of `ProgrammingCourse` and `MathCourse`.
D: **Incorrect:** An `abstract` class implementing an interface is not required to implement the interface's methods; concrete subclasses implement them.
Question 5 MCQ · 4.0 marks
Consider the Java code given below.
Choose the correct option.
and
generates a compilation error because method
is already defined with the same signature.
and
generates a compilation error because method
is already defined with the same signature.
Only
generates a compilation error because method
is already defined with the same signature.
This program generates output:
Published solution
**1. Understand Type Erasure for generic methods in Java:**
In `GradeCalculator`, let us examine the post-erasure method signatures of the three generic methods:
- **LINE 1:** `public <T extends Number> void calculateGrade(T marks)`
Because `T` is bounded by `Number`, type erasure replaces `T` with its upper bound `Number`, giving the erased signature:
`calculateGrade(Number)`
- **LINE 2:** `public `‹U extends Number›` void calculateGrade(U marks)`
Because `U` is also bounded by `Number`, type erasure replaces `U` with `Number`, giving the exact same erased signature:
`calculateGrade(Number)`
- **LINE 3:** `public <T> void calculateGrade(T marks)`
Because `T` is unbounded, type erasure replaces `T` with `Object`, giving the distinct erased signature:
`calculateGrade(Object)`
**2. Identify the compilation error:**
Because **LINE 1** and **LINE 2** have the exact same type-erased signature `calculateGrade(Number)` in the same class, the Java compiler reports a duplicate method error at **LINE 2** (while LINE 3 erases to `calculateGrade(Object)` and does not clash).
**Answer: C — Only LINE 2 generates a compilation error because method calculateGrade() is already defined with the same signature.**
A: **Incorrect:** LINE 3 has an unbounded type parameter `<T>` which erases to `calculateGrade(Object)`, a distinct signature from `calculateGrade(Number)`.
B: **Incorrect:** LINE 1 is the first declaration and LINE 3 erases to `Object`; the conflict is between LINE 1 and LINE 2.
C: **Correct:** Both `<T extends Number>` (LINE 1) and ``‹U extends Number›`` (LINE 2) erase to `calculateGrade(Number)`, causing a duplicate method compilation error at LINE 2.
D: **Incorrect:** The program fails to compile due to the erasure clash between LINE 1 and LINE 2.
Question 6 MCQ · 4.0 marks
Consider the code given below.
Choose the correct option to fill in place of
so that the output is:
Published solution
**1. Analyze the visibility of the inner classes inside `HospitalSystem`:**
In `HospitalSystem`:
- `Consultation` and `DiagnosticTest` are declared as **`private` inner classes** (`private class Consultation implements MedicalService` and `private class DiagnosticTest implements MedicalService`).
- Because they are `private` to `HospitalSystem`, the external class `Test` **cannot reference the type names `Consultation` or `DiagnosticTest` directly** (nor instantiate them with `new Consultation()`).
- However, both private inner classes implement the package-accessible interface **`MedicalService`**, and `HospitalSystem` provides `public` factory methods `h.getConsultation()` and `h.getDiagnosticTest()`.
**2. Choose the valid declaration in `Test.main`:**
By upcasting the returned objects to the interface type `MedicalService`:
```java
MedicalService obj1 = h.getConsultation();
MedicalService obj2 = h.getDiagnosticTest();
```
`Test` never mentions the private class names and can call `obj1.provideService()` and `obj2.provideService()` polymorphically!
**Answer: B — MedicalService obj1 = h.getConsultation(); MedicalService obj2 = h.getDiagnosticTest();**
A: **Incorrect:** `Consultation` and `DiagnosticTest` are `private` non-static inner classes of `HospitalSystem` and cannot be referenced or instantiated directly inside `Test`.
B: **Correct:** Storing the objects returned by `h.getConsultation()` and `h.getDiagnosticTest()` in `MedicalService` interface references avoids accessing the `private` class names while allowing `provideService()` calls.
C: **Incorrect:** The class names `Consultation` and `DiagnosticTest` have `private` visibility inside `HospitalSystem` and are not visible as variable types in `Test`.
D: **Incorrect:** `new Consultation()` and `new DiagnosticTest()` cannot be called directly from `Test` because the classes are `private` inner classes of `HospitalSystem`.
Question 7 MCQ · 4.0 marks
Consider the Java code given below.
What will the output be?
This program generates the output:
This program generates the output:
This program generates the output:
This program generates the output:
Published solution
**1. Trace the operations on `ArrayDeque<String> books`:**
Recall that `add(e)` (or `addLast(e)`) appends an element to the **back (tail)** of the deque, while `addFirst(e)` inserts an element at the **front (head)** of the deque (and `ArrayDeque` allows duplicate elements):
1. `books.add("Dune")` \(\implies\) `[Dune]`
2. `books.addFirst("1984")` \(\implies\) `[1984, Dune]`
3. `books.add("Emma")` \(\implies\) `[1984, Dune, Emma]`
4. `books.addFirst("Hamlet")` \(\implies\) `[Hamlet, 1984, Dune, Emma]`
5. `books.add("1984")` \(\implies\) `[Hamlet, 1984, Dune, Emma, 1984]`
Printing `books` outputs:
`[Hamlet, 1984, Dune, Emma, 1984]`
**2. Trace the construction of `TreeSet<String> set = new TreeSet<String>(books)`:**
`TreeSet` removes duplicates and sorts strings in **natural (lexicographical/ASCII) order** (where digits `'1'` come before uppercase letters `'D', 'E', 'H'`):
Printing `set` outputs:
`[1984, Dune, Emma, Hamlet]`
**Answer: A — [Hamlet, 1984, Dune, Emma, 1984] followed by [1984, Dune, Emma, Hamlet].**
A: **Correct:** `ArrayDeque` preserves insertion order at front/back including duplicates (`[Hamlet, 1984, Dune, Emma, 1984]`), and `TreeSet` deduplicates and sorts them lexicographically (`[1984, Dune, Emma, Hamlet]`).
B: **Incorrect:** This reverses the two lines and omits the duplicate `1984` in the deque.
C: **Incorrect:** `addFirst("Hamlet")` places `Hamlet` before `1984`, and `add("1984")` appends a second `1984` at the end of `books`.
D: **Incorrect:** `TreeSet` removes duplicates and sorts the elements alphabetically (`[1984, Dune, Emma, Hamlet]`).
Question 8 MCQ · 4.0 marks
Consider the code given below.
What will the output be?
Published solution
**1. Trace the `for` loop inside the `try` block on `data = {12, -8, null, 15, -6}`:**
- **`i = 0` (`data[0] = 12`):** Not null \(\implies\) `data[0]` is updated in place to \(12 \times 5 = 60\).
- **`i = 1` (`data[1] = -8`):** Not null \(\implies\) `data[1]` is updated in place to \(-8 \times 5 = -40\).
- **`i = 2` (`data[2] = null`):** `data[2] == null` is true \(\implies\) throws `new MissingValueException()`.
**2. Trace the `catch` block and final `for` loop:**
- Because the `for` loop is **inside** the `try` block, throwing `MissingValueException` at `i = 2` immediately **aborts the `for` loop** (so indices `3` (`15`) and `4` (`-6`) are never processed!).
- The `catch` block runs `System.out.println(e);`, which invokes `e.toString()` and prints:
`Missing data point encountered`
- Next, the second `for` loop after the `catch` block prints all 5 elements of `data`:
`60 -40 null 15 -6 `
**Answer: D — Missing data point encountered followed by 60 -40 null 15 -6.**
A: **Incorrect:** After catching the exception, execution continues normally to the second `for` loop, which prints the array elements.
B: **Incorrect:** The exception thrown at index 2 terminates the first loop early, so `15` and `-6` are never multiplied by 5, and the exception message is printed first.
C: **Incorrect:** The second `for` loop iterates over the entire `data` array (`60 -40 null 15 -6`), not just the first two elements.
D: **Correct:** Indices 0 and 1 become `60` and `-40`, index 2 throws `MissingValueException` (printing `Missing data point encountered` and exiting the first loop), and the second loop prints `60 -40 null 15 -6`.
Question 9 MCQ · 4.0 marks
Consider the following block of code.
Assume that assertions are enabled during program execution. Which among the following code
blocks can replace the given code in order to generate an
with a customized
assertion error as shown below?
Published solution
**1. Recall the syntax of the Java `assert` statement with a detail message:**
Java provides two forms of the `assert` statement:
1. `assert expression1;` — throws an `AssertionError` with no message if `expression1` is `false`.
2. `assert expression1 : expression2;` — if `expression1` evaluates to `false`, throws an uncaught `java.lang.AssertionError` whose detail message is the string representation of `expression2`.
**2. Apply to the requirement:**
We want the program to throw `java.lang.AssertionError: Package not found` when `pkg` is `null` (i.e., we assert that `pkg != null` is true, with message `"Package not found"`):
```java
Package pkg = warehouse.getPackage();
assert pkg != null : "Package not found";
```
**Answer: A — Package pkg = warehouse.getPackage(); assert pkg != null : "Package not found";**
A: **Correct:** When assertions are enabled and `pkg` is `null`, `assert pkg != null : "Package not found";` throws `java.lang.AssertionError: Package not found`.
B: **Incorrect:** Uses the single-operand `assert pkg != null;` (which has no custom detail message) and catches `RuntimeException` (which does not catch `AssertionError`, since `AssertionError` extends `Error`).
C: **Incorrect:** `assert pkg != null;` throws an `AssertionError` with no detail message before the `if` statement is ever reached.
D: **Incorrect:** Catching `AssertionError` and printing `'Package not found'` suppresses the exception stack trace instead of generating an uncaught `AssertionError: Package not found`.
Question 10 MCQ · 4.0 marks
What will the output be?
Published solution
**1. Analyze `Vehicle.clone()` (Shallow Copy vs. Deep Copy):**
Look at `Vehicle.clone()`:
```java
public Vehicle clone() throws CloneNotSupportedException {
return (Vehicle) super.clone();
}
```
Although `Engine` implements `Cloneable`, `Vehicle.clone()` only calls `super.clone()` (`Object.clone()`) and **does NOT call `engine.clone()`**!
Therefore, `Vehicle bike = car.clone();` performs a **shallow copy**:
- `car` and `bike` are two separate `Vehicle` objects, each with its own `model` reference (`"Sedan"`).
- However, `car.engine` and `bike.engine` point to the **exact same shared `Engine` instance** in memory!
**2. Trace `bike.updateVehicle("Bike", "Electric")`:**
- `model = "Bike"` rebinds `bike.model` to the new `String` `"Bike"` (leaving `car.model` as `"Sedan"`).
- `engine.updateType("Electric")` mutates the `type` field inside the **shared `Engine` object** to `"Electric"`, affecting both `car.engine` and `bike.engine`!
Thus, printing `car + ", " + bike` outputs:
`Sedan : Electric, Bike : Electric`
**Answer: B — Sedan : Electric, Bike : Electric.**
A: **Incorrect:** `String` is immutable and `bike.model = "Bike"` only reassigns `bike`'s own `model` field, so `car.model` remains `"Sedan"`.
B: **Correct:** Because `Vehicle.clone()` performs a shallow copy (`super.clone()`), `car` and `bike` share the same `Engine` object, so mutating `engine.updateType("Electric")` changes both to `Electric` while `car.model` stays `Sedan`.
C: **Incorrect:** `Vehicle.clone()` does not clone the `engine` field, so `car.engine` is also mutated to `"Electric"`.
D: **Incorrect:** `bike.updateVehicle("Bike", "Electric")` updates both `bike.model` and the shared `engine`'s type.
Question 11 MCQ · 4.0 marks
Consider the Java code given below:
What will the output be for the above Java code?
Published solution
**1. Trace the Java Stream pipeline step by step:**
We start with `Integer[] readings = {28, 31, 35};`:
1. **`.map((t) -> t + 3)`:** Adds `3` to each element in the stream:
- \(28 + 3 = 31\)
- \(31 + 3 = 34\)
- \(35 + 3 = 38\)
The mapped stream contains `{31, 34, 38}`.
2. **`.filter((t) -> t > 30)`:** Keeps elements strictly greater than `30` from the **already-mapped** values `{31, 34, 38}`:
- \(31 > 30\) (kept!)
- \(34 > 30\) (kept!)
- \(38 > 30\) (kept!)
3. **`.forEach((x) -> System.out.println(x))`:** Prints `31`, `34`, and `38` on separate lines.
**Answer: D — 31, 34, 38.**
A: **Incorrect:** These are the original unmapped values `{28, 31, 35}`.
B: **Incorrect:** These are the original values filtered by `> 30` without applying `.map(t -> t + 3)`.
C: **Incorrect:** Because `.map(t -> t + 3)` runs *before* `.filter(t -> t > 30)`, `28` becomes `31` before the filter check and satisfies `31 > 30`.
D: **Correct:** Mapping `{28, 31, 35}` with `t + 3` produces `{31, 34, 38}`, all three of which satisfy `> 30`.
Question 12 MCQ · 4.0 marks
Method
returns an
describing the specified value,
if non-null, otherwise returns an empty
.
Based on this description, consider the code given below, and answer the question that follows.
Choose the correct option.
This program generates the output:
This program generates the output:
This program terminates abnormally due to
without printing any value.
This program terminates abnormally due to
after
printing the value:
Published solution
**1. Understand `Optional.ofNullable` and `ifPresent`:**
In the `for` loop over `pList`:
1. **First iteration (`Arun`, `seatNumber = "12A"`):**
- `Optional.ofNullable("12A")` returns a non-empty `Optional` containing `"12A"`.
- `op1.ifPresent(s -> System.out.println(s))` executes the lambda and prints **`12A`**.
2. **Second iteration (`Meera`, `seatNumber = null`):**
- `Optional.ofNullable(null)` safely returns `Optional.empty()` (it does **not** throw `NullPointerException`).
- Calling `op1.ifPresent(...)` on an empty `Optional` simply **does nothing** (the lambda is not executed).
Thus, the program prints only `12A` and terminates normally.
**Answer: B — This program generates the output: 12A.**
A: **Incorrect:** When `seatNumber` is `null`, `Optional.ofNullable(null)` returns an empty `Optional`, and `ifPresent` does not execute the print statement.
B: **Correct:** `Optional.ofNullable` wraps `"12A"` (which is printed by `ifPresent`) and turns `null` into `Optional.empty()` (which `ifPresent` safely skips).
C: **Incorrect:** `Optional.ofNullable` explicitly allows `null` arguments without throwing `NullPointerException`.
D: **Incorrect:** Unlike `Optional.of(null)`, `Optional.ofNullable(null)` never throws `NullPointerException`.
Question 13 MCQ · 4.0 marks
Consider the Java code given below.
Choose the correct option.
This program generates the output:
This program generates the output:
This program generates the output:
This program generates the output:
Published solution
**1. Understand `Collectors.partitioningBy(Predicate)`:**
`Collectors.partitioningBy(c -> c.getYield() >= 22.0)` partitions the stream of `Crop` objects into a `Map<Boolean, List<Crop>>` with two keys:
- **`true`:** List of crops whose yield is **\(\ge 22.0\)**:
- `Wheat` (`25.3 >= 22.0`)
- `Cotton` (`22.0 >= 22.0`)
- **`false`:** List of crops whose yield is **\(< 22.0\)**:
- `Rice` (`18.5 < 22.0`)
- `Maize` (`16.9 < 22.0`)
**2. Determine what `System.out.println(yieldMap.get(false))` prints:**
`yieldMap.get(false)` retrieves the list of crops for which the predicate was `false`, and `Crop.toString()` returns `name`, printing:
`[Rice, Maize]`
**Answer: C — This program generates the output: [Rice, Maize].**
A: **Incorrect:** `[Wheat, Cotton]` corresponds to `yieldMap.get(true)` (yields \(\ge 22.0\)), whereas the code prints `yieldMap.get(false)`.
B: **Incorrect:** `[Wheat]` is neither `yieldMap.get(true)` nor `yieldMap.get(false)`.
C: **Correct:** `yieldMap.get(false)` returns the list of crops with `getYield() < 22.0`, which are `Rice` (`18.5`) and `Maize` (`16.9`).
D: **Incorrect:** `Cotton` has yield `22.0 >= 22.0`, so `Cotton` is placed in the `true` partition, not the `false` partition.
Question 14 MCQ · 4.0 marks
Published solution
**1. Analyze custom serialization (`writeObject` and `readObject`) and `transient` fields in `Order`:**
In `class Order implements Serializable`:
- `price` (`2499.99`) is a normal non-transient field, so `out.defaultWriteObject()` and `in.defaultReadObject()` automatically serialize and deserialize `price = 2499.99`.
- `product` (`"Headphones"`) is declared **`transient`**, so `defaultWriteObject()` skips it! Because `writeObject` and `readObject` do not manually write or read `product`, upon deserialization `product` is initialized to its default reference value **`null`**.
- `orderId` (`567890`) is also declared **`transient`**, so `defaultWriteObject()` skips it. However, the custom `writeObject` method explicitly writes `out.writeInt(orderId + 1000)` (`568890`), and the custom `readObject` method explicitly reads it back and subtracts `1000`:
`orderId = in.readInt() - 1000 = 567890`!
**2. Determine the output of `System.out.println(obj)`:**
`price=2499.99, product=null, orderId=567890`
**Answer: C — price=2499.99, product=null, orderId=567890.**
A: **Incorrect:** `product` is `transient` (so it deserializes as `null`), while `orderId` is manually saved and restored by `writeObject`/`readObject`.
B: **Incorrect:** Because `product` is marked `transient` and is not manually serialized in `writeObject`, its value after deserialization is `null`.
C: **Correct:** `price` is saved by `defaultWriteObject()`, `product` is `transient` and becomes `null`, and `orderId` is custom-serialized as `orderId + 1000` and restored as `567890`.
D: **Incorrect:** The custom `writeObject` and `readObject` methods preserve `orderId = 567890`.
Question 15 MCQ · 4.0 marks
Consider the code given below. Assume that the file
contains the following lines of
text in it.
Choose the correct option.
generates
This program generates the output:
This program generates the output:
This program generates the output:
Published solution
**1. Trace the `Scanner` calls on `travel.txt` step by step:**
The file `travel.txt` contains 3 lines:
- Line 1: `"Travel broadens the mind and creates memories."`
- Line 2: `"Planning a journey requires careful preparation."`
- Line 3: `"Travel experiences can be educational and exciting."`
Now trace the four `System.out.println` statements:
1. `System.out.println("Data from file:");`
Prints: `Data from file:`
2. `System.out.println(scanner.nextLine());`
Reads and consumes the entire first line:
Prints: `Travel broadens the mind and creates memories.`
3. `System.out.println(scanner.next());`
Reads only the **next whitespace-delimited token (word)** from the start of Line 2 (`"Planning"`), leaving the cursor right before the space `" a journey requires careful preparation."` on Line 2!
Prints: `Planning`
4. `System.out.println(scanner.nextLine());`
Reads the **remainder of the current line (Line 2)** up to the newline character:
Prints: ` a journey requires careful preparation.`
**Answer: C — Data from file: / Travel broadens the mind and creates memories. / Planning / a journey requires careful preparation.**
A: **Incorrect:** `new Scanner(InputStream)` is a standard constructor and does not throw `IOException`.
B: **Incorrect:** `scanner.next()` reads only a single word (`Planning`), not the entire second line.
C: **Correct:** `nextLine()` reads Line 1, `next()` reads the first word `Planning` of Line 2, and the second `nextLine()` reads the rest of Line 2 (` a journey requires careful preparation.`).
D: **Incorrect:** After `nextLine()` consumes Line 1, the cursor is at the start of Line 2 (`Planning...`), not Line 3.
Question 16 MCQ · 4.0 marks
Consider the following code which converts temperatures given in Centigrade scale to Fahrenheit
scale and vice versa, using two threads. Once the conversion is finished, the program should check
whether there is a temperature value in the array which is the same in both the scales.
import java.util.*;
class Centigrade extends Thread{
double[] f_temp = null;
public Centigrade(double[] arr) {
f_temp = arr;
}
public void run() {
// converts the temperatures in f_temp to centigrade
for(int i = 0; i < f_temp.length; it+) {
£_temp[i] = ((£_temp[i] - 32)/9.0)*5;
}
5
class Fahrenheit extends Thread{
double[] c_temp = null;
public Fahrenheit (double[] arr) {
c_temp = arr;
}
public void run() {
// converts the temperatures in c_temp to fahrenheit
for(int i = 0; i < c_temp.length; i++) {
c_temp[i] = ((9.0/5.0)*c_temp[i]) + 32.0;
}
}
public class Test{
public static void main(String args[]) {
double temp_in_fahrenheit[] = {29.67, -40.0, 50.0, 32.0};
double temp_in_centigrade[] = {100.0, -92.54, 32.0, -40.0};
Centigrade cobj = new Centigrade(temp_in_fahrenheit) ;
Fahrenheit fobj = new Fahrenheit (temp_in_centigrade) ;
is the only temperature which is same in both the scales. Choose the correct option which
should be written in place of
, so that this program produces the result as
on
every execution.
Published solution
**1. Understand the thread synchronization requirement in `Test.main`:**
In `main`, two worker threads `cobj` and `fobj` are started via `cobj.start()` and `fobj.start()` to convert the elements of `temp_in_fahrenheit` and `temp_in_centigrade` in the background.
Immediately after `SEGMENT 1`, the `main` thread loops over both arrays to find the matching converted value (`-40.0`).
If the `main` thread runs the comparison loops before `cobj` and `fobj` have finished executing their `run()` methods, the arrays will still contain unconverted or partially converted numbers (a race condition)!
**2. Use `join()` to wait for both threads to finish:**
Calling `cobj.join();` and `fobj.join();` inside a `try-catch(InterruptedException e)` block causes the `main` thread to wait until **both `cobj` and `fobj` have completely finished executing** before checking the arrays, guaranteeing `-40.0` on every execution.
**Answer: A — try { cobj.join(); fobj.join(); } catch(InterruptedException e) {}.**
A: **Correct:** Calling `cobj.join()` and `fobj.join()` blocks `main` until both conversion threads complete their `run()` methods.
B: **Incorrect:** Calling `wait()` without holding the object's monitor lock (`synchronized`) immediately throws `IllegalMonitorStateException`.
C: **Incorrect:** `Thread.sleep(2)` sleeps for a fixed 2 ms, which does not guarantee that both threads have finished on a busy system.
D: **Incorrect:** Leaving `SEGMENT 1` blank creates a race condition where `main` can check the arrays before the worker threads finish converting them.
Question 17 MCQ · 5.0 marks
Consider the Java code given below.
Choose the correct option to fill in the blank at
such that the program generates the
following output.
All of these.
Published solution
**1. Examine the method calls inside `MusicApp.access(PARAM-1)`:**
Inside `access(_______)`, the code invokes all three methods on `obj`:
```java
obj.play();
obj.download();
obj.sharePlaylist();
```
- `Playable` only declares `play()` (does not have `download()` or `sharePlaylist()`).
- `Downloadable` only declares `download()` (does not have `play()` or `sharePlaylist()`).
- `PremiumContent extends Playable, Downloadable` and also declares `sharePlaylist()`, so a parameter of type **`PremiumContent obj`** exposes all three methods (`play()`, `download()`, and `sharePlaylist()`)!
**Answer: C — PremiumContent obj.**
A: **Incorrect:** A reference of type `Playable` only knows about `play()` and causes a compile-time error on `obj.download()` and `obj.sharePlaylist()`.
B: **Incorrect:** A reference of type `Downloadable` only knows about `download()` and causes a compile-time error on `obj.play()` and `obj.sharePlaylist()`.
C: **Correct:** `PremiumContent` extends both `Playable` and `Downloadable` and declares `sharePlaylist()`, making all three method calls valid.
D: **Incorrect:** Neither `Playable obj` nor `Downloadable obj` compiles because they lack the other interfaces' methods.
Question 18 MCQ · 5.0 marks
Method
of interface
has the following structure and functionality:
If the specified key is not already associated with a value or is associated with null, associates it
with the given non-null value. Otherwise, replaces the associated value with the results of the
given remapping function, or removes if the result is null.
Consider the code given below that uses the merge method to merge two maps, and answer the
question that follows.
Choose the correct option regarding the code.
It generates the output:
It generates the output:
It generates the output:
It generates
during runtime.
Published solution
**1. Trace the `TreeMap` creation and `merge` operations:**
First, `totalStock` is a `TreeMap<String, Integer>` (which always maintains keys in **alphabetical/natural sorted order**).
1. Copying `warehouse1` puts:
`{"Laptop": 12, "Tablet": 8}` into `totalStock`.
2. Next, iterating over `warehouse2` (`{"Laptop": 7, "Monitor": 5}`) and calling `totalStock.merge(e.getKey(), e.getValue(), (x, y) -> y + x)`:
- For `"Laptop"` (already present with value `12`, new value `7`): applies the remapping function `(12, 7) -> 7 + 12 = 19`, updating `"Laptop"` to **`19`**.
- For `"Monitor"` (not present in `totalStock`): inserts `"Monitor"` with value **`5`**.
- `"Tablet"` remains **`8`**.
**2. Format the `TreeMap` output in alphabetical order of keys (`Laptop, Monitor, Tablet`):**
`{Laptop=19, Monitor=5, Tablet=8}`
**Answer: A — It generates the output: {Laptop=19, Monitor=5, Tablet=8}.**
A: **Correct:** `merge` sums the existing and new counts for `Laptop` (`12 + 7 = 19`), inserts `Monitor=5`, keeps `Tablet=8`, and `TreeMap` prints keys in alphabetical order.
B: **Incorrect:** `merge` applies the remapping function `(x, y) -> y + x` when a key already exists, giving `Laptop=19` rather than overwriting with `7`.
C: **Incorrect:** Because `totalStock` is a `TreeMap`, keys are printed in alphabetical order (`Laptop, Monitor, Tablet`), not `Laptop, Tablet, Monitor`.
D: **Incorrect:** All keys and values are non-null, so no `NullPointerException` occurs.
Question 19 MCQ · 5.0 marks
Consider the Java code given below.
Which of the following is NOT true about the given code?
This program may generate
.
The program may generate the output:
The program may generate the output:
The program may generate the output:
Published solution
**1. Note that the question asks: "Which of the following is NOT true about the given code?"**
Look at the map implementation used in `Hospital.main`:
`Map<String, String> patientMap = new ConcurrentHashMap();`
**2. Understand weakly consistent iterators in `ConcurrentHashMap`:**
- Unlike `HashMap` (whose iterators are *fail-fast* and throw `ConcurrentModificationException` if modified concurrently), `ConcurrentHashMap` is a thread-safe concurrent collection whose iterators are **weakly consistent**.
- A `ConcurrentHashMap` iterator **never throws `ConcurrentModificationException`**! Depending on thread scheduling between `main` and thread `t` (`patientMap.put("D", "Divya")`), the iterator may or may not reflect the insertion of `"D" => "Divya"`.
- Therefore, Statement A (*"This program may generate `ConcurrentModificationException`."*) is **NOT true**!
**Answer: A — This program may generate ConcurrentModificationException.**
A: **Correct:** This statement is NOT true (so select it): `ConcurrentHashMap` iterators are weakly consistent and are guaranteed never to throw `ConcurrentModificationException`.
B: **Incorrect:** This output is possible if thread `t` inserts `"D" => "Divya"` before the iterator finishes traversing the buckets.
C: **Incorrect:** Because `ConcurrentHashMap` does not guarantee insertion order, `"D" => "Divya"` can also appear first if inserted before iteration starts.
D: **Incorrect:** This output is possible if the `main` thread finishes iterating over `A, B, C` before thread `t` executes `put("D", "Divya")`.
Question 20 MCQ · 5.0 marks
The Java code given below produces a toggle button. With the first click, the room light should be
switched on, with the next click it should be switched off, and on the next click, it should be
switched on again, and so on. Based on the requirement, answer the question that follows the
code.
Choose the correct code segment inside method actionPerformed() such that the given behaviour
can be implemented correctly.
Published solution
**1. Understand how `ActionCommand` controls the toggle button state in Swing:**
In the `SmartHome` constructor:
- `btnToggle = new JButton("Light");` (note: it is a regular `JButton`, not a `JToggleButton`).
- `btnToggle.setActionCommand("ON");` initializes the button's action command string to `"ON"`.
**2. Trace what `actionPerformed(ActionEvent e)` must do on each click:**
- When `e.getActionCommand().equals("ON")` (first click, 3rd click, etc.):
1. Switch the room light on by setting `pnlLight.setBackground(Color.yellow);`.
2. Flip the button's action command for the *next* click using `btnToggle.setActionCommand("OFF");`.
- When `e.getActionCommand().equals("OFF")` (second click, 4th click, etc.):
1. Switch the room light off by setting `pnlLight.setBackground(Color.darkGray);`.
2. Flip the button's action command back to `"ON"` using `btnToggle.setActionCommand("ON");`.
This exact logic is implemented in **Option A**.
**Answer: A — if(e.getActionCommand().equals("ON")){ btnToggle.setActionCommand("OFF"); pnlLight.setBackground(Color.yellow); } else if(e.getActionCommand().equals("OFF")){ btnToggle.setActionCommand("ON"); pnlLight.setBackground(Color.darkGray); }.**
A: **Correct:** Checks `e.getActionCommand()` (`"ON"` vs `"OFF"`), updates `pnlLight`'s background color accordingly, and toggles `btnToggle.setActionCommand(...)` for the next click.
B: **Incorrect:** On a standard `JButton`, `btnToggle.isSelected()` is always `false` because `JButton` does not maintain a toggle selection state.
C: **Incorrect:** Because `btnToggle.isSelected()` is checked first (and is always `false` on a `JButton`), the panel background is always set to `darkGray`.
D: **Incorrect:** `e.getSource()` returns the `JButton` object reference itself, which is never `.equals("ON")` or `.equals("OFF")`.
Question 21 MCQ · 5.0 marks
Consider the following Java code and choose the correct option.
This program prints
followed by
with message
.
This program generates
.
This program generates output:
This program generates output:
Published solution
**1. Understand `Optional.orElseThrow(Supplier)`:**
In `Example.show()`:
```java
System.out.println(op.orElseThrow(() -> new UserException("No number detected")));
```
- If the `Optional<Integer> op` contains a value, `orElseThrow` returns that unwrapped value.
- If `op` is empty (`Optional.empty()`), `orElseThrow` invokes the supplier lambda and throws the returned exception (`UserException`).
**2. Trace the two calls in `Test.main`:**
1. `Optional<Integer> op = Optional.of(100); new Example(op).show();`
Since `op` contains `100`, `show()` prints **`100`**.
2. `Optional<Integer> op2 = Optional.empty(); new Example(op2).show();`
Since `op2` is empty, `orElseThrow` throws **`UserException`** with message **`"No number detected"`**.
**Answer: A — This program prints 100 followed by UserException with message "No number detected".**
A: **Correct:** The first call unwraps and prints `100`, and the second call on `Optional.empty()` throws `UserException: No number detected`.
B: **Incorrect:** `Optional.empty()` creates a valid empty `Optional` object (not a `null` reference), so `orElseThrow` throws `UserException`, not `NullPointerException`.
C: **Incorrect:** `orElseThrow` throws an exception on an empty `Optional` rather than returning `null`.
D: **Incorrect:** `orElseThrow` throws `UserException` when empty instead of printing `Optional.empty`.
Question 22 MCQ · 5.0 marks
Consider the code given below.
Identify the appropriate option to fill in the blank at
, such that the threads
and
execute the
function in parallel.
Published solution
**1. Analyze what `PrlProdList` needs to inherit and implement:**
1. Inside `PrlProdList.run()`, the method `show()` of class `ProdList` is called directly without an object prefix. Therefore, `PrlProdList` must **extend `ProdList`** (`extends ProdList`).
2. In `FClass.main()`, `new PrlProdList()` is passed to the `Thread(Runnable target)` constructor (`new Thread(new PrlProdList())`). Therefore, `PrlProdList` must **implement the `Runnable` interface** (`implements Runnable`).
**2. Combine in valid Java class declaration syntax:**
In Java, `extends` must always come before `implements` (and Java does not allow extending multiple classes like `extends ProdList, Thread`):
`class PrlProdList extends ProdList implements Runnable`
**Answer: D — extends ProdList implements Runnable.**
A: **Incorrect:** Without `extends ProdList`, calling `show()` inside `PrlProdList.run()` fails to compile.
B: **Incorrect:** Without `implements Runnable`, `new Thread(new PrlProdList())` fails to compile because `PrlProdList` is not a `Runnable`.
C: **Incorrect:** Java does not support multiple inheritance of classes (`extends ProdList, Thread` is a syntax error).
D: **Correct:** Extending `ProdList` provides the `show()` method, and implementing `Runnable` allows instances of `PrlProdList` to be passed to `new Thread(...)`.
Question 23 MSQ · 5.0 marks
Consider the Java code given below.
Choose the correct option(s).
The program will always generate the output:
The program will always generate the output:
The output can be
or
or
or
or
and can also cycle back
and start again.
The program may not generate any output.
Published solution
**1. Analyze the multithreaded interaction between `main` and thread `t1`:**
In `ServerStatus.main`:
```java
Thread t1 = new Thread(monitor);
t1.start();
monitor.setStop(true);
```
1. `t1.start()` schedules thread `t1` to run `monitor.run()`, which loops `while (!stopRequested)` printing elements of `{"Online", "Busy", "Idle", "Warning", "Offline"}` cyclically.
2. Immediately on the next line, the `main` thread calls `monitor.setStop(true)`, which sets `stopRequested = true` (and note that `stopRequested` is not even `volatile`, nor is there any synchronization).
**2. Determine the possible outputs depending on OS thread scheduling:**
- **Case 1:** If the `main` thread executes `monitor.setStop(true)` **before** the OS scheduler gives `t1` its first CPU slice to check `while (!stopRequested)`, then `t1` sees `stopRequested == true` immediately and exits the loop **without printing anything**! (Statement D is **correct**!)
- **Case 2:** If `t1` starts running before `main` executes `monitor.setStop(true)` (or before the write becomes visible), `t1` can print 1, 2, 3, 4, 5, or more status strings (and even cycle back around via `(index + 1) % status.length`) before seeing `stopRequested == true` and stopping! (Statement C is **correct**!)
- Because thread scheduling is non-deterministic, it is **not** guaranteed to always produce a fixed sequence (Statements A and B are **incorrect**).
**Answer: C, D — The output can be partial or cycle back depending on thread scheduling, or the program may not generate any output at all.**
A: **Incorrect:** Thread scheduling is non-deterministic; `t1` is not guaranteed to print all 5 elements exactly once before stopping.
B: **Incorrect:** `t1` may print fewer or more than 1 element (or none at all) depending on when `setStop(true)` takes effect.
C: **Correct:** Depending on how many loop iterations `t1` executes before observing `stopRequested == true`, it can print any prefix of the array or wrap around via modulo indexing.
D: **Correct:** If `main` sets `stopRequested = true` before `t1` enters the `while (!stopRequested)` loop, `t1` terminates immediately and prints nothing.
Question 24 MSQ · 5.0 marks
Consider the Java code given below.
Which of the following options is/are possible result/s of the above code?
Published solution
**1. Analyze the `synchronized` method `bookTicket` on the shared `Stadium` object:**
In `SportsBooking.main`:
- A single shared `Stadium` instance has `available = 1` ticket.
- Two threads `t1` (`"Arjun"`, requesting `1` ticket) and `t2` (`"Meera"`, requesting `1` ticket) call `stadium.bookTicket(1, name)`.
- Because `bookTicket` is declared **`synchronized`** on the shared `stadium` instance, only **one** thread can execute `bookTicket` at a time (mutual exclusion, no race condition!).
**2. Determine the two possible execution orders:**
- **Order 1 (`t1` acquires the lock first):**
`"Arjun"` sees `available = 1 >= 1`, decrements `available` to `0`, and prints `"Arjun booked 1 ticket"`. Next, `"Meera"` enters `bookTicket`, sees `available = 0 < 1`, and prints `"Meera cannot book 1 ticket"`. (**Option C!**)
- **Order 2 (`t2` acquires the lock first):**
`"Meera"` sees `available = 1 >= 1`, decrements `available` to `0`, and prints `"Meera booked 1 ticket"`. Next, `"Arjun"` enters `bookTicket`, sees `available = 0 < 1`, and prints `"Arjun cannot book 1 ticket"`. (**Option A!**)
Because `bookTicket` is `synchronized`, it is impossible for both to book a ticket (Option B) or for neither to book a ticket (Option D).
**Answer: A, C — Either Meera books 1 ticket and Arjun cannot, or Arjun books 1 ticket and Meera cannot.**
A: **Correct:** If thread `t2` (`Meera`) acquires the `stadium` monitor lock before `t1` (`Arjun`), Meera books the 1 available ticket and Arjun cannot.
B: **Incorrect:** Because `bookTicket` is `synchronized` on the shared `stadium` object, both threads cannot book the single available ticket.
C: **Correct:** If thread `t1` (`Arjun`) acquires the `stadium` monitor lock before `t2` (`Meera`), Arjun books the 1 available ticket and Meera cannot.
D: **Incorrect:** Since `available` starts at `1`, the first thread to enter `bookTicket` is guaranteed to succeed.