0
java value types
Why its 5? Can you please explain for me? public class MyClass { public static void main(String[ ] args) { int x = 5; addOneTo(x); System.out.println(x); } static void addOneTo(int num) { num = num + 1; } } // Outputs "5"
3 Respuestas
+ 3
Functions arguments are passed by value, so when addOneTo increments 'num', in fact, it doesn't increment the actual value of 'x'. It remains unchanged, so the output is 5.
+ 3
this returns to "pass by value" subject in java fundamentals concepts, that is when you pass a variable to a method, just a copy of that variable passed to the method and the variable doesn't change after runing the method ;)
read more about this!
0
the variable you set in MyClass is 'x' is passed through addOneTo but it's a local variable there.
Also inside addOneTo method 'num' variable is local variable there and after increased to 6 it will be destroyed since there isn't any return value.