+ 2

why doesn't swapping doesn't happen here?

As a and b are passed as reference their values should affect in main method after swapping but this doesn't happening https://code.sololearn.com/cA8A5a23A15a/?ref=app

8th Apr 2021, 3:52 AM
rajshekhar y dodamani
rajshekhar y dodamani - avatar
7 odpowiedzi
+ 2
In Java, parameters are always passed by value. Even in the case of the so-called reference variables. What you pass is the memory address value contained in the variable that refers to the location where the object is allocated. Consequently, if you change the reference contained in the formal parameter which is a local variable, this change is confined to the method called and not to the current parameter of the caller. If, on the other hand, you change the values ​​in the location allocated to the object, these changes will be referenced both by the formal parameter and by the current one whose content is the same memory address, that is the reference to the memory location in which the object is contained. Moral: there is no passage by reference in Java https://code.sololearn.com/c0A21A1a8a23/?ref=app
10th Apr 2021, 12:17 AM
Ciro Pellegrino
Ciro Pellegrino - avatar
+ 1
You forgot to share your code bit link ☝
8th Apr 2021, 5:12 AM
Ipang
+ 1
Lol, I really forgot
8th Apr 2021, 3:16 PM
rajshekhar y dodamani
rajshekhar y dodamani - avatar
+ 1
Interesting case, So I searched for solutions, and saw most recommended way was to use Collections.swap() or use a wrapper class.
8th Apr 2021, 3:44 PM
Ipang
+ 1
I used wrapper class itself
8th Apr 2021, 3:59 PM
rajshekhar y dodamani
rajshekhar y dodamani - avatar
+ 1
because Integer is immutable, a = b creates new Integer object stored in the local variable a and is lost after return, try it by System.out.println(System.identityHashCode(a) );
9th Apr 2021, 5:02 AM
zemiak