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.
2 Réponses
+ 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.
+ 2
5 will be the output. This is known as pass by copy.