Java puzzle 13: Invoking methods

  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 
>

In this Java puzzle the method myMethod is invoked, which returns an integer variable. Two integer parameters are passed to the method.

Java puzzle 13: Invoking a method

Level: Easy

What is the output of this program and why?

public class MyClass
{
  int i = 2;
  int i2;
  
  public int myMethod(int i, int i2)
  {
    return i + this.i2;
  }
  public static void main(String[] args)
  {
    MyClass mc = new MyClass();
    System.out.print(mc.myMethod(3, 5));
  }
}
Author: Sar Maroof

Answer explanation

  1. The parameters 3 and 5 are passed to the method myMethod.
  2. The statement return i + this.i2 returns the value of the
    parameter i plus the value of the instance variable i2. Remember that the keyword this here refers to the instance variable
    not the parameter that passed to the method.
  3. The value of the parameter i is 3 and the value of the instance variable i2 is 0, because it is not initialized.
    Therefore the program writes 3 + 0 = 3 to the standard output.





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!

6 Comments

Add a Comment
  1. I just really like what you’re up to, and how you show and discuss it!.

  2. Thank you for offering this. It’s encouraging.

    1. You are welcome!

  3. Great, outstanding perform. It introduced a warm grin to my experience.

  4. Thanks for this Awesome publish.

    1. You are welcome!

Leave a Reply

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