public class MyClass { public static void main(String[ ] args) { int num = 5; addOneTo(num); System.out.println(num); } static int addOneTo(int num) { num = num + 1; return num; } } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

public class MyClass { public static void main(String[ ] args) { int num = 5; addOneTo(num); System.out.println(num); } static int addOneTo(int num) { num = num + 1; return num; } }

what is the output of this program??5,6 justify.

11th Sep 2016, 8:11 AM
Nikhil Mittal
Nikhil Mittal - avatar
2 Answers
+ 4
You didn't assign num to the result of addOneTo like so, num = addOneTo (num); Therefore the result is 5. Still not sure? Lets say the static method has a parameter it takes in of b instead of num. This would make the method look like static int addOneTo(int b) { b = b + 1; return b; } see the problem here? This is the idea of Scope. When you define the parameter as num for the rest of the function num will be whatever you pass into your function. That's why addOneTo (num) returns 6 but doesn't set the value of num to 6.
11th Sep 2016, 12:48 PM
John McEnery
John McEnery - avatar
+ 2
5 will be the output. This is known as pass by copy.
11th Sep 2016, 9:06 AM
Ousmane Diaw