+ 4

Can anyone plz explain this code better that why we have output 5 not 6.

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; } }

2nd Jul 2017, 1:55 PM
Pulkit sharma
Pulkit sharma - avatar
6 Respostas
+ 1
The x variable is not passed to the addOneTo() method, only a copy of it's value. That's why it is not affected. There are variables that are passed by copy, like int, double, float... and variables passed by reference (to it's memory address), like String and all others object type variables. For reference variables a copy of it's memory address is passed, them, by modifying a variable passed by reference you change the value stored in that address.
2nd Jul 2017, 2:12 PM
Felipe
Felipe - avatar
+ 6
@thanks guyz.. @Thirumurugan @felipe @jonas
2nd Jul 2017, 2:43 PM
Pulkit sharma
Pulkit sharma - avatar
+ 5
Thanks@Mado
2nd Jul 2017, 2:42 PM
Pulkit sharma
Pulkit sharma - avatar
+ 3
if you want output "6" put num instead of x in System.out.println(num);
2nd Jul 2017, 2:36 PM
Thirumurugan C
Thirumurugan C - avatar
+ 2
The reason is because Java by default passes by value, meaning it creates a copy of what you pass in through parameters and you are changing that copy. The best way to directly change the variable would be something like this: public class MyClass { public static void main(String[ ] args) { int x = 5; x = addOneTo(x); System.out.println(x); } static int addOneTo(int num) { return num = num + 1; } } returning a value from a function and then directly assigning that value to the variable that you passed in, is a great way to solve this problem. Hope this helps! Happy Coding!
2nd Jul 2017, 2:39 PM
Amado Marquez
Amado Marquez - avatar
+ 1
That's because the method takes a value and assigns it to a method variable called num. This variable is incremented by one while the x variable in the main method isn't affected.
2nd Jul 2017, 2:06 PM
Jonas Schröter
Jonas Schröter - avatar