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
- The parameters 3 and 5 are passed to the method myMethod.
- 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. - 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.
Suggested Articles
![]() ![]() ![]() |
I just really like what you’re up to, and how you show and discuss it!.
Thank you for offering this. It’s encouraging.
You are welcome!
Great, outstanding perform. It introduced a warm grin to my experience.
Thanks for this Awesome publish.
You are welcome!