+ 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; } }
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.
+ 6
@thanks guyz.. @Thirumurugan @felipe @jonas
+ 5
Thanks@Mado
+ 3
if you want output "6"
put num instead of x in System.out.println(num);
+ 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!
+ 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.