+ 2
Why are object references different after assignment in a static method?
Why a1==a2 is true after assignment a1=a2 in the main method, but a1==a2 returns false if we do the same in another static method m? https://code.sololearn.com/cFFq9ZKjzhuZ/?ref=app https://code.sololearn.com/cJk1103IX86a/?ref=app
5 ответов
+ 2
Ada-
Your understanding is correct. The link below is a very good explanation of how Java passes objects.
https://stackoverflow.com/questions/7893492/is-java-really-passing-objects-by-value
+ 2
Ada yes! Java is pass by value so what you've done it reassigned the parameter a1 to something else, the original a1 that you passed in is unaffected
(be careful if you modify the parameter directly, by modifying attributes or calling certain methods - we still have the reference of the object and can mutate it, we jusy can't reassign or swap the real object in that method)
+ 1
Ada-
Yes, the method m assigns a2 to a1 but the main method does not see that.
The print statement and the method m (a1=a2) are not in the same scope,
hence the false result.
See link below, I think it will make things clearer than my writing.
https://code.sololearn.com/cIl7kl465Iqo/#java
0
Thank you ODLNT for the explanation. Is my understanding correct, that a1=a2 inside m is the modification of parameter a1, not the initial a1 variable in main method?
0
thank you very much!