Java puzzle 26: Invoking a method within a method

Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
 P01   P02   P03   P04   P05   P06   P07   P08   P09   P10   P11   P12   P13   P14   P15   P16   P17   P18   P19   P20   P21   P22   P23   P24   P25   P26   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

  1. 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.
  2. 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.
  3. So, the statement System.out.print(“x” + x + “y” + y); writes x5y6 to the  standard output.

The correct answer is: x5y6


If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below! offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof


 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017