Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.
17 / 17 published solutions
Question 80 NAT · 2.0 marks
If the unit-norm eigenvector corresponding to the largest eigenvalue of
is
, find
.
Published solution
**1. Center the five observations:** The points are \((-2,-2),(-1,-1),(0,0),(1,1),(2,2)\). Their mean is \((0,0)\), so they are already centered.
**2. Compute the population covariance:** Each diagonal entry and the cross-covariance equal \((4+1+0+1+4)/5=2\). Thus \[C=\begin{pmatrix}2&2\\2&2\end{pmatrix}.\]
**3. Find the principal eigenpair:** The unit vector \(v=(1,1)^T/\sqrt2\) has eigenvalue 4; the perpendicular direction has eigenvalue 0. Either sign of v is valid.
**4. Evaluate the quadratic form:** Since \(Cv=4v\) and \(v^Tv=1\), \(v^TCv=4v^Tv=4\).
**Answer: 4.**
**Convention note:** The shared dataset is supplied in the MLF passage of this bundle; covariance is normalized by n=5.
**Java**
**Section Id :** 640653122505
**Section Number :** 6
**Section type :** Online
**Mandatory or Optional :** Mandatory
**Number of Questions :** 16
**Number of Questions to be attempted :** 16
**Section Marks :** 100
**Display Number Panel :** Yes
**Section Negative Marks :** 0
**Group All Questions :** No
**Enable Mark as Answered Mark for Review and**
No
**Clear Response :**
**Section Maximum Duration :** 0
**Section Minimum Duration :** 0
**Section Time In :** Minutes
**Maximum Instruction Time :** 0
Published solution
**1. Center the five observations:** The points are \((-2,-2),(-1,-1),(0,0),(1,1),(2,2)\). Their mean is \((0,0)\), so they are already centered.
**2. Compute the population covariance:** Each diagonal entry and the cross-covariance equal \((4+1+0+1+4)/5=2\). Thus \[C=\begin{pmatrix}2&2\\2&2\end{pmatrix}.\]
**3. Recompute after adding the two points:** Adding \((100,100)\) and \((-100,-100)\) leaves the mean zero. All seven points remain on the same line, and \(C^\prime=\tfrac{20010}{7}\begin{pmatrix}1&1\\1&1\end{pmatrix}\).
**4. Compare principal directions:** Both covariance matrices have the same unique leading eigenspace, the span of \((1,1)^T\). A unit vector in this one-dimensional space can have either sign, so \(v^\prime=v\) or \(v^\prime=-v\). The magnitude of the variance changes, but the principal axis does not.
**Answer: A — \(v^\prime=v\) or \(v^\prime=-v\).**
**Convention note:** The dataset needed for this question is present in the shared MLF passage in this bundle. Eigenvector sign has no effect on the PCA axis.
A: **Correct:** Both vectors lie on the same one-dimensional principal axis, with arbitrary sign.
B: **Incorrect:** The perpendicular axis has zero variance, so it cannot become the leading direction.
C: **Incorrect:** The principal axes coincide; a 45-degree angle is impossible.
D: **Incorrect:** The exact line containing every point determines the leading eigenspace.
**1. Choose selection rather than transformation:** filter keeps Student objects satisfying a Boolean predicate, whereas map replaces each Student with the predicate’s Boolean result. To print names afterward, the stream must still contain Students.
**2. Apply both inclusive boundaries:** Anu (85.5), Hari (78.0) and David (70.0) satisfy grade>=70.0 and grade<=90.0. Bindu (92.0) exceeds the upper bound and Hasan (65.0) fails the lower bound. David remains because 70 is included.
**3. Compare the valid pipelines:** One combined filter and two consecutive filters impose the same conjunction. Both preserve list order and print Anu, Hari and David on separate lines.
**Answer: B, C — the combined filter or the two successive filters; output Anu, Hari, David.**
A: **Incorrect:** map changes the stream element type to Boolean, so the subsequent access to s.name does not compile.
B: **Correct:** A combined filter retains precisely the Students within the inclusive range.
C: **Correct:** The two filters successively enforce the lower and upper bounds while retaining Student objects.
D: **Incorrect:** The map step produces Boolean elements, whose type has no name field.
Consider the code given below.
interface Vehicle {
public abstract double getFuelEfficiency();
}
class Car implements Vehicle, Cloneable {
protected double fuelCapacity;
protected double mileage;
public Car(double fuel, double m) {
fuelCapacity = fuel;
mileage = m;
}
public double getFuelEfficiency() {
return fuelCapacity * mileage;
}
public Car clone() throws CloneNotSupportedException {
return (Car) super.clone();
}
}
class ElectricCar extends Car {
public ElectricCar(double batteryCapacity, double mileage) {
super(batteryCapacity, mileage);
}
public ElectricCar clone() throws CloneNotSupportedException {
return (ElectricCar) super.clone();
}
}
public class VehicleTest {
public static void main(String[] args) {
try {
ElectricCar e1 = new ElectricCar(50, 2);
ElectricCar e2 = e1.clone();
e1.fuelCapacity = 100;
System.out.print(e1.getFuelEfficiency() + e2.getFuelEfficiency());
} catch (CloneNotSupportedException e) {
System.out.println("Cloning not supported");
}
}
}
What will the output be?
6406535937287.
200.0
6406535937288.
300.0
6406535937289.
400.0
6406535937290.
Cloning not supported
Published solution
**1. Trace the clone chain:** ElectricCar.clone calls Car.clone, which delegates to Object.clone. Car implements Cloneable, and the runtime object is an ElectricCar, so the clone also has runtime type ElectricCar and both casts succeed.
**2. Separate the two objects:** Object.clone copies the primitive double fields. Immediately after cloning, both objects have fuelCapacity=50 and mileage=2. Updating e1.fuelCapacity to 100 changes only e1; e2 retains 50.
**3. Calculate the printed sum:** The method returns fuelCapacity multiplied by mileage. Thus e1 returns \(100\cdot2=200\) and e2 returns \(50\cdot2=100\). Their double-valued sum prints as 300.0.
**Answer: B — 300.0.**
A: **Incorrect:** This omits the cloned object’s contribution or assumes the update did not occur.
B: **Correct:** The two efficiencies are 200.0 and 100.0.
C: **Incorrect:** The primitive field change in e1 does not also change e2.
D: **Incorrect:** Cloneable is implemented, so this cloning operation is supported.
while (!s.isEmpty()) {
if (s.pop().equals(d.peek())) {
return false;
}
}
6406535937292.
while (!s.isEmpty()) {
if (s.pop().equals(d.poll())) {
return false;
}
}
6406535937293.
while (!s.isEmpty()) {
if (!s.pop().equals(d.poll())) {
return false;
}
}
6406535937294.
while (!s.isEmpty()) {
if (!s.pop().equals(d.peek())) {
return false;
}
}
Published solution
**1. Compare the string in opposite directions:** Pushing each character onto the stack makes pop return characters from right to left. Adding characters to the deque’s tail makes poll remove them from left to right. Corresponding results must match for a palindrome.
**2. Return false only on a mismatch:** Use !s.pop().equals(d.poll()). Both operations advance their structures. If the stack empties without a mismatch, the existing final return true correctly accepts the string.
**3. Dry-run both inputs:** For level, the compared pairs are (l,l),(e,e),(v,v),(e,e),(l,l), so it returns true. For hello, the first pair is (o,h), so it immediately returns false.
**Answer: C — use !s.pop().equals(d.poll()) as the mismatch condition.**
A: **Incorrect:** This rejects equal characters, so it incorrectly rejects level at its first pair; peek also fails to advance the deque.
B: **Incorrect:** This advances both structures but reverses the logic by returning false on a match.
C: **Correct:** It consumes opposite-end characters and rejects exactly when they differ.
D: **Incorrect:** peek keeps comparing every popped character with the same first character; level fails at its second comparison.
**1. Filter by length:** The list is apple, banana, pear, kiwi, plum. The condition length()>4 retains apple (5) and banana (6), excluding the three four-letter words.
**2. Transform and skip:** map(toUpperCase) produces APPLE,BANANA. skip(1) removes the first surviving element APPLE, leaving BANANA. The skip is applied after filtering, not to the original unfiltered list.
**3. Execute the terminal operation:** forEach prints the remaining one element on its own line: BANANA.
**Answer: B — BANANA.**
A: **Incorrect:** This is the stream before skip(1) removes APPLE.
B: **Correct:** BANANA is the only element remaining after filtering, mapping and skipping.
C: **Incorrect:** APPLE is precisely the element removed by skip(1).
D: **Incorrect:** KIWI and PLUM fail the strict length()>4 condition.
public class MathUtils {
public Object getFirst(Object[] arr) {
// Returns the first element of the array
}
public double sum(Object[] arr) {
// Returns the sum of all elements in the array
}
}
6406535937300.
public class MathUtils {
public Object getFirst(Object[] arr) {
// Returns the first element of the array
}
public double sum(Number[] arr) {
// Returns the sum of all elements in the array
}
}
6406535937301.
public class MathUtils {
public T getFirst(T[] arr) {
// Returns the first element of the array
}
public double sum(T[] arr) {
// Returns the sum of all elements in the array
}
}
6406535937302.
public class MathUtils {
public Object getFirst(Object[] arr) {
// Returns the first element of the array
}
public double sum(Double[] arr) {
// Returns the sum of all elements in the array
}
}
Published solution
**1. Erase the unbounded type parameter:** In <T> T getFirst(T[] arr), the implicit bound of T is Object. Erasure therefore gives Object getFirst(Object[] arr).
**2. Erase the bounded parameter separately:** In <T extends Number> double sum(T[] arr), T erases to its bound Number, making the parameter Number[]. The primitive return type double does not change.
**3. Match both erased signatures:** Option B has Object getFirst(Object[]) and double sum(Number[]). The two method-local type parameters are independent and must each be erased according to its own bound.
**Answer: B — Object getFirst(Object[]) and double sum(Number[]).**
**Convention note:** The comments stand for method bodies. Concrete implementations need actual return statements; the question is comparing signatures after erasure, not claiming the comment-only class is executable.
A: **Incorrect:** The sum parameter erases to Number[], not Object[], because T has a Number bound.
B: **Correct:** Both method signatures have the correct erased types.
C: **Incorrect:** Erasure removes the type parameters; the undeclared T shown here cannot remain.
D: **Incorrect:** A Number bound does not narrow to the particular subclass Double.
Consider the Java code given below.
interface Discount{
public void apply(int price);
}
class ShoppingCart{
public Discount getDiscount(String type){
Discount d = null;
if(type == "festival")
d = new FestivalDiscount();
return d;
}
private class FestivalDiscount implements Discount{
public void apply(int price){
System.out.println("Final Price: " + (price - 100));
}
}
}
public class CartTest {
public static void main(String[] args) {
// CODE SEGMENT //
disc.apply(500);
}
}
Choose the correct option to fill in at CODE SEGMENT such that the output is:
Final Price: 400
6406535937303.
FestivalDiscount disc = new ShoppingCart().getDiscount("festival");
6406535937304.
Discount disc = new ShoppingCart().getDiscount("festival");
6406535937305.
ShoppingCart sc = new ShoppingCart();
FestivalDiscount disc = sc.getDiscount("festival");
6406535937306.
No line/s of code at CODE SEGMENT can generate the given output because
FestivalDiscount is a private inner class.
Published solution
**1. Use the accessible return type:** getDiscount is public and returns the Discount interface. Although its implementation class FestivalDiscount is private, outside code can store and invoke the returned object through Discount.
**2. Follow the factory call:** new ShoppingCart().getDiscount("festival") selects the private implementation and returns it as Discount. Thus the correct declaration is Discount disc = new ShoppingCart().getDiscount("festival");.
**3. Invoke through the interface:** disc.apply(500) dynamically dispatches to FestivalDiscount.apply, which subtracts 100 and prints Final Price: 400.
**Answer: B — Discount disc = new ShoppingCart().getDiscount("festival");.**
**Convention note:** The source compares strings with ==. In this exact program both occurrences are the same interned literal, so the branch is taken. For general string inputs, use "festival".equals(type) to compare contents; an unequal reference could otherwise leave d null.
A: **Incorrect:** FestivalDiscount is a private inner type and cannot be named as this unqualified external variable type.
B: **Correct:** The accessible interface type matches the factory’s return type and exposes apply.
C: **Incorrect:** Creating a separate cart variable does not make its private inner class accessible.
D: **Incorrect:** Private implementation classes can be used through an accessible interface returned by a public method.
Consider two Java files located in two different packages as shown below.
Account.java:
package com.bank;
public class Account {
int accountNumber = 1001;
private double balance = 5000.0;
protected void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
public void displayBalance() {
System.out.println("Balance: " + balance);
}
}
SavingsAccount.java:
package com.customer;
import com.bank.Account;
public class SavingsAccount extends Account {
public static void main(String[] args) {
SavingsAccount sa = new SavingsAccount();
System.out.println(sa.accountNumber); // LINE 1
System.out.println(sa.balance); // LINE 2
sa.deposit(1000); // LINE 3
sa.displayBalance(); // LINE 4
}
}
Choose the correct option.
6406535937307.
LINE 1 and LINE 2 generate compilation errors.
6406535937308.
LINE 2 generates a compilation error, while others compile fine.
6406535937309.
LINE 1, LINE 2, and LINE 3 generate compilation errors.
6406535937310.
Only LINE 3 generates a compilation error.
Published solution
**1. Check the two fields across packages:** accountNumber has no access modifier, so it is package-private and inaccessible from com.customer. balance is private to Account and is inaccessible directly even from its subclass. Thus LINE 1 and LINE 2 fail compilation.
**2. Check protected access through the subclass receiver:** LINE 3 occurs inside SavingsAccount and uses a SavingsAccount reference sa. This satisfies Java’s cross-package protected-member rule, so the inherited deposit method is accessible. A static main method may still call an instance method through an object reference.
**3. Check public access:** displayBalance is public and therefore accessible at LINE 4. The correct set of failing lines is exactly 1 and 2.
**Answer: A — LINE 1 and LINE 2 generate compilation errors.**
A: **Correct:** Both nonpublic fields are inaccessible under their respective access rules, while the method calls are legal.
B: **Incorrect:** LINE 1 is also inaccessible because the two classes are in different packages.
C: **Incorrect:** LINE 3 is legal from the subclass through a SavingsAccount receiver.
D: **Incorrect:** LINE 3 is legal, and both field-access lines fail.
Consider the Java code given below.
interface Shape {
void draw();
}
class ShapeFactory {
private String type;
public void setType(String t) {
type = t;
}
public String getType() {
return type;
}
public Shape createShape() {
switch (getType()) {
case "Circle":
return new Circle();
case "Square":
return new Square();
case "Triangle":
return new Triangle();
default:
return null;
}
}
private class Circle implements Shape {
public void draw() {
System.out.println("Drawing Circle");
}
}
private class Square implements Shape {
public void draw() {
System.out.println("Drawing Square");
}
}
private class Triangle implements Shape {
public void draw() {
System.out.println("Drawing Triangle");
}
}
}
public class ShapeDemo {
public static void main(String[] args) {
ShapeFactory sf = new ShapeFactory();
sf.setType("Square");
// --------- LINE 1 ---------
}
}
Identify the appropriate option(s) to fill in place of LINE 1 such that the output is:
Drawing Square
6406535937311.
Shape s = sf.createShape();
s.draw();
6406535937312.
sf.draw();
6406535937313.
sf.createShape().draw();
6406535937314.
Shape s = sf;
s.draw();
Published solution
**1. Trace the factory’s state:** sf.setType("Square") makes createShape take its Square branch, instantiate the private Square class and return that instance as Shape.
**2. Invoke through the returned Shape:** Either assign the result to Shape s and then call s.draw(), or immediately call sf.createShape().draw(). Both dispatch to Square.draw and print Drawing Square.
**3. Distinguish factory from product:** sf is a ShapeFactory object, not a Shape. It neither implements Shape nor defines draw, so calling sf.draw() or assigning sf directly to Shape is invalid.
**Answer: A, C — assign the returned Shape and call draw, or call sf.createShape().draw().**
A: **Correct:** The return type Shape is accessible and its draw method dispatches to the private Square implementation.
B: **Incorrect:** ShapeFactory has no draw method.
C: **Correct:** The method chain invokes draw on the Shape returned by createShape.
D: **Incorrect:** ShapeFactory does not implement Shape and cannot be assigned directly to a Shape variable.
LINE 1 generates a compilation error due to duplicate keys.
6406535937316.
The program generates the output:
{Alpha=88, Beta=76, Delta=70, Gamma=85}
6406535937317.
The program generates the output:
{Alpha=88, Beta=80, Delta=70, Gamma=92}
6406535937318.
The program generates the output:
{Alpha=88, Beta=156, Delta=70, Gamma=177}
Published solution
**1. Copy projectA into combined:** The initial combined map is Alpha=88, Beta=76, Gamma=92. Map.put does not reject a repeated key; maps hold a single value per key.
**2. Apply the merge function:** For Beta, merge chooses \(\min(76,80)=76\). For Gamma, it chooses \(\min(92,85)=85\). Delta is absent, so it is inserted as 70 without invoking the remapping function.
**3. Use TreeMap ordering:** The keys print in natural alphabetical order: Alpha, Beta, Delta, Gamma. The exact map output is {Alpha=88, Beta=76, Delta=70, Gamma=85}.
**Answer: B — {Alpha=88, Beta=76, Delta=70, Gamma=85}.**
A: **Incorrect:** put is valid and handles existing keys by replacement; this code has no duplicate-key compilation error.
B: **Correct:** These are the minimum values for repeated keys, printed in sorted key order.
C: **Incorrect:** This retains the maxima, contrary to Math.min in the remapping function.
D: **Incorrect:** These are sums, but the code uses Math.min rather than addition.
Consider the Java code given below that prints the average rating of a set of Rateable objects. From
among the options, identify the appropriate function header for the function printAverageRating that
takes as input an array of Rateable objects and prints the average rating.
import java.util.*;
interface Rateable {
public abstract double getRating();
}
class Product implements Rateable {
private double rating;
// Constructor
// method getRating() that returns rating of Product
}
public class Test {
// LINE 1: FUNCTION HEADER
{
// invokes method getRating()
// to compute and print the average rating
}
public static void main(String[] args) {
Rateable[] products = {new Product(4.5), new Product(3.8),
new Product(5.0)};
printAverageRating(products);
}
}
Choose the correct option(s).
**1. Start from the argument’s declared type:** products is a Rateable[] even though its individual elements are Product objects. Method applicability is checked using that declared array type.
**2. Check the two suitable headers:** static <T extends Rateable> void printAverageRating(T[] items) can infer T as Rateable and permits getRating calls. static void printAverageRating(Rateable[] items) also directly accepts the supplied argument and exposes the required interface method.
**3. Check the rejected declarations:** A bare <?> is not a legal parameter type. A bound T extends Product restricts its argument to Product arrays or subtype arrays, so the declared Rateable[] cannot be passed to it.
**4. Verify the intended computation:** The sum of ratings is \(4.5+3.8+5.0=13.3\), and dividing by 3 gives approximately 4.4333. Both valid headers support a body that iterates over the array and computes this average.
**Answer: B, D — the generic T extends Rateable header and the direct Rateable[] header.**
**Convention note:** The commented constructor, getRating implementation and averaging body are intentional placeholders in the source; the choices concern which headers support the stated completed program.
A: **Incorrect:** A wildcard cannot stand alone as the parameter type; it belongs inside an appropriate generic type argument.
B: **Correct:** The bound gives each element a getRating method, and T=Rateable accepts the declared argument.
C: **Incorrect:** Rateable[] is not a Product[]; generic inference cannot satisfy both this argument and the narrower Product bound.
D: **Correct:** The parameter exactly matches the declared Rateable[] argument and supports getRating.
**1. Apply the required predicate to every element:** The marks are Amit=85, Neha=42, Raj=90 and Pooja=35. Filtering by getMarks()>=50 retains Amit and Raj in their original encounter order.
**2. Compare lambda parameter syntax:** In a stream of Students, s -> ... infers s as Student. Writing (Student s) -> ... explicitly specifies the same type, so both versions are valid and yield the requested output.
**3. Distinguish filter from takeWhile:** filter tests each Student independently. takeWhile stops at the first failing element, Neha, so it yields only Amit and never reaches Raj. Comparing the Student object itself with integer 50 is a type error.
**Answer: A, C — the inferred or explicitly typed filter; output Amit : 85 and Raj : 90.**
A: **Correct:** The inferred Student parameter is used to test its numeric marks.
B: **Incorrect:** The >= operator cannot compare a Student reference with the integer 50.
C: **Correct:** The explicit Student parameter type is valid and gives the same predicate.
D: **Incorrect:** takeWhile stops at Neha and omits the later passing student Raj.
Consider the Java code given below.
class Student {
private int marks;
public Student(int marks){
assert marks >= 0 && marks <= 100 : "bad marks"; // assert-1
this.marks = marks;
}
}
class LoanApplication {
private double loanAmount;
public LoanApplication(double loanAmount){
assert loanAmount > 0 : "bad loan"; // assert-2
this.loanAmount = loanAmount;
}
}
class Product {
private int quantity;
public Product(int quantity){
assert quantity >= 0 : "bad qty"; // assert-3
this.quantity = quantity;
}
}
public class FClass {
public static void main(String[] args){
LoanApplication l = new LoanApplication(-50000);
Product p = new Product(10);
Student s = new Student(105);
}
}
Identify the assert statement that throws the AssertionError when the class is executed as:
java -ea:Student -da:LoanApplication FClass
6406535937327.
assert-1
6406535937328.
assert-2
6406535937329.
assert-3
6406535937330.
None of these
Published solution
**1. Read the class-specific switches:** -ea:Student enables assertions in Student. -da:LoanApplication disables them in LoanApplication. Assertions in other ordinary application classes remain disabled by default because there is no global -ea.
**2. Follow constructor order:** LoanApplication(-50000) first executes with its assertion disabled, so the negative amount does not throw AssertionError. Product(10) also completes; its condition would be true even if assertions were enabled.
**3. Evaluate the enabled assertion:** Student(105) checks marks>=0 && marks<=100. The upper-bound test fails, so assert-1 throws AssertionError with the detail message bad marks.
**Answer: A — assert-1.**
A: **Correct:** Only this enabled assertion has a false condition.
B: **Incorrect:** This assertion is explicitly disabled for LoanApplication.
C: **Incorrect:** This assertion is not enabled, and quantity 10 also satisfies its condition.
D: **Incorrect:** The Student assertion is enabled and fails for 105.
map1 will print entries in the order in which they were inserted.
map2 will print entries in sorted order of keys.
6406535937332.
map1 will print entries in unspecified order.
map2 will print entries in sorted order of keys.
6406535937333.
map1 will print entries in sorted order of keys.
map2 will print entries in insertion order.
6406535937334.
Both map1 and map2 will print entries in unspecified order.
Published solution
**1. Identify the first map’s contract:** map1 is a HashMap. It does not guarantee insertion order or sorted key order. A particular execution may happen to look sorted for these small integer keys, but that is not the API’s ordering guarantee.
**2. Identify the second map’s contract:** map2 is a TreeMap populated from map1. It orders Integer keys naturally, so its entries print as 1->Apple, 2->Cherry, 3->Banana, 4->Date, regardless of the order in which they were copied.
**3. Match the promised behavior:** The correct description is unspecified iteration order for map1 and sorted key order for map2.
**Answer: B — map1 unspecified order; map2 sorted key order.**
A: **Incorrect:** HashMap does not promise the insertion order 3,1,4,2.
B: **Correct:** HashMap has unspecified order; TreeMap sorts these integer keys increasingly.
C: **Incorrect:** HashMap does not guarantee sorted order, and TreeMap is not insertion-ordered.
D: **Incorrect:** TreeMap does specify sorted order, so the second claim is false.
Consider the Java code given below.
interface Chargeable {
void showChargeStatus();
}
class Laptop implements Chargeable {
public void showChargeStatus() {
System.out.println("Laptop is charging");
}
}
class Mobile implements Chargeable {
public void showChargeStatus() {
System.out.println("Mobile is charging");
}
}
class DeviceList {
private Object[] devices = {new Laptop(), new Mobile()};
public void testDevices() {
for (int i = 0; i < devices.length; i++) {
//LINE-1
}
}
}
public class TestDevices {
public static void main(String[] args) {
DeviceList dL = new DeviceList();
dL.testDevices();
}
}
Identify the appropriate option to fill in place of LINE-1 such that the output is:
Laptop is charging
Mobile is charging
6406535937335.
((Chargeable) devices[i]).showChargeStatus();
6406535937336.
devices[i].showChargeStatus();
6406535937337.
((Laptop) devices[i]).showChargeStatus();
6406535937338.
((Mobile) devices[i]).showChargeStatus();
Published solution
**1. Use the compile-time element type:** devices is declared Object[], so devices[i] has compile-time type Object. Object has no showChargeStatus method, even when the runtime object implements Chargeable.
**2. Cast to the common interface:** Both Laptop and Mobile implement Chargeable. Casting each object to Chargeable is therefore valid and exposes showChargeStatus to the compiler.
**3. Follow dynamic dispatch:** At index 0 the call executes Laptop.showChargeStatus and prints Laptop is charging. At index 1 it executes Mobile.showChargeStatus and prints Mobile is charging. A cast to one concrete device class would fail on the other device.
**Answer: A — ((Chargeable) devices[i]).showChargeStatus();.**
A: **Correct:** Both runtime objects implement Chargeable, and dynamic dispatch chooses their respective implementations.
B: **Incorrect:** Object does not declare showChargeStatus, so this does not compile.
C: **Incorrect:** The Laptop cast succeeds first but throws ClassCastException for the Mobile at index 1.
D: **Incorrect:** The Mobile cast throws ClassCastException immediately for the Laptop at index 0.
Consider the Java code given below.
class NegativeBalanceException extends Exception {
public NegativeBalanceException() {
super("Transaction failed: negative balance");
}
}
class BankAccount {
private double balance;
public BankAccount(double b) {
balance = b;
}
public void withdraw(double amount) throws NegativeBalanceException {
if(balance - amount < 0)
throw new NegativeBalanceException();
balance -= amount;
System.out.println("Withdrawal successful: " + balance);
}
}
public class TestBank {
public static void main(String[] args) {
try {
BankAccount acc1 = new BankAccount(500);
BankAccount acc2 = new BankAccount(200);
acc1.withdraw(600);
acc2.withdraw(150);
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Choose the correct option.
6406535937339.
This program generates output:
Transaction failed: negative balance
6406535937340.
This program generates output:
Transaction failed: negative balance
Withdrawal successful: 50.0
6406535937341.
This program generates output:
Withdrawal successful: -100.0
Withdrawal successful: 50.0
6406535937342.
The program crashes due to the uncaught exception: NegativeBalanceException
**Appdev2**
**Section Id :** 640653122506
**Section Number :** 7
**Section type :** Online
**Mandatory or Optional :** Mandatory
**Number of Questions :** 17
**Number of Questions to be attempted :** 17
**Section Marks :** 50
**Display Number Panel :** Yes
**Section Negative Marks :** 0
**Group All Questions :** No
**Enable Mark as Answered Mark for Review and**
No
**Clear Response :**
**Section Maximum Duration :** 0
**Section Minimum Duration :** 0
**Section Time In :** Minutes
**Maximum Instruction Time :** 0
Published solution
**1. Evaluate the first withdrawal:** acc1 begins with balance 500 and receives withdraw(600). The condition \(500-600<0\) is true, so it throws NegativeBalanceException before changing the balance or printing success.
**2. Transfer control to the catch block:** Both withdrawals are inside one try block. Throwing from the first skips the remaining statement acc2.withdraw(150); execution does not resume at that statement after the catch.
**3. Print the exception message:** NegativeBalanceException extends Exception, so catch(Exception e) handles it. e.getMessage() returns Transaction failed: negative balance, which is the sole output line.
**Answer: A — Transaction failed: negative balance.**
A: **Correct:** The first withdrawal throws and the catch prints exactly this message.
B: **Incorrect:** The second withdrawal is skipped when the first throws.
C: **Incorrect:** The guard throws before allowing a negative balance or printing success.
D: **Incorrect:** The catch block handles this Exception subclass.