Java puzzle 26: Invoking a method within a method

  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

  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

 

The second edition of Learn Java and Master Writing Code is easy to understand, organized to learn Java voor beginners and it guides readers to master Java code by solving more than 100 exercises and assignments. This book explains each chapter properly before starting with the exercises and the assignments. Available on Amazon. See inside the book here!




Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 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 *