1Z0-808 · Question #8
Given: class Alpha { int ns; static int s; Alpha(int ns) { if (s < ns) { s = ns; this.ns = ns; } } void doPrint() { System.out.println("ns = " + ns + " s = " + s); } } And, public class TestA {…
The correct answer is A. ns = 50 s = 125 ns = 125 s = 125 ns = 100 s = 125. Option B is actually the correct output based on the code - the stated answer A appears to be incorrect. Here's why: Tracing through the constructor logic (if (s < ns) - only update if the new value exceeds the current static max): | Call | s before | Condition s < ns? |…
Question
Options
- Ans = 50 s = 125 ns = 125 s = 125 ns = 100 s = 125
- Bns = 50 s = 125 ns = 125 s = 125 ns = 0 s = 125
- Cns = 50 s = 50 ns = 125 s = 100 ns = 100 s = 100
- Dns = 50 s = 50 ns = 125 s = 125 ns = 0 s = 125
How the community answered
(20 responses)- A60% (12)
- B5% (1)
- C20% (4)
- D15% (3)
Explanation
Option B is actually the correct output based on the code - the stated answer A appears to be incorrect. Here's why:
Tracing through the constructor logic (if (s < ns) - only update if the new value exceeds the current static max):
| Call | s before | Condition s < ns? | this.ns | s after |
|---|---|---|---|---|
new Alpha(50) | 0 | 0 < 50 → true | 50 | 50 |
new Alpha(125) | 50 | 50 < 125 → true | 125 | 125 |
new Alpha(100) | 125 | 125 < 100 → false | 0 (default) | 125 |
When Alpha(100) is constructed, the if condition fails - so this.ns = ns never executes, leaving ref3.ns at its default value of 0.
Output:
ns = 50 s = 125
ns = 125 s = 125
ns = 0 s = 125 ← not 100
This matches B, not A. Choice A is wrong because it shows ref3.ns = 100, which would only be true if the assignment executed - but it doesn't. Choice D is wrong because it shows ref1.s = 50 before ref2 updates it, but doPrint() is called after all three objects are constructed, so s is already 125 for all of them.
Memory tip: When a static field acts as a "running max," remember that instance fields that are only set inside a conditional will hold their default value (0 for int) if the condition never triggers - the constructor parameter name shadows the instance field but doesn't assign it automatically.
Topics
Community Discussion
No community discussion yet for this question.