+ 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
7 Answers
+ 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
+ 1
You forgot to share your code bit link â
+ 1
Lol, I really forgot
+ 1
Interesting case,
So I searched for solutions, and saw most recommended way was to use Collections.swap() or use a wrapper class.
+ 1
I used wrapper class itself
+ 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) );
0
No bro, not talking about the `Integer`.
https://www.geeksforgeeks.org/collections-swap-method-in-java-with-examples/
https://www.geeksforgeeks.org/swap-exchange-objects-java/