Java puzzle 26: Invoking a method within a method

<< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
 P25   P26   P27   P28   P29   P30 
 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". He is a professional computer programming teacher, gives master classes and publishes technical articles. His experience with developing software started from 2001 and he has worked as a software developer 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