nerdexam
Oracle

1Z0-809 · Question #141

Given: ``java class MyField { int x, y; public void doStuff(int x, int y) { this.x = x; this.y = y; } public void display() { System.out.println(x + ":" + y + " "); } public static void…

The correct answer is C. 100 : 200 ; 100 : 0. Option C as stated appears to be incorrect - the actual answer based on this code is B (100:200 ; 100:200), and here's why. Code trace: 1. m1.x = 100, m1.y = 200 - both fields set directly 2. m2.doStuff(m1.x, m1.y) passes 100 and 200 as arguments 3. Inside doStuff, this.x = x…

Question

Given:
class MyField {
 int x, y;
 public void doStuff(int x, int y) {
 this.x = x;
 this.y = y;
 }
 public void display() {
 System.out.println(x + ":" + y + " ");
 }
 public static void main(String[] args) {
 MyField m1 = new MyField();
 m1.x = 100;
 m1.y = 200;
 MyField m2 = new MyField();
 m2.doStuff(m1.x, m1.y);
 m1.display();
 m2.display();
 }
}
What is the result?

Options

  • A100 : 0 ; 100 : 200
  • B100 : 200 ; 100 : 200
  • C100 : 200 ; 100 : 0
  • D100 : 0 ; 100 : 0

How the community answered

(45 responses)
  • A
    2% (1)
  • B
    4% (2)
  • C
    82% (37)
  • D
    11% (5)

Explanation

Option C as stated appears to be incorrect - the actual answer based on this code is B (100:200 ; 100:200), and here's why.

Code trace:

  1. m1.x = 100, m1.y = 200 - both fields set directly
  2. m2.doStuff(m1.x, m1.y) passes 100 and 200 as arguments
  3. Inside doStuff, this.x = x sets m2.x = 100 and this.y = y sets m2.y = 200 - the this. qualifier eliminates any shadowing ambiguity
  4. m1.display()100:200, m2.display()100:200

Why the distractors fail:

  • A / D assume one or both y values are 0, which would only happen if m1.y was never assigned or doStuff failed to set this.y - neither is true
  • C would require m2.y to remain 0, meaning this.y = y was ignored - but with the explicit this. prefix, the field assignment works correctly

Memory tip: When a method parameter shares a name with an instance field, this.field = param always assigns to the field - this is unambiguous. Only code that writes y = y (without this) would be a no-op bug.

Note to you: The question's stated correct answer of C appears to be a typo or error in the source material. I'd recommend verifying against your course materials - the correct answer based on standard Java semantics is B.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice