nerdexam
Oracle

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? |…

Working with Methods and Encapsulation

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 ref1 = new Alpha(50); Alpha ref2 = new Alpha(125); Alpha ref3 = new Alpha(100); ref1.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 = 100 ns = 100 s = 100
  • Dns = 50 s = 50 ns = 125 s = 125 ns = 0 s = 125

How the community answered

(20 responses)
  • A
    60% (12)
  • B
    5% (1)
  • C
    20% (4)
  • D
    15% (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):

Calls beforeCondition s < ns?this.nss after
new Alpha(50)00 < 50 → true5050
new Alpha(125)5050 < 125 → true125125
new Alpha(100)125125 < 100 → false0 (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

#static variables#instance variables#constructors#default initialization

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice