+ 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?

6th Apr 2018, 11:11 AM
alireza
10 Réponses
+ 11
alireza because the addOneTo method takes the value of x and increment it, instead of incrementing x itself
6th Apr 2018, 11:45 AM
Ibaadi Jaya
Ibaadi Jaya - avatar
+ 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" .
6th Apr 2018, 11:29 AM
Ibaadi Jaya
Ibaadi Jaya - avatar
+ 7
If you want to put the incremented value in x, you can use a return. https://code.sololearn.com/c2hIettstUo5/?ref=app
6th Apr 2018, 11:51 AM
Geo
Geo - avatar
+ 6
I think that Java always pass arguments by value.
6th Apr 2018, 11:33 AM
Geo
Geo - avatar
+ 5
Ibaadi Jaya LunarCoffee Geo in the method, it does this work: x=x+1,why it prints x=5 instead6
6th Apr 2018, 11:44 AM
alireza
+ 5
alireza It does that because the method is adding 1 to the copy of x, so it isn't modifying the original variable.
6th Apr 2018, 11:51 AM
LunarCoffee
LunarCoffee - avatar
+ 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.
6th Apr 2018, 11:31 AM
LunarCoffee
LunarCoffee - avatar
+ 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.
6th Apr 2018, 11:36 AM
LunarCoffee
LunarCoffee - avatar
+ 3
Geo LunarCoffee Ibaadi Jaya Thank you very much
6th Apr 2018, 12:03 PM
alireza
0
So a void method cannot change any variable of primitive type? Is that right?
21st Jan 2020, 3:58 PM
jozhyk
jozhyk - avatar