nerdexam
Oracle

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

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 { public static void main (String[ ] args) { Alpha refl = new Alpha(50); Alpha ref2 = new Alpha(125); Alpha ref3 = new Alpha(100); refl.doPrint(); ref2.doPrint(); ref3.doPrint(); } } What is the result?

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)
  • A
    8% (2)
  • B
    72% (18)
  • C
    4% (1)
  • D
    16% (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; the if block was skipped entirely.
  • C is wrong because it treats S as if each object sees only its own "snapshot" of S at 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 = 0 but wrongly shows S = 50 and S = 125 for ref1/ref2 as if S were 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.

Full 1Z0-809 Practice