nerdexam
Oracle

1Z0-829 · Question #34

Given: public class App { public int x = 100; public static void main(String[] args) { int x = 1000; App t = new App(); t.myMethod(x); System.out.println(x); } public void myMethod(int x) { x++…

The correct answer is D. 1001 100 1000. Option D is correct because Java is pass-by-value: when main calls t.myMethod(x), it passes a copy of the local x (1000) - so x++ inside myMethod increments that copy to 1001 (first print), but the original x in main remains 1000 (third print). The second print (this.x) refers…

Java Object-Oriented Approach

Question

Given: public class App { public int x = 100; public static void main(String[] args) { int x = 1000; App t = new App(); t.myMethod(x); System.out.println(x); } public void myMethod(int x) { x++; System.out.println(x); System.out.println(this.x); } } What is the result?

Options

  • A1001 1001 1000
  • B101 101 1000
  • C100 100 1000
  • D1001 100 1000

How the community answered

(62 responses)
  • A
    10% (6)
  • B
    2% (1)
  • C
    6% (4)
  • D
    82% (51)

Explanation

Option D is correct because Java is pass-by-value: when main calls t.myMethod(x), it passes a copy of the local x (1000) - so x++ inside myMethod increments that copy to 1001 (first print), but the original x in main remains 1000 (third print). The second print (this.x) refers to the instance field of the App object, which was initialized to 100 and never modified.

Why the distractors fail:

  • A (1001/1001/1000) - confuses this.x (instance field = 100) with the local parameter after increment
  • B (101/101/1000) - assumes the parameter starts at 100 (the instance field value) rather than 1000 (what was passed in)
  • C (100/100/1000) - ignores the x++ increment entirely

Memory tip: When you see this.x vs. a plain x in Java, ask yourself which scope wins - this.x is always the instance field, while a bare x resolves to the nearest local scope first. And remember: primitives passed to methods are copies, so mutations inside the method never escape back to the caller.

Topics

#Variable scope#Pass-by-value#this keyword#Instance variables

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice