1Z0-809 · Question #52
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 B. ns = 50 S = 125 ns = 125 S = 125 ns = 0 S = 125. Option B is correct because the constructor only assigns this.ns when S < ns - for ref3(100), the condition 125 < 100 is false, so this.ns is never set and retains Java's default value of 0. Meanwhile, S is static (shared across all instances), so by the time any doPrint()…
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 = 125 ns = 100 S = 100
- Dns = 50 S = 50 ns = 125 S = 125 ns = 0 S = 125
How the community answered
(25 responses)- A8% (2)
- B72% (18)
- C4% (1)
- D16% (4)
Explanation
Option B is correct because the constructor only assigns this.ns when S < ns - for ref3(100), the condition 125 < 100 is false, so this.ns is never set and retains Java's default value of 0. Meanwhile, S is static (shared across all instances), so by the time any doPrint() runs, every object sees the final value of S = 125.
- A is wrong because it shows
ref3.ns = 100, implying the constructor ran fully for ref3 - it didn't; theifblock was skipped entirely. - C is wrong because it treats
Sas if each object sees only its own "snapshot" ofSat creation time, but static fields are shared globally and reflect the current value at print time. - D is wrong for the same snapshot reasoning - it correctly gets
ref3.ns = 0but wrongly showsS = 50andS = 125for ref1/ref2 as ifSwere captured at construction.
Memory tip: Think "static = shared scoreboard, instance = personal score." If the constructor's condition fails, the personal score (ns) never gets written, defaulting to 0 - but the scoreboard (S) is always current for everyone.
Community Discussion
No community discussion yet for this question.