MauryaHub PYQ Practice

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

Question 2 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
What will the output be?
6406536934604.Source diagram or notation
6406536934605.Source diagram or notation
6406536934606.Source diagram or notation
6406536934607.Source diagram or notation

Published solution

**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()`.

Report a correction for Q2

Question 3 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
What will the output be?
6406536934612.
This program generates the output:
Source diagram or notation
6406536934613.
This program generates the output:
Source diagram or notation
6406536934614.
This program generates the output:
Source diagram or notation
6406536934615.
This program generates the output:
Source diagram or notation

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.

Report a correction for Q3

Question 4 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
Source diagram or notation
Identify the appropriate statement to fill in the blank at
Source diagram or notation
, such that the output is:
Source diagram or notation
6406536934616.Source diagram or notation
6406536934617.Source diagram or notation
6406536934618.Source diagram or notation
6406536934619.Source diagram or notation

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.

Report a correction for Q4

Question 5 MCQ · 4.0 marks

Consider the following block of code.
Source diagram or notation
Which among the following code blocks can replace the given code in order to generate a customized assertion error as shown below?
Source diagram or notation
6406536934620.Source diagram or notation
6406536934621.Source diagram or notation
6406536934622.Source diagram or notation
6406536934623.Source diagram or notation

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.

Report a correction for Q5

Question 6 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
Choose the correct option.
6406536934624.
It generates the output:
Source diagram or notation
6406536934625.
Compilation fails because
Source diagram or notation
and
Source diagram or notation
cannot be converted to
Source diagram or notation
6406536934626.
Compilation fails because
Source diagram or notation
method has not been defined in classes
Source diagram or notation
and
Source diagram or notation
6406536934627.
It generates the output:
Source diagram or notation

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.

Report a correction for Q6

Question 7 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
Choose the correct option to fill in place of
Source diagram or notation
so that the output is:
Source diagram or notation
6406536934628.Source diagram or notation
6406536934629.Source diagram or notation
6406536934630.Source diagram or notation
6406536934631.Source diagram or notation

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`.

Report a correction for Q7

Question 8 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
Choose the correct option.
6406536934632.
This program generates the output:
Source diagram or notation
6406536934633.
This program generates the output:
Source diagram or notation
6406536934634.
This program generates the output:
Source diagram or notation
6406536934635.
This program generates the output:
Source diagram or notation

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`.

Report a correction for Q8

Question 9 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
Choose the correct option to fill in the blank at
Source diagram or notation
such that the program generates the following output.
Source diagram or notation
6406536934640.Source diagram or notation
6406536934641.Source diagram or notation
6406536934642.Source diagram or notation
6406536934643.
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.

Report a correction for Q9

Question 10 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
Choose the correct option.
6406536934644.
This program generates the output:
Source diagram or notation
6406536934645.
This program generates the output:
Source diagram or notation
6406536934646.
This program generates the output:
Source diagram or notation
6406536934647.
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.

Report a correction for Q10

Question 11 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
Choose the correct option.
6406536934648.
It generates the output:
Source diagram or notation
6406536934649.
It generates the output:
Source diagram or notation
6406536934650.
It generates the output:
Source diagram or notation
6406536934651.
It generates the output:
Source diagram or notation

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`).

Report a correction for Q11

Question 12 MCQ · 4.0 marks

Consider the Java code given below. Suppose the file
Source diagram or notation
is written successfully by the program.
Source diagram or notation
What will the output be?
6406536934652.Source diagram or notation
6406536934653.Source diagram or notation
6406536934654.Source diagram or notation
6406536934655.Source diagram or notation

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.

Report a correction for Q12

Question 13 MCQ · 4.0 marks

Consider the code given below that checks whether two normal distributions are identical. Method
Source diagram or notation
is overridden to compare two
Source diagram or notation
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.
Source diagram or notation
Choose the correct option to fill in place of
Source diagram or notation
so that the output is:
Source diagram or notation
6406536934664.Source diagram or notation
6406536934665.Source diagram or notation
6406536934666.Source diagram or notation
6406536934667.Source diagram or notation

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`.

Report a correction for Q13

Question 14 MCQ · 4.0 marks

Consider the following Java code that uses chained exceptions.
Source diagram or notation
What can be the output of this code?
6406536934668.Source diagram or notation
6406536934669.Source diagram or notation
6406536934670.Source diagram or notation
6406536934671.Source diagram or notation

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()`.

