1Z0-809 · Question #145
class Alpha { int ns; static int s; Alpha(int ns) { if (s == ns) this.ns = ns; } void doPrint() { System.out.println("ns = " + ns + " s = " + s); } } And, public class TestA { public static void…
The correct answer is B. ns = 50 s = 125 ns = 125 s = 125 ns = 0 s = 125. Note on the code: The constructor as displayed appears to have a formatting issue - the version that produces answer B uses if (ns > s) { this.ns = ns; s = ns; } (updates both fields only when the argument exceeds the current static value). The key logic: only when ns is…
Question
Options
- Ans = 50 s = 50 ns = 125 s = 125 ns = 100 s = 100
- Bns = 50 s = 125 ns = 125 s = 125 ns = 0 s = 125
- Cns = 50 s = 125 ns = 125 s = 125 ns = 100 s = 125
- Dns = 50 s = 50 ns = 125 s = 125 ns = 0 s = 125
How the community answered
(33 responses)- A12% (4)
- B79% (26)
- C3% (1)
- D6% (2)
Explanation
Note on the code: The constructor as displayed appears to have a formatting issue - the version that produces answer B uses if (ns > s) { this.ns = ns; s = ns; } (updates both fields only when the argument exceeds the current static value). The key logic: only when ns is strictly greater than s do both this.ns and s get updated.
Option B is correct because s (static, starts at 0) acts as a running maximum: new Alpha(50) sets s=50 and ref1.ns=50 (50>0); new Alpha(125) sets s=125 and ref2.ns=125 (125>50); but new Alpha(100) hits a false condition (100 is NOT > 125), so ref3.ns stays at its default value of 0 and s remains 125. Since all three doPrint() calls happen after all constructors finish, the static s prints as 125 in every line.
Why A is wrong: It shows s as 50, 125, and 100 sequentially - but s is static and has a single value (125) when printing starts, so it cannot appear as different values across lines.
Why C is wrong: It prints ref3.ns as 100, implying the third constructor set this.ns = 100 - but the condition 100 > 125 is false, so that branch never executes and this.ns stays 0.
Why D is wrong: It shows s=50 for ref1's print, which would only be true if ref1 were printed right after construction - but all three prints happen after all three objects are built, at which point s is already 125.
Memory tip: When a static field appears in output, ask yourself "what is its value after the last constructor runs?" - not at each individual construction step. Static = one shared copy, printed at call time, not snapshot time.
Community Discussion
No community discussion yet for this question.