Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.
15 / 15 published solutions
Question 2 MCQ · 6.0 marks
Consider the following Java program.
What is the maximum number of activation records on the stack during the execution of the
program?
6406536344545.
2
6406536344546.
3
6406536344547.
4
6406536344548.
5
Published solution
**1. Expand the active calls:** fact(3) calls fact(2), which calls fact(1), which calls fact(0). Before the base case returns, all four factorial invocations are simultaneously active.
**2. Include the caller:** main() is still waiting for fact(3), so it contributes one additional frame. Maximum stack depth is 4+1=5 activation records.
**Answer: D — 5.**
**Convention note:** Count the methods in the displayed program, including main; JVM startup or implementation-internal frames are outside this textbook model.
A: **Incorrect:** This misses most of the recursive chain.
B: **Incorrect:** Three excludes the base case and main frame.
C: **Incorrect:** Four counts the factorial invocations but omits main.
D: **Correct:** The active chain is main→fact(3)→fact(2)→fact(1)→fact(0).
Choose the correct option regarding the given code.
6406536344557.
This code generates output:
6406536344558.
This code generates output:
6406536344559.
This code generates output:
6406536344560.
This code generates a compilation error because the method
cannot be overridden
Published solution
**1. Check final:** SecuritySystem.authenticate() is final, so a subclass cannot override it with the same instance-method signature. Declaring the attempted override final again does not make it legal.
**2. Conclude:** BiometricSystem’s declaration causes a compilation error. No authentication message is produced by this program.
**Answer: D — Compilation error: authenticate() is final.**
A: **Incorrect:** Compilation fails; superclass and subclass bodies do not both run automatically anyway.
B: **Incorrect:** Compilation fails before any base-class message can print.
C: **Incorrect:** Dynamic dispatch cannot rescue an illegal override of a final method.
D: **Correct:** The final superclass method cannot be overridden.
generates compilation error because a variable of type
cannot refer to an object of type
.
6406536344563.
generates run time error because there is ambiguity in which
method is being invoked.
6406536344564.
The program generates output:
Published solution
**1. Resolve the no-argument call:** ImagePost obj refers to a SponsoredPost object. obj.publish() selects the no-argument signature and dispatches to SponsoredPost.publish().
**2. Resolve the overloaded call:** obj.publish(100) selects ImagePost.publish(int), which SponsoredPost does not override. The output is “Publish sponsored post with default promotion”, then “Image post with likes: 100”.
**Answer: D — Publish sponsored post with default promotion; Image post with likes: 100.**
A: **Incorrect:** Overriding does not automatically execute all superclass bodies; there are only two print calls.
B: **Incorrect:** SponsoredPost is a subclass of ImagePost, so the assignment is legal.
C: **Incorrect:** Overload resolution and dynamic dispatch select a definite method.
D: **Correct:** The overridden no-argument method and inherited int overload run in that order.
**1. Delegate within Intern:** The one-argument constructor must call this("ABC Corp",15000.00,d), forwarding its domain together with default company values to Intern’s three-argument constructor.
**2. Initialize Company:** That constructor calls super(n,s), then stores domain=d. Dynamic toString() uses Company’s initialized fields plus the domain, giving “name = ABC Corp, stipend = 15000.0, domain = ML”.
**Answer: B — LINE-1: this("ABC Corp",15000.00,d); LINE-2: super(n,s);.**
A: **Incorrect:** Company has no three-argument constructor, and Intern has no matching two-argument constructor.
B: **Correct:** this(...) chains to the Intern constructor, whose super(n,s) initializes Company correctly.
C: **Incorrect:** n and s do not exist in the one-argument constructor; the other this(...) call is also invalid recursive delegation.
D: **Incorrect:** The displayed constructor signatures do not match these calls.
**1. Track actual types:** obj1, obj2 and obj3 have different declared types, but all three refer to separately created Humanoid objects. Each called method is an overridable instance method.
**2. Apply dynamic dispatch:** operate(), diagnose() and performTask() therefore all use Humanoid’s bodies. Output: “Humanoid operating”, “Humanoid diagnosing”, “Humanoid performing task”.
**Answer: B — Humanoid operating; Humanoid diagnosing; Humanoid performing task.**
A: **Incorrect:** Superclass implementations do not run automatically, and there are only three calls.
B: **Correct:** Every call dispatches to the Humanoid override.
C: **Incorrect:** Declared reference types do not force Robot’s bodies for these instance methods.
D: **Incorrect:** The first two calls also dispatch to Humanoid, not to their reference-type classes.
**1. Use the public abstraction:** SensorIter is a private inner class. Outside SensorArray, obtain an instance through sensors.getIterator() and store it in the accessible Iterator interface type.
**2. Invoke through the interface:** Iterator declares has_next() and get_next(), so Iterator iter=sensors.getIterator() makes both calls in the loop legal without exposing the implementation class.
**Answer: B — Iterator iter = sensors.getIterator();.**
**Convention note:** The ellipses stand for valid iterator state and method bodies; the question tests how the client obtains and types the iterator.
A: **Incorrect:** The private inner class cannot be instantiated by this unqualified name outside SensorArray.
B: **Correct:** The factory returns an Iterator, and that interface exposes both required methods.
C: **Incorrect:** SensorIter is inaccessible here; additionally the factory’s declared return type is Iterator.
D: **Incorrect:** A private implementing class does not prevent calls through its public interface.
Reason: An interface reference cannot be passed as a constructor argument.
6406536344550.
This program generates the output:
6406536344551.
This program generates the output:
followed by runtime error
Reason: A method inside
is invoking
inside
, whereas
is invoking another method in
.
6406536344552.
This program generates compiler error at
Reason: A method inside
is invoking a method defined in an interface.
Published solution
**1. Pass the callback:** WorkSession implements Pomodoro, so Timer(this,minutes) receives a compatible interface reference and the value 25.
**2. Follow call order:** runTimer() first prints “Timer running”, then p.notifyUser(25) invokes WorkSession.notifyUser(), printing “Session time: 25 minutes”. After that returns, beginSession prints “Pomodoro session ended”.
**Answer: B — Timer running; Session time: 25 minutes; Pomodoro session ended.**
A: **Incorrect:** An object implementing an interface may be passed to a parameter of that interface type.
B: **Correct:** The timer message, callback message and final session message follow this execution order.
C: **Incorrect:** A callback to the waiting object is legal and does not imply a runtime error.
D: **Incorrect:** Invoking a declared interface method is legal and dispatches to the implementation.
cannot be accessed without using an accessor method.
6406536344554.
The program generates the output:
6406536344555.
The program generates the output:
6406536344556.
The program generates the output:
Published solution
**1. Check access before execution:** performanceScore is private in EmployeeTest. The separate top-level class Test cannot assign emp2.performanceScore directly, even when both classes are in the same source file.
**2. Conclude:** LINE-1 is a compile-time access error, so neither println executes. A suitable accessible setter could permit the intended update, but it is absent.
**Answer: A — Compilation error at LINE-1: private performanceScore access.**
A: **Correct:** The private-field access is illegal from the separate class Test.
B: **Incorrect:** These would be the intended values after a legal update, but the displayed program does not compile.
C: **Incorrect:** The program fails, and preincrement would assign employee IDs 1 and 2 rather than zero.
D: **Incorrect:** The program fails, and a shared increasing counter would not give both employees ID 1.
**1. Inspect inheritance syntax:** LINE 15 uses extends Device, Portable. A class may extend one class and implement interfaces; it must use extends Device implements Portable, and then implement carry() or be abstract.
**2. Inspect construction:** LINE 20 tries new Device(), but Device is abstract. It also attempts to assign the superclass-typed result to a Laptop reference. The option identifying LINE 15 and LINE 20 is correct.
**Answer: C — Line 15 and Line 20.**
**Convention note:** Treat the public classes as belonging to appropriately named separate files. The method carry() must also be supplied if Hybrid is repaired into a concrete Portable implementation.
A: **Incorrect:** Laptop correctly extends Device, implements Portable and supplies public method bodies.
B: **Incorrect:** An interface can declare carry() without explicitly writing public abstract.
C: **Correct:** The class inheritance declaration and abstract-class instantiation are erroneous.
D: **Incorrect:** An abstract class may declare a public abstract method.
**1. Retain the abstract obligation:** Differentiable requires takeDerivative(). Expression overrides evaluate() but leaves takeDerivative() unimplemented, so Expression must be abstract.
**2. Complete the subtype:** Polynomial extends that abstract class and implements takeDerivative(). It is consequently a concrete Differentiable; its evaluate() is inherited from Expression, printing “Evaluating at x”, followed by “Polynomial taking derivative”.
**Answer: B — abstract class Expression implements Differentiable with evaluate() printing Evaluating at x.**
A: **Incorrect:** A concrete Expression cannot leave takeDerivative() unimplemented.
B: **Correct:** The abstract class can supply evaluate() and defer takeDerivative() to Polynomial.
C: **Incorrect:** An interface extends rather than implements another interface, and Polynomial cannot extend an interface as a class.
D: **Incorrect:** Expression would be an interface, incompatible with class Polynomial extends Expression; its concrete method also lacks default or static.
generates compilation error because a variable of type
cannot refer to an object of type
.
6406536344588.
generates runtime error because there is ambiguity in which
method is being invoked.
Published solution
**1. Resolve the most specific default:** DigitalSensor extends Sensor and overrides collectData() with its own default method. TemperatureSensor inherits that more-specific default and implements calibrate().
**2. Follow the calls:** The exact code prints “Digital sensor collecting data”, then “Temperature sensor calibrated”. The intended option is A, which identifies the DigitalSensor implementation.
**Answer: A — Digital sensor collecting data; Temperature sensor calibrated.**
**Convention note:** The answer choices mistakenly use “reading data”, while both method bodies print “collecting data”. A is the intended dispatch answer, but its output is not verbatim correct; the exact output is provided above.
A: **Correct:** This selects the correct implementation, although the printed option says “reading” where the code says “collecting”.
B: **Incorrect:** The more-specific DigitalSensor default overrides the Sensor default.
C: **Incorrect:** TemperatureSensor implements DigitalSensor, hence also Sensor; the assignment is valid.
D: **Incorrect:** The subinterface default is more specific, so there is no ambiguity.
**1. Initialize each object:** b1 uses the no-argument constructor, retaining title “Unknown Title” and setting author “Unknown Author”. b2’s two-argument constructor sets “Java Programming” and “Riya”.
**2. Apply the setter:** b1.setAuthor("Ananya") changes only b1’s author. The lines are “Title: Unknown Title, Author: Ananya” and “Title: Java Programming, Author: Riya”.
**Answer: C — Title: Unknown Title, Author: Ananya; Title: Java Programming, Author: Riya.**
**Convention note:** Treat the two public top-level classes as separate correspondingly named source files.
A: **Incorrect:** Changing b1 does not copy b2’s author into it.
B: **Incorrect:** This ignores b1.setAuthor("Ananya").
C: **Correct:** Both independently initialized objects and the setter are represented correctly.
D: **Incorrect:** The setter targets b1 rather than b2.
**1. Obtain hidden implementations through factories:** DirectMessage and StoryUpdate are private inner classes, so client code cannot name or construct them directly. Both implement Notification, directly or through inheritance.
**2. Use interface references:** Store sm.getAlert1() and sm.getAlert2() in Notification obj1 and obj2. Calling sendAlert() dispatches to DirectMessage and StoryUpdate respectively, giving the two requested messages.
**Answer: B — Notification obj1=sm.getAlert1(); Notification obj2=sm.getAlert2();.**
A: **Incorrect:** Both implementation class names are private and unavailable for direct construction here.
B: **Correct:** The accessible Notification type exposes sendAlert() for both returned objects.
C: **Incorrect:** The client cannot name the private inner classes as local variable types.
D: **Incorrect:** The private inner classes cannot be constructed directly by the client.
Choose the correct option regarding the above code.
6406536344597.
generates compilation error because the method
is not abstract.
6406536344598.
generates compilation error because class
cannot implement two interfaces.
6406536344599.
generates compilation error because class
is
not declared as abstract.
6406536344600.
,
and
generate compilation errors because the
methods
,
and
are not abstract.
Published solution
**1. List the required methods:** Activatable requires activate() and deactivate(); Calibratable requires calibrate() and supplies default showCalibrationStatus(). Implementing multiple interfaces is legal.
**2. Find the missing implementation:** TemperatureSensor implements activate() and deactivate() but not calibrate(). It must implement that method or be declared abstract; its concrete declaration at LINE 11 is invalid.
**Answer: C — LINE 11: TemperatureSensor must implement calibrate() or be abstract.**
A: **Incorrect:** A default interface method may have a body, so LINE 7 is legal.
B: **Incorrect:** A class is allowed to implement multiple interfaces.
C: **Correct:** The class leaves the abstract calibrate() obligation unimplemented.
D: **Incorrect:** These bodyless interface instance methods are implicitly public abstract.
**1. Resolve the existing call:** obj has declared type Algorithm but actual type SortingAlgorithm. execute() dispatches to SortingAlgorithm, printing “Sorting algorithm is executing”.
**2. Expose the subclass-only method:** C checks instanceof and casts; D directly casts. Both succeed for the actual object and then print “QuickSort applied”.
**Answer: C, D — C and D — guarded or direct SortingAlgorithm cast.**
**Convention note:** The requested sample output says “Sorting algorithm is running”, but the actual method prints “Sorting algorithm is executing”. C and D are the intended valid insertions; no offered insertion changes the already executed first print.
A: **Incorrect:** Algorithm does not declare applyQuickSort(), so lookup fails.
B: **Incorrect:** applyQuickSort() is nonstatic and needs an instance.
C: **Correct:** The guarded downcast is valid and exposes the subclass method.
D: **Correct:** The direct downcast succeeds for this SortingAlgorithm object.