Java puzzle 13: Invoking methods

<< 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 
 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.

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!
SarMaroof.com 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!

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 *

Sarmaroof © 2017