Programming Concepts using Java · End Term · Jan 2026 · FN
Programming Concepts using Java · End Term · Jan 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.
What will the output be?
**1. Trace object creation and copy constructor in `Showroom.main()`:**
1. `Vehicle v1 = new Car("Sedan", 5);` creates a `Car` instance with `model = "Sedan"` and `seat_count = 5`.
2. `Vehicle v2 = new Car((Car)v1);` invokes the `Car(Car c)` copy constructor, which creates a **separate `Car` object** initialized with `model = c.model` (`"Sedan"`) and `seat_count = c.seat_count` (`5`).
3. `v2.model = "SUV";` modifies the `model` field of `v2` only; `v1.model` remains `"Sedan"`.
**2. Trace `System.out.println(v1 + "\n" + v2)`:**
Because dynamic method dispatch calls the overridden `Car.toString()` on both `v1` and `v2`:
- Line 1 (`v1`): `model = Sedan, seat_count = 5`
- Line 2 (`v2`): `model = SUV, seat_count = 5`
**Answer: C — `model = Sedan, seat_count = 5` followed by `model = SUV, seat_count = 5`**
A: **Incorrect:** `v1` and `v2` are distinct objects (`v1.model` stays `Sedan`), and `Car.toString()` includes `seat_count = 5`.
B: **Incorrect:** Modifying `v2.model` does not affect `v1.model` because `new Car((Car)v1)` created an independent copy.
C: **Correct:** `v1` retains `model = Sedan, seat_count = 5` while `v2` prints `model = SUV, seat_count = 5` via overridden `Car.toString()`.
D: **Incorrect:** Dynamic dispatch invokes `Car.toString()`, which appends `, seat_count = 5` to `super.toString()`.
Question 3 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 insertions into `ArrayDeque<String> topics`:**
- `topics.add("Algebra")` (adds to back) \(\to\) `[Algebra]`
- `topics.addFirst("Physics")` (adds to front) \(\to\) `[Physics, Algebra]`
- `topics.add("Chemistry")` (adds to back) \(\to\) `[Physics, Algebra, Chemistry]`
- `topics.addFirst("Mathematics")` (adds to front) \(\to\) `[Mathematics, Physics, Algebra, Chemistry]`
- `topics.add("Physics")` (adds to back; `ArrayDeque` allows duplicates) \(\to\) **`[Mathematics, Physics, Algebra, Chemistry, Physics]`**
**2. Trace `new TreeSet<String>(topics)`:**
`TreeSet` removes duplicates (`"Physics"` appears once) and sorts elements in natural alphabetical order:
**`[Algebra, Chemistry, Mathematics, Physics]`**
**Answer: A — `[Mathematics, Physics, Algebra, Chemistry, Physics]` followed by `[Algebra, Chemistry, Mathematics, Physics]`**
A: **Correct:** `ArrayDeque` preserves insertion order (`addFirst` at front, `add` at back, keeping duplicates), while `TreeSet` deduplicates and sorts alphabetically.
B: **Incorrect:** Swaps the output order of `topics` (`ArrayDeque`) and `set` (`TreeSet`).
C: **Incorrect:** `ArrayDeque` does not sort or deduplicate elements.
D: **Incorrect:** `TreeSet` removes duplicate `'Physics'` and sorts strings alphabetically.
Question 4 MCQ · 4.0 marks
Consider the Java code given below.
Identify the appropriate statement to fill in the blank at
, such that the output is:
Published solution
**1. Analyze the visibility and return types in `BookList`:**
- `iter.get_next()` has return type `Object` (as declared in `interface Iterator`), so calling `.print()` directly on `iter.get_next()` fails compilation because `Object` has no `print()` method.
- Inside `BookList`, the inner class `private class Book extends Printable` is declared **`private`**, so `Book` is not visible outside `BookList` (inside `IterTest.main()`). Casting to `(Book)` inside `IterTest` causes a compile-time visibility error.
- However, `Book` extends the package-private abstract class **`Printable`**, which declares `public abstract void print();`.
**2. Conclude the valid statement at `LINE 1`:**
Casting `iter.get_next()` to `Printable` and calling `.print()`:
`((Printable)iter.get_next()).print();`
compiles cleanly and invokes `Book.print()` via polymorphism.
**Answer: A — `((Printable)iter.get_next()).print();`**
A: **Correct:** Casts the `Object` returned by `iter.get_next()` to the accessible superclass `Printable` and invokes `print()` polymorphically.
B: **Incorrect:** `Book` is a `private` inner class of `BookList` and cannot be referenced inside `IterTest`.
C: **Incorrect:** Each element is a `Book` (which extends `Printable`), not a `BookList`, and `BookList` has no `print()` method.
D: **Incorrect:** `iter.get_next()` returns `Object`, which does not declare a `print()` method.
Question 5 MCQ · 4.0 marks
Consider the following block of code.
Which among the following code blocks can replace the given code in order to generate a
customized assertion error as shown below?
Published solution
**1. Understand Java `assert` syntax:**
In Java, the two-part assertion statement is:
`assert <boolean_expression> : <detail_message_expression>;`
- When `<boolean_expression>` evaluates to `true`, execution continues normally.
- When `<boolean_expression>` evaluates to `false` (and assertions are enabled with `-ea`), Java throws a `java.lang.AssertionError` whose message is `<detail_message_expression>`.
**2. Match the required assertion:**
We want to assert that `server` is **not** `null` (`server != null`), and if it is `null`, throw an uncaught `AssertionError` with message `"Server not available"`:
```java
Server server = network.getActiveServer();
assert server != null : "Server not available";
```
**Answer: A — `Server server = network.getActiveServer(); assert server != null : "Server not available";`**
A: **Correct:** Uses `assert server != null : "Server not available";` to throw `java.lang.AssertionError: Server not available` when `server` is `null`.
B: **Incorrect:** `assert server != null;` has no custom detail message, and `AssertionError` is an `Error`, not a `RuntimeException`.
C: **Incorrect:** If `assert server != null;` fails, it throws `AssertionError` without a custom message before reaching the `if` statement.
D: **Incorrect:** Catches the `AssertionError` and prints to stdout instead of generating the stack trace shown.
Question 6 MCQ · 4.0 marks
Consider the Java code given below.
Choose the correct option.
It generates the output:
Compilation fails because
and
cannot be converted to
Compilation fails because
method has not been defined in
classes
and
It generates the output:
Published solution
**1. Trace the inheritance and method overriding in `DatasetApp`:**
- `Dataset` defines `load()` (`"Loading a generic dataset"`) and `summarize()` (`"Summarizing dataset"`).
- `CSVFile extends Dataset` overrides `load()` to print `"Loading CSV file"` and inherits `summarize()`.
- `ExcelFile extends Dataset` overrides `load()` to print `"Loading Excel file"` and inherits `summarize()`.
**2. Trace `describe(csv)` and `describe(excel)`:**
- `describe(csv)` calls `csv.load()` (prints `Loading CSV file`) and `csv.summarize()` (prints `Summarizing dataset`).
- `describe(excel)` calls `excel.load()` (prints `Loading Excel file`) and `excel.summarize()` (prints `Summarizing dataset`).
**Answer: D — Prints `Loading CSV file`, `Summarizing dataset`, `Loading Excel file`, `Summarizing dataset`**
A: **Incorrect:** Overridden `load()` methods in `CSVFile` and `ExcelFile` are dynamically dispatched at runtime instead of calling `Dataset.load()`.
B: **Incorrect:** Upcasting subclasses (`CSVFile` and `ExcelFile`) to their superclass reference `Dataset` is always valid.
C: **Incorrect:** Subclasses automatically inherit the public `summarize()` method from `Dataset`.
D: **Correct:** Dynamic method dispatch calls each subclass's overridden `load()` followed by the inherited `summarize()` method.
Question 7 MCQ · 4.0 marks
Consider the Java code given below.
Choose the correct option to fill in place of
so that the output is:
Published solution
**1. Analyze inner class visibility in `PaymentGateway`:**
- Inside `PaymentGateway`, both `CreditCard` and `UPI` are declared as **`private` inner classes** (`private class CreditCard implements Payment` and `private class UPI implements Payment`).
- Because they are `private`, the type names `CreditCard` and `UPI` cannot be used inside `Test.main()`.
- However, both implement the package-private interface **`Payment`**, and `PaymentGateway` provides `public` factory methods `m.getCreditCard()` and `m.getUPI()`.
**2. Identify the valid code block in `Test.main()`:**
Storing the returned objects in variables of the accessible interface type `Payment`:
```java
Payment obj1 = m.getCreditCard();
Payment obj2 = m.getUPI();
```
compiles cleanly and allows calling `obj1.process()` and `obj2.process()`.
**Answer: B — `Payment obj1 = m.getCreditCard(); Payment obj2 = m.getUPI();`**
A: **Incorrect:** `CreditCard` and `UPI` are `private` inner classes of `PaymentGateway` and cannot be instantiated directly from `Test`.
B: **Correct:** Uses the public factory methods `m.getCreditCard()` and `m.getUPI()` and assigns them to the accessible `Payment` interface type.
C: **Incorrect:** The type names `CreditCard` and `UPI` are `private` to `PaymentGateway` and inaccessible in `Test`.
D: **Incorrect:** Cannot directly instantiate `private` inner classes `new CreditCard()` and `new UPI()` outside `PaymentGateway`.
Question 8 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(s -> s.getMarks() >= 75.0)` splits the stream of `Student` objects into a `Map<Boolean, List<Student>>` with two keys:
- Key `true`: students whose marks are `>= 75.0` (`Ravi` with `82.3` and `Kiran` with `75.0`).
- Key `false`: students whose marks are `< 75.0` (`Asha` with `65.5` and `Neha` with `58.9`).
**2. Trace `System.out.println(marksMap.get(false))`:**
`marksMap.get(false)` returns the list of students who did not satisfy `marks >= 75.0`, which prints **`[Asha, Neha]`**.
**Answer: C — `[Asha, Neha]`**
A: **Incorrect:** `[Ravi, Kiran]` is the list for `marksMap.get(true)` (`marks >= 75.0`).
B: **Incorrect:** `marksMap.get(false)` retrieves all students with `marks < 75.0`, not `[Ravi]`.
C: **Correct:** `Asha` (`65.5`) and `Neha` (`58.9`) have marks below `75.0`, so `marksMap.get(false)` prints `[Asha, Neha]`.
D: **Incorrect:** `Kiran` has `75.0 >= 75.0`, so `Kiran` is in the `true` partition, not `false`.
Question 9 MCQ · 4.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. Analyze the methods called on `obj` inside `Executor.execute()`:**
Inside `execute(___)`:
- `obj.selectItems();` (declared in `Step1`)
- `obj.makePayment();` (declared in `Step2`)
- `obj.confirmOrder();` (declared in `Step3`)
**2. Check the interface hierarchy:**
`interface Step3 extends Step1, Step2` inherits `selectItems()` from `Step1` and `makePayment()` from `Step2`, and adds `confirmOrder()`. Therefore, declaring the parameter as **`Step3 obj`** (or `OnlineOrder obj`) is required so all three methods are known at compile time on `obj`.
**Answer: C — `Step3 obj`**
A: **Incorrect:** `Step1` only declares `selectItems()`, so `obj.makePayment()` and `obj.confirmOrder()` fail to compile.
B: **Incorrect:** `Step2` only declares `makePayment()`, so `obj.selectItems()` and `obj.confirmOrder()` fail to compile.
C: **Correct:** `Step3` extends both `Step1` and `Step2` and declares `confirmOrder()`, so all three method calls compile and run.
D: **Incorrect:** Neither `Step1 obj` nor `Step2 obj` compiles because they lack the other interfaces' methods.
Question 10 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 terminates abnormally due to unhandled exception(s).
Published solution
**1. Understand `Map.getOrDefault(key, defaultValue)`:**
`map.getOrDefault(k, def)` returns the value mapped to `k` if `k` exists in `map`; otherwise it returns `def`.
**2. Trace the entries added to `national` and `regional` (`LinkedHashMap` preserves insertion order):**
- `schoolA` has only `"A NAT" -> "Twice"`.
- `regional.put("A REG", schoolA.getOrDefault("A REG", "N/A"))` \(\to\) puts `"A REG" -> "N/A"` in `regional`.
- `national.put("A NAT", schoolA.getOrDefault("A NAT", "N/A"))` \(\to\) puts `"A NAT" -> "Twice"` in `national`.
- `schoolB` has only `"B REG" -> "Once"`.
- `national.put("B NAT", schoolB.getOrDefault("B NAT", "N/A"))` \(\to\) puts `"B NAT" -> "N/A"` in `national`.
- `regional.put("B REG", schoolB.getOrDefault("B REG", "N/A"))` \(\to\) puts `"B REG" -> "Once"` in `regional`.
**3. Trace the two `for` loops:**
- First loop (`national`): prints `A NAT Twice` then `B NAT N/A`.
- Second loop (`regional`): prints `A REG N/A` then `B REG Once`.
**Answer: B — Prints `A NAT Twice`, `B NAT N/A`, `A REG N/A`, `B REG Once`**
A: **Incorrect:** Omits the entries where `getOrDefault` returned `"N/A"` (`B NAT N/A` and `A REG N/A`).
B: **Correct:** Prints both entries of `national` (`A NAT Twice`, `B NAT N/A`) followed by both entries of `regional` (`A REG N/A`, `B REG Once`).
C: **Incorrect:** Omits the entries that existed in `schoolA` and `schoolB`.
D: **Incorrect:** `getOrDefault` safely returns `"N/A"` for missing keys without throwing any exception.
Question 11 MCQ · 4.0 marks
Consider the Java code given below.
Choose the correct option.
It generates the output:
It generates the output:
It generates the output:
It generates the output:
Published solution
**1. Trace the stream pipeline in `DeliveryAnalysis.main()`:**
1. Input list `deliveryTimes`: `[45.5, 60.2, 39.8, 72.4]`.
2. `.filter(n -> n < 50)` keeps only elements strictly less than `50.0`: `[45.5, 39.8]`.
3. `.max(Double::compareTo)` finds the maximum element among `[45.5, 39.8]`, returning `Optional.of(45.5)`.
4. `value.ifPresentOrElse(...)` sees a non-empty `Optional` and prints **`45.5`**.
**Answer: C — `45.5`**
A: **Incorrect:** Two elements (`45.5` and `39.8`) are less than `50`, so the `Optional` is non-empty.
B: **Incorrect:** `72.4` is filtered out by `.filter(n -> n < 50)`.
C: **Correct:** Among the values less than `50` (`45.5` and `39.8`), the maximum is `45.5`.
D: **Incorrect:** `39.8` is the minimum of the filtered elements, whereas `.max(...)` selects the maximum (`45.5`).
Question 12 MCQ · 4.0 marks
Consider the Java code given below.
Suppose the file
is written successfully by the program.
What will the output be?
Published solution
**1. Inspect the contents written to `notes.txt`:**
Line 1: `it stores two numbers\n`
Line 2: `10 is first\n`
Line 3: `20 is second\n`
**2. Trace the `Scanner` calls in `readFromFile("notes.txt")`:**
1. `sc.next()` reads the first whitespace-delimited token on Line 1: prints **`it`**.
2. `sc.nextLine()` reads the remainder of Line 1 up to the newline: prints **` stores two numbers`**.
3. `sc.nextInt()` reads the integer token at the start of Line 2: prints **`10`**.
4. `sc.nextLine()` reads the remainder of Line 2 up to the newline: prints **` is first`**.
**Answer: C — `it`, ` stores two numbers`, `10`, ` is first`**
A: **Incorrect:** Both writing and reading succeed without throwing an `IOException`.
B: **Incorrect:** `sc.nextLine()` consumes only the rest of the current line after `sc.next()`, not the entire line from the beginning.
C: **Correct:** `sc.next()` reads `it`, `sc.nextLine()` reads the rest of line 1 (` stores two numbers`), `sc.nextInt()` reads `10`, and `sc.nextLine()` reads the rest of line 2 (` is first`).
D: **Incorrect:** `sc.nextLine()` after `sc.next()` finishes line 1 rather than skipping to line 2.
Question 13 MCQ · 4.0 marks
Consider the code given below that checks whether two normal distributions are identical. Method
is overridden to compare two
objects as follows. If two
distributions have the same mean and variance, then both are considered identical. Based on the
given information, answer the question that follows.
Choose the correct option to fill in place of
so that the output is:
Published solution
**1. Analyze `equals(Object obj)` overriding in `NormalDistribution`:**
Because the parameter `obj` has compile-time type `Object`, we cannot access `obj.mean` or `obj.variance` directly without **explicitly downcasting** `obj` to `NormalDistribution`.
**2. Check the four options:**
- **Option A:** Uses variable `s` (`s.mean`) without declaring `s`, failing compilation.
- **Option B & Option C:** Write `NormalDistribution s = obj;` without a cast and access `obj.mean`, both of which fail compilation (`Object` cannot be converted to `NormalDistribution` without a cast, and `Object` has no field `mean`).
- **Option D:** Properly checks `if (obj instanceof NormalDistribution)`, downcasts `NormalDistribution s = (NormalDistribution) obj;`, and returns `true` when `this.mean == s.mean && this.variance == s.variance`, else `false`.
**Answer: D**
A: **Incorrect:** References `s.mean` and `s.variance` without declaring or initializing `s`.
B: **Incorrect:** Fails to compile because `NormalDistribution s = obj;` lacks an explicit `(NormalDistribution)` cast and `obj.mean` is invalid on type `Object`.
C: **Incorrect:** Fails to compile (no cast on `obj` and accesses `obj.mean`) and also inverts the boolean return logic.
D: **Correct:** Safely checks `instanceof`, explicitly casts `(NormalDistribution) obj` to `s`, and compares `this.mean == s.mean && this.variance == s.variance`.
Question 14 MCQ · 4.0 marks
Consider the following Java code that uses chained exceptions.
What can be the output of this code?
Published solution
**1. Trace the chained exception flow in `DataService.processData()`:**
1. Inside the `try` block of `processData()`, `throw new DataStorageException("Insufficient memory for dataset")` is thrown.
2. The `catch (DataStorageException e)` block catches `e`, creates `DataProcessingException dpe = new DataProcessingException("Failed to process dataset")`, chains the original exception as the cause via `dpe.initCause(e)`, and throws `dpe`.
**2. Trace `DataApp.main()`:**
- `e.getMessage()` returns the message of `dpe`: **`Failed to process dataset`**.
- `e.getCause().getMessage()` returns the message of the chained `DataStorageException`: **`Reason: Insufficient memory for dataset`**.
**Answer: A — `Failed to process dataset` followed by `Reason: Insufficient memory for dataset`**
A: **Correct:** `e` is the outer `DataProcessingException` (`Failed to process dataset`) and `e.getCause()` is the inner `DataStorageException` (`Insufficient memory for dataset`).
B: **Incorrect:** Reverses the outer exception message (`e.getMessage()`) and the inner cause message (`e.getCause().getMessage()`).
C: **Incorrect:** Omits the first line printed by `System.out.println(e.getMessage())`.
D: **Incorrect:** Omits the first line and prints the outer message instead of `e.getCause().getMessage()`.
Question 15 MCQ · 4.0 marks
Method
returns an infinite sequential ordered
produced by
iterative application of a function
to an initial element
, producing a
consisting of
,
,
, etc. Based on the above information, consider the code given below, and answer
the question that follows.
What will the output be?
Published solution
**1. Trace the stream pipeline in `Test.main()`:**
1. `Stream.iterate(1, n -> n + 2)` generates the infinite stream of odd positive integers: \(1, 3, 5, 7, 9, \dots\)
2. `.map(n -> n * n)` squares each odd integer: \(1^2 = 1,\; 3^2 = 9,\; 5^2 = 25,\; 7^2 = 49, \dots\)
3. `.filter(n -> n % 4 == 1)` keeps numbers whose remainder mod 4 is 1. Since the square of any odd number \((2k+1)^2 = 4k(k+1) + 1 \equiv 1 \pmod 4\), all of \(1, 9, 25, \dots\) pass the filter!
4. `.limit(3)` takes the first 3 elements: **`1 9 25`**.
**Answer: A — `1 9 25`**
A: **Correct:** The first three odd numbers `1, 3, 5` squared are `1, 9, 25`, all of which satisfy `n % 4 == 1`.
B: **Incorrect:** `1, 3, 5` are the unmapped odd numbers before `.map(n -> n * n)` squares them.
C: **Incorrect:** `1` (`1 % 4 == 1`) is not filtered out, so the output starts with `1`.
D: **Incorrect:** `4, 16, 36` are squares of even numbers (`% 4 == 0`), not odd numbers.
Question 16 MCQ · 4.0 marks
Consider the code given below.
Choose the correct option.
The code always prints 2000.
The code prints any number in the range 1000 to 2000
The code prints any number in the range 0 to 1000
The code always prints 1000.
Published solution
**1. Analyze the multithreaded race condition on `Experiment.totalObservations`:**
Two threads (`t1` and `t2`) concurrently execute `Experiment.totalObservations++` `1000` times each without synchronization (`synchronized` or `AtomicInteger`).
**2. Determine the possible range of final values:**
- **Maximum (`2000`):** If all 1,000 increments from `t1` and all 1,000 increments from `t2` interleave without any lost updates, the final value is `2000`.
- **At least `1000` in typical interleavings:** Each thread performs 1,000 read-modify-write increments; when both threads overlap on the same value, updates can be lost, producing a non-deterministic result in the range **`1000` to `2000`**.
**Answer: B — The code prints any number in the range 1000 to 2000**
A: **Incorrect:** Because `totalObservations++` is not synchronized, lost updates during thread interleaving can produce values less than 2000.
B: **Correct:** Due to the data race on the unsynchronized static counter, updates can overlap, resulting in a value between 1000 and 2000.
C: **Incorrect:** Each thread increments 1000 times starting from 0, so the count reaches at least 1000.
D: **Incorrect:** If the threads do not overlap on every single iteration, the result exceeds 1000.
Question 17 MCQ · 4.0 marks
Consider the Java code given below.
What will the output be?
Published solution
**1. Analyze the `clone()` implementation in `ResearchPaper`:**
Inside `ResearchPaper.clone()`:
```java
ResearchPaper r = (ResearchPaper) super.clone();
r.authors = this.authors.clone();
return r;
```
Calling `this.authors.clone()` on an `Author[]` array creates a **new array object**, but copies the **same `Author` object references** into the new array (a shallow copy of the array elements, not a deep clone of each `Author` object).
**2. Trace `Test.main()`:**
1. `r1.authors[0]` and `r2.authors[0]` both point to the **exact same `Author("Dr. Rao")` object**.
2. `authors2[0].name = "Dr. Mehta";` mutates that shared `Author` object's `name` to `"Dr. Mehta"`.
3. `r2.title = "Time Series Study";` reassigns `r2.title` (leaving `r1.title` as `"Regression Study"`).
4. Therefore:
- `r1` prints: **`Regression Study : Dr. Mehta`**
- `r2` prints: **`Time Series Study : Dr. Mehta`**
**Answer: D — `Regression Study : Dr. Mehta` followed by `Time Series Study : Dr. Mehta`**
A: **Incorrect:** `r2.title` was reassigned to `'Time Series Study'`, so the second line starts with `'Time Series Study'`, not `'Regression Study'`.
B: **Incorrect:** `r1.title` was not changed and remains `'Regression Study'`.
C: **Incorrect:** Because `this.authors.clone()` only clones the array of references and not the `Author` objects themselves, `r1.authors[0]` and `r2.authors[0]` refer to the same `Author` instance (`Dr. Mehta`).
D: **Correct:** `r1` and `r2` have independent `title` strings, but share the same `Author` object at index `0` (`Dr. Mehta`).
Question 18 MCQ · 4.0 marks
Consider the Java code given below.
What will the output be?
Published solution
**1. Understand `Stream.takeWhile(predicate)` and `Stream.dropWhile(predicate)`:**
Given `list = ["Drone", "Droid", "Arm", "Motor", "Driver"]` and predicate `s -> s.startsWith("D")`:
- **`takeWhile(s -> s.startsWith("D"))`:** Takes elements from the start of the stream **until the first element that fails the predicate** (`"Arm"`), and then stops immediately (ignoring `"Driver"` at the end). Thus it prints:
**`Drone Droid `**
- **`dropWhile(s -> s.startsWith("D"))`:** Drops elements from the start of the stream **until the first element that fails the predicate** (`"Arm"`), and then emits **all remaining elements** (including `"Driver"`). Thus it prints:
**`Arm Motor Driver `**
**Answer: C — `Drone Droid` on the first line and `Arm Motor Driver` on the second line**
A: **Incorrect:** Confuses `takeWhile`/`dropWhile` with `filter`: `takeWhile` stops permanently as soon as `'Arm'` fails the predicate.
B: **Incorrect:** `dropWhile` outputs all elements from `'Arm'` onward, including `'Driver'` at the end.
C: **Correct:** `takeWhile` takes the leading prefix `'Drone Droid'`, and `dropWhile` emits everything after that prefix (`'Arm Motor Driver'`).
D: **Incorrect:** `'Arm'` and `'Motor'` are not dropped by `dropWhile`.
Question 19 MSQ · 4.0 marks
From among the options, identify the appropriate function header(s) for function
that takes as input an array of
objects and prints the highest salary among them.
Choose the correct option(s).
Published solution
**1. Analyze the method call `printSalary(p)` where `p` is `Payable[]`:**
Inside `printSalary`, the method invokes `salary()` on elements of the array `p`, where `salary()` is declared in `abstract class Payable`.
**2. Evaluate each candidate method header:**
- **Option A (`public static void printSalary(<?> p)`):** Invalid Java syntax; wildcards `<?>` can only appear as type arguments of parameterized types (e.g., `List<?>`), not as a standalone type.
- **Option B (`public static void printSalary(T[] p)`):** Fails compilation because type parameter `<T>` is not declared before the return type `void`, and an unbounded `T` would not have a `.salary()` method.
- **Option C (`public static <T extends Payable> void printSalary(T[] p)`):** **Valid!** Declares a bounded generic type parameter `<T extends Payable>`, allowing `salary()` to be called on elements of `p`.
- **Option D (`public static void printSalary(Payable[] p)`):** **Valid!** Directly accepts a `Payable[]` array and calls `salary()` polymorphically.
**Answer: C, D**
A: **Incorrect:** `<?> p` is a syntax error in Java because wildcards cannot be used as raw parameter types.
B: **Incorrect:** `T` is undeclared (missing `<T extends Payable>` before `void`), and an unbounded `T` does not define `salary()`.
C: **Correct:** Declares bounded type parameter `<T extends Payable>`, accepting `Payable[]` and permitting calls to `.salary()`.
D: **Correct:** Accepts `Payable[]` directly, allowing polymorphic calls to `.salary()` on every element.
Question 20 MCQ · 6.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. Understand `ConcurrentHashMap` iterators:**
In `Test.main()`, `squareMap` is a `ConcurrentHashMap`. Unlike `HashMap` (whose iterators are fail-fast), iterators returned by `ConcurrentHashMap.entrySet().iterator()` are **weakly consistent**: they are thread-safe for concurrent modification and **never throw `ConcurrentModificationException`**.
**2. Check what happens when `SquareMapUpdater` runs concurrently:**
- Depending on thread scheduling, `t.run()` (`squareMap.put("4", "Sixteen")`) may execute before, during, or after the `main` thread iterates over `squareMap`, so ``4 => Sixteen` may or may not appear in the printed output (Options B, C, and D are all possible outputs).
- However, **Option A (`This program may generate ConcurrentModificationException`) is NOT true** because `ConcurrentHashMap` never throws `ConcurrentModificationException`.
**Answer: A — This program may generate `ConcurrentModificationException`.**
A: **Correct:** This statement is **NOT true** (and therefore should be selected) because `ConcurrentHashMap` uses weakly consistent iterators that never throw `ConcurrentModificationException`.
B: **Incorrect:** This output is possible if thread `t` inserts `"4" -> "Sixteen"` before the iterator finishes.
C: **Incorrect:** This output is also possible depending on hash bucket ordering and when thread `t` inserts `"4"`.
D: **Incorrect:** This output is possible if the `main` thread finishes iterating before thread `t` executes `put("4", "Sixteen")`.
Question 21 MCQ · 6.0 marks
Consider the Java code given below.
Choose the correct option to be filled in place of
such that the above program
produces the GUI given below.
Published solution
**1. Inspect the Swing `JFrame` layout and panel contents:**
- By default, a `JFrame` uses **`BorderLayout`**.
- `pnlLbl` contains `lblFrom` (`"From:"`) and `txtFrom`.
- `pnlTxt` contains `lblTo` (`"To:"`) and `txtTo`.
- `pnlBtn` contains `btn` (`"Book Ticket"`).
**2. Match the target GUI positions from top to bottom:**
- Top (`"North"`): `From: [ ]` \(\implies\) `add(pnlLbl, "North");`
- Middle (`"Center"`): `To: [ ]` \(\implies\) `add(pnlTxt, "Center");`
- Bottom (`"South"`): `[ Book Ticket ]` \(\implies\) `add(pnlBtn, "South");`
**Answer: C — `add(pnlLbl, "North"); add(pnlTxt, "Center"); add(pnlBtn, "South");`**
A: **Incorrect:** Places `pnlTxt` (`To:`) in `North` at the top and `pnlLbl` (`From:`) in `Center`.
B: **Incorrect:** Places `pnlBtn` (`Book Ticket`) in `Center` and `pnlTxt` (`To:`) at the bottom (`South`).
C: **Correct:** Places `pnlLbl` (`From:`) at the top (`North`), `pnlTxt` (`To:`) in the middle (`Center`), and `pnlBtn` (`Book Ticket`) at the bottom (`South`).
D: **Incorrect:** Places `pnlBtn` at the top (`North`) and `pnlLbl` at the bottom (`South`).
Question 22 MCQ · 5.0 marks
Consider the code given below.
What will the output be?
Published solution
**1. Analyze custom Java serialization (`writeObject` and `readObject`) and `transient` fields:**
In `class Satellite implements Serializable`:
- `orbitHeight` (`35786.0`) is a normal non-transient field \(\implies\) serialized by `out.defaultWriteObject()` and restored by `in.defaultReadObject()` as **`35786.0`**.
- `missionType` (`"COMMUNICATION"`) is declared **`transient`** and is not manually written in `writeObject` \(\implies\) deserialized to its default reference value **`null`**.
- `satelliteId` (`42`) is declared **`transient`**, so `defaultWriteObject()` skips it, **but** custom `writeObject` executes:
`out.writeInt(satelliteId * 10);` \(\implies\) writes \(42 \times 10 = 420\).
Then custom `readObject` executes:
`satelliteId = in.readInt() / 10;` \(\implies\) restores \(420 / 10 = 42\).
**2. Conclude the output of `System.out.println(obj)`:**
`orbitHeight=35786.0, missionType=null, satelliteId=42`
**Answer: C — `orbitHeight=35786.0, missionType=null, satelliteId=42`**
A: **Incorrect:** `satelliteId` is manually written and restored by the custom `writeObject` and `readObject` methods, so it does not remain `0`.
B: **Incorrect:** `orbitHeight` is non-transient (`35786.0`), and `missionType` is `transient` (so it becomes `null`, not `COMMUNICATION`).
C: **Correct:** `orbitHeight` is restored by default serialization (`35786.0`), `transient missionType` deserializes as `null`, and `satelliteId` is restored by the custom `writeObject`/`readObject` methods.
D: **Incorrect:** `missionType` is `transient` and becomes `null` upon deserialization.
Question 23 MCQ · 5.0 marks
Method
returns an
that describes the specific
value, if non-null; otherwise returns an
.
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 terminates due to
after printing the
message:
This program generates the output:
This program generates the output:
Published solution
**1. Trace `Optional.ofNullable()` and `ifPresent()` in `Test.main()`:**
- `TransportService` initializes `drivers` with `"RouteA" -> "Suresh"` and `"RouteB" -> "Mahesh"`.
- `d1 = Optional.ofNullable(new TransportService().getDriver("RouteA"))`: Since `getDriver("RouteA")` returns `"Suresh"` (non-null), `d1` is `Optional.of("Suresh")`.
- `d2 = Optional.ofNullable(new TransportService().getDriver("RouteC"))`: Since `"RouteC"` is not in the map, `getDriver("RouteC")` returns `null`, and `Optional.ofNullable(null)` safely returns `Optional.empty()`.
**2. Trace the `ifPresent` calls:**
- `d1.ifPresent(n -> System.out.println(n.toUpperCase()))` executes the lambda and prints **`SURESH`**.
- `d2.ifPresent(...)` does nothing because `d2` is empty.
**Answer: A — `SURESH`**
A: **Correct:** `d1` contains `'Suresh'` (printing `SURESH`), while `d2` is `Optional.empty()` so `d2.ifPresent(...)` is a no-op.
B: **Incorrect:** `Optional.ofNullable(null)` returns `Optional.empty()` rather than throwing a `NullPointerException`.
C: **Incorrect:** `d2.ifPresent(...)` does not execute its lambda when `d2` is empty, so `null` is not printed.
D: **Incorrect:** `getDriver("RouteA")` returns the driver name `"Suresh"`, not the key `"RouteA"`.
Question 24 MSQ · 6.0 marks
Consider the following code which has 4 user-defined threads, two threads would work as stock
adders to a warehouse (object) and the other two work as stock removers from the same
warehouse.
Choose all the options that would NEVER occur as a result of execution of this code.
It may generate the output as:
It may generate the output as:
It may generate the output as:
It may generate the output as:
Published solution
**1. Analyze the `synchronized` methods in `Warehouse`:**
- `stock` starts at `0`.
- Two adder threads (`t1`, `t3`) each call `wh.add(1000)`, which adds `1000` to `stock` and prints `"After adding, stock = " + stock`.
- Two remover threads (`t2`, `t4`) each call `wh.remove(500)`, which checks **`if (stock > amount)`** (i.e., `if (stock > 500)`). Notice two critical facts:
1. If `stock <= 500` when a remover runs, the `if` condition is **false**, so `stock` is **not** decremented and **nothing is printed**!
2. Because `stock` starts at `0` and `remove(500)` only executes when `stock > 500`, `stock` can **never** become negative (`-500` or `-1000`), and if `stock == 1000` gets decremented to `500`, a second `remove(500)` cannot decrement `500` (since `500 > 500` is false)!
**2. Identify which outputs can NEVER occur:**
- **Option A (`1000 -> 500 -> 1000 -> 500`):** Impossible! If `stock` is `500` after the first remove, adding `1000` makes `stock = 1500` (not `1000`), and after removing `500` again `stock` becomes `1000` (not `500`).
- **Option B (`-500 -> -1000 -> 0 -> 1000`):** Impossible! `remove(500)` checks `if (stock > 500)`, so `stock` can never become negative.
- **Options C and D:** Both `1000 -> 2000 -> 1500 -> 1000` (C) and `1000 -> 500 -> 1500 -> 1000` (D) are completely valid thread interleavings.
**Answer: A, B**
A: **Correct:** This output can **NEVER** occur because `500 + 1000` is `1500`, not `1000`.
B: **Correct:** This output can **NEVER** occur because `if (stock > amount)` prevents `remove(500)` from ever making `stock` negative.
C: **Incorrect:** This output **can** occur when `t1` and `t3` run first (`1000`, `2000`) followed by `t2` and `t4` (`1500`, `1000`).
D: **Incorrect:** This output **can** occur when `t1` runs (`1000`), then `t2` (`500`), then `t3` (`1500`), then `t4` (`1000`).