1Z0-803 · Question #254
Given: public class TestField { int x; int y; public void doStuff(int x, int y) { this.x = x; y =this.y; } public void display() { System.out.print(x + " " + y + " : "); } public static void main(Stri
The correct answer is C. 100 200 : 100 0 :. This program demonstrates object instantiation, instance variable assignment, and parameter passing in Java. The key is understanding how this.y references the instance variable while y without this refers to the method parameter.
Question
Given:
public class TestField { int x; int y; public void doStuff(int x, int y) { this.x = x; y =this.y; } public void display() { System.out.print(x + " " + y + " : "); } public static void main(String[] args) { TestField m1 = new TestField(); m1.x = 100; m1.y = 200; TestField m2 = new TestField(); m2.doStuff(m1.x, m1.y); m1.display(); m2.display(); } } What is the result?
Options
- A100 200 : 100 200
- B100 0 : 100 0 :
- C100 200 : 100 0 :
- D100 0 : 100 200 :
How the community answered
(46 responses)- A7% (3)
- B24% (11)
- C57% (26)
- D13% (6)
Why each option
This program demonstrates object instantiation, instance variable assignment, and parameter passing in Java. The key is understanding how `this.y` references the instance variable while `y` without `this` refers to the method parameter.
Incorrect, `m2.y` is not updated by the `doStuff` method as the assignment `y = this.y` affects the local parameter, not the instance variable.
Incorrect, `m1.y` is explicitly set to 200, not 0.
C is correct because `m1.x` and `m1.y` are explicitly set to 100 and 200 respectively. In `m2.doStuff(m1.x, m1.y)`, `this.x = x` assigns the parameter `x` (100) to `m2.x`, but `y = this.y` assigns `m2.y`'s default value (0) to the *local parameter* `y`, leaving `m2.y` (the instance variable) at its default of 0, resulting in '100 200 : 100 0 :'.
Incorrect, `m1.y` is 200, and `m2.y` is 0.
Concept tested: Java instance variables, method parameters, 'this' keyword.
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Topics
Community Discussion
No community discussion yet for this question.