When passing an object as a parameter to a method, the link must be copied. Then why the output is 0 9 9 , and not 9 9 9 ? It turns out, s1 and s2 refer to different objects?

 public class Main { public static void main(String[] args) { Integer s = 0; foo(s, s = 9); System.out.println(s); } static void foo(Integer s1, Integer s2) { System.out.println(s1); System.out.println(s2); } } 

    2 answers 2

    The parameters are calculated from left to right, and therefore s1 and s2 refer to different objects. If you write

     foo(s = 9, s); 

    Then get 9 9 9 . Since in this case the operation = executed before the calculation of the second parameter. Your code is equivalent (except for the fact that there are no new variables):

     Integer s = 0; // "раскрыл скобки" для foo(s, s = 9); Integer old_s = s; s = 9; foo(old_s, s); // "раскрыл скобки" System.out.println(s); 
    • those. = creates a new object, and does not change the value of the old? - user232692
    • 2
      operation = changes the value of the variable to the left and returns the value of the expression to the right. so you can do it like this a = b = c = 123 - Mikhail Vaysman
    • it's good. The sequence of actions s=9 : 1) allocate memory for the int variable; 2) writing to it 9; 3) we assign THIS address to the reference variable s and it now points to a new memory area; 4) the garbage collector frees the old address? - user232692
    • 3 point autopacking - user232692
    • are you talking about int or integer? - Mikhail Vaysman

    This happens because you first send to the first argument, and in the second you override the variable by 9. You can override one and the same variable, unlimited count-one time, only if it is not final.

     Integer i = 1; i = i * 2; i = i + i; i-=1; 
    • By "override" is meant "I refer to a new object" or "I refer to an old modified object"? - user232692
    • You change the old one - or rather replace it with a new one with a new value, sometimes it is useful not to create a new object, we can do everything in one place and override it and do so much. how many operations will be needed. - And
    • in your example, how many addresses are used? - user232692