Report a correction for Q14

Question 15 MCQ · 4.0 marks

Method
Source diagram or notation
returns an infinite sequential ordered
Source diagram or notation
produced by iterative application of a function
Source diagram or notation
to an initial element
Source diagram or notation
, producing a
Source diagram or notation
consisting of
Source diagram or notation
,
Source diagram or notation
,
Source diagram or notation
, etc. Based on the above information, consider the code given below, and answer the question that follows.
Source diagram or notation
What will the output be?
6406536934672.Source diagram or notation
6406536934673.Source diagram or notation
6406536934674.Source diagram or notation
6406536934675.Source diagram or notation

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.

Report a correction for Q15

Question 16 MCQ · 4.0 marks

Consider the code given below.
Source diagram or notation
Choose the correct option.
6406536934676.
The code always prints 2000.
6406536934677.
The code prints any number in the range 1000 to 2000
6406536934678.
The code prints any number in the range 0 to 1000
6406536934679.
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.

Report a correction for Q16

Question 17 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
What will the output be?
6406536934680.Source diagram or notation
6406536934681.Source diagram or notation
6406536934682.Source diagram or notation
6406536934683.Source diagram or notation

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`).

Report a correction for Q17

Question 18 MCQ · 4.0 marks

Consider the Java code given below.
Source diagram or notation
What will the output be?
6406536934684.Source diagram or notation
6406536934685.Source diagram or notation
6406536934686.Source diagram or notation
6406536934687.Source diagram or notation

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`.

Report a correction for Q18

Question 19 MSQ · 4.0 marks

From among the options, identify the appropriate function header(s) for function
Source diagram or notation
that takes as input an array of
Source diagram or notation
objects and prints the highest salary among them.
Source diagram or notation
Choose the correct option(s).
6406536934608.Source diagram or notation
6406536934609.Source diagram or notation
6406536934610.Source diagram or notation
6406536934611.Source diagram or notation

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.

Report a correction for Q19

Question 20 MCQ · 6.0 marks

Consider the Java code given below.
Source diagram or notation
Which of the following is NOT true about the given code?
6406536934636.
This program may generate
Source diagram or notation
.
6406536934637.
The program may generate the output:
Source diagram or notation
6406536934638.
The program may generate the output:
Source diagram or notation
6406536934639.
The program may generate the output:
Source diagram or notation

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")`.

Report a correction for Q20

Question 21 MCQ · 6.0 marks

Consider the Java code given below.
Source diagram or notation
Choose the correct option to be filled in place of
Source diagram or notation
such that the above program produces the GUI given below.
Source diagram or notation
6406536934692.Source diagram or notation
6406536934693.Source diagram or notation
6406536934694.Source diagram or notation
6406536934695.Source diagram or notation

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`).

Report a correction for Q21

Question 22 MCQ · 5.0 marks

Consider the code given below.
Source diagram or notation
What will the output be?
6406536934656.Source diagram or notation
6406536934657.Source diagram or notation
6406536934658.Source diagram or notation
6406536934659.Source diagram or notation

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.

Report a correction for Q22

Question 23 MCQ · 5.0 marks

Method
Source diagram or notation
returns an
Source diagram or notation
that describes the specific value, if non-null; otherwise returns an
Source diagram or notation
. Based on this description, consider the code given below, and answer the question that follows.
Source diagram or notation
Choose the correct option.
6406536934688.
This program generates the output:
Source diagram or notation
6406536934689.
This program terminates due to
Source diagram or notation
after printing the message:
Source diagram or notation
6406536934690.
This program generates the output:
Source diagram or notation
6406536934691.
This program generates the output:
Source diagram or notation

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"`.

Report a correction for Q23

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.
Source diagram or notation
Source diagram or notation
Choose all the options that would NEVER occur as a result of execution of this code.
6406536934660.
It may generate the output as:
Source diagram or notation
6406536934661.
It may generate the output as:
Source diagram or notation
6406536934662.
It may generate the output as:
Source diagram or notation
6406536934663.
It may generate the output as:
Source diagram or notation

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`).

Report a correction for Q24