+ 1

Value & Reference Type

Value Type was kind of confusing 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" -> Why the output is 5 I thought was 6?

30th May 2017, 4:36 AM
Jose Humberto Mejia
Jose Humberto Mejia - avatar
1 Antwort
+ 1
Java passes by value, and this is a perfect example of that. int num in the method addOneTo is indeed 5. However this is not the same variable as the one before. num is a new int that has the value of 5. You then increase the value by one, so num = 6. But again this is not the same int, num is NOT x. x only passed it's value to the method, which made num equal to that vakue. To work around this make the function return an int value. Ex/ int x = 5; x = addOneTo(x); Then you can do: static int addOneTo(int num){ return num+1; } In conclusion, In Java, Primitive data-types are passed by value and not by reference.
30th May 2017, 4:41 AM
Rrestoring faith
Rrestoring faith - avatar