nerdexam
Oracle

1Z0-803 · Question #151

Given: public class Access { private int x = 0; private int y = 0; public static void main(String[] args) { Access accApp = new Access(); accApp.printThis(1, 2); accApp.printThat(3, 4); } public void

The correct answer is B. x:0 y:0. The printThis method fails to modify the instance variables because it assigns local parameters to themselves, leaving the instance variables with their initial values. The printThat method correctly updates the instance variables using the this keyword.

Working with Methods and Encapsulation

Question

Given:

public class Access { private int x = 0; private int y = 0; public static void main(String[] args) { Access accApp = new Access(); accApp.printThis(1, 2); accApp.printThat(3, 4); } public void printThis(int x, int y) { x = x; y = y; System.out.println("x:" + this.x + " y:" + this.y); } public void printThat(int x, int y) { this.x = x; this.y = y; System.out.println("x:" + this.x + " y:" + this.y); } } What is the result?

Options

  • Ax:1 y:2
  • Bx:0 y:0
  • Cx:3 y:4
  • Dx:3 y:4

How the community answered

(53 responses)
  • A
    4% (2)
  • B
    79% (42)
  • C
    11% (6)
  • D
    6% (3)

Why each option

The `printThis` method fails to modify the instance variables because it assigns local parameters to themselves, leaving the instance variables with their initial values. The `printThat` method correctly updates the instance variables using the `this` keyword.

Ax:1 y:2

This would be the result if `printThis` had correctly assigned the parameter values to the instance variables `this.x` and `this.y`.

Bx:0 y:0Correct

Inside the `printThis(int x, int y)` method, the statements `x = x;` and `y = y;` refer to and assign the local parameter variables to themselves. Since the `this` keyword is not used, the instance variables `this.x` and `this.y` remain unaffected by these assignments. Therefore, when `System.out.println` is called within `printThis`, it prints the initial default values of the instance variables, which are `0` for both `x` and `y`.

Cx:3 y:4

This is the output produced by the `printThat` method, which correctly modifies the instance variables using the `this` keyword, but the question implicitly asks for the output of the first `System.out.println` call.

Dx:3 y:4

This is the output produced by the `printThat` method, which correctly modifies the instance variables using the `this` keyword, but the question implicitly asks for the output of the first `System.out.println` call.

Concept tested: Java instance vs. local variables, 'this' keyword

Source: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Topics

#this keyword#instance variables#method parameters

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice