explain this code please. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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"

18th Mar 2017, 12:41 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
3 Answers
+ 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.
18th Mar 2017, 12:48 PM
Puspal Ghosh
Puspal Ghosh - avatar
0
That was a brilliant reply, thank you!
18th Mar 2017, 12:55 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
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.
25th Apr 2017, 2:45 PM
Soumik