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
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)- A2% (1)
- B4% (2)
- C82% (37)
- D11% (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:
m1.x = 100,m1.y = 200- both fields set directlym2.doStuff(m1.x, m1.y)passes100and200as arguments- Inside
doStuff,this.x = xsetsm2.x = 100andthis.y = ysetsm2.y = 200- thethis.qualifier eliminates any shadowing ambiguity m1.display()→100:200,m2.display()→100:200
Why the distractors fail:
- A / D assume one or both
yvalues are 0, which would only happen ifm1.ywas never assigned ordoStufffailed to setthis.y- neither is true - C would require
m2.yto remain 0, meaningthis.y = ywas ignored - but with the explicitthis.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.