Quizzes Assignments Puzzles Easy exercises Required knowledge |
< |
Java Puzzles Green = Easy, Blue = Normal, Red = Hard Select 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 By title |
> |
---|
This code demonstrates invoking a method within another method.
Java puzzle 26: Invoking a method within a method
Level: Normal
What is the output of this program and why?
public class MyClass { int x = 2; int y = 5; void myMethod(int x, int y) { this.x += x; this.y += y; } void print() { myMethod(3, 1); System.out.print("x" + x + "y" + y); } public static void main(String[] args) { new MyClass().print(); } }
Author: Sar Maroof
Answer explanation
- The statement myMethod(3, 1); invokes the method myMethod. The statement this.x += x; adds the value of the parameter x to the value of the instance variable x. So, x = the initial value of x + 3 = 2 + 3 = 5.
- The statement this.y += y; adds the value of the parameter y to the value of the instance variable y. So, y = its initial value + 1, y = 5 + 1 = 6.
- So, the statement System.out.print(“x” + x + “y” + y); writes x5y6 to theĀ standard output.
The correct answer is: x5y6
Suggested Articles
![]() ![]() ![]() |