0

Java beginner need help

can someone explain why output is 5 not 6 ?(in the simplest way possible i'm quite dumb) 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"

18th Oct 2017, 2:47 PM
oyl
1 Answer
+ 5
For primitive types like int, double, char etc., when a variable is passed to a method, actually a COPY (value) of the variable is passed. So whatever you'll do inside that method, it won't affect the original variable. Calling the method will pass 5 (value) to it, it won't pass x. If you print num inside the method, it will print 6. But x will remain as it was.
18th Oct 2017, 2:56 PM
Shamima Yasmin
Shamima Yasmin - avatar