+ 5
value_types
https://code.sololearn.com/c4VwLCiPFQ1T/?ref=app why out put of this code is 5? can some one explain for me how this code work?
10 Antworten
+ 11
alireza because the addOneTo method takes the value of x and increment it, instead of incrementing x itself
+ 7
See this part of the Java tutorial, in the Value and Reference Types lesson of the Classes and Objects section:
"These data types (in this case "x") store the values assigned to them in the corresponding memory locations.
So, when you pass them to a method, you basically operate on the variable's value, rather than on the variable itself."
In other words, the addOneTo method increments "5" instead of "x" .
+ 7
If you want to put the incremented value in x, you can use a return.
https://code.sololearn.com/c2hIettstUo5/?ref=app
+ 6
I think that Java always pass arguments by value.
+ 5
+ 5
alireza
It does that because the method is adding 1 to the copy of x, so it isn't modifying the original variable.
+ 4
In Java, the primitive types (lowercase common types like int, float, double, long, short, boolean, etc.) aren't objects, and they're passed by value instead of by reference like with objects (instances of classes).
In your case, adding the number to the variable in the method does nothing to the variable itself, because it is passed by value. That means a copy was taken of the object, and that was passed to the function.
When passing by reference, on the other hand, you give the method a reference to the actual object, so when you modify that reference, it modifies the original object.
+ 4
Geo
Java passes by value for the primitive types; otherwise, it passes by reference (for all objects), though there may be exceptions to that that I am not aware of. It makes sense, because copying an object of a huge class (1000+ members, for example) would be far too inefficient, so passing by reference is used instead.
+ 3
0
So a void method cannot change any variable of primitive type? Is that right?