+ 1
explain this code please.
why is the output 5? and not 6. Could someone please explain using the most simple terms possible. 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 Réponses
+ 2
here, passing x doesn't actually pass x. instead, it makes a copy of x and passes it. hence, anychanges to the copy wouldn't affect x.
0
That was a brilliant reply, thank you!
0
I think answer is 5 because, in this example value of x is refers to the function and as this function get the value of x set it to num then increase num, and code prints the value of x not num. so this code's output is 5.