In java, I use a variable to temporarily store the value, but why does the temporary variable change after the original variable is changed?

I wrote a function, to move c such as abcd to the specified location, and the rest to an index
example: swap (abcd,2,0), then output-> cabd

the code is as follows

public class why {

  static public void main(String args[])
  {
      char[] chs = {"a","b","c","d"};
      sw( chs ,2 , 0 );
  }
  
  static public void sw(char chs[] , int i , int j)
  { 
          char [] tempchs = chs ; //abcdtempchs
          
          System.out.print("start ");
          System.out.println(tempchs);

/*-----------------------------------------------------*/

        char temp = chs[i];
        
        for(int k = i ; k>j ; k--)
        {            
            chs[k] = chs[k-1];                
        }
        
        chs[j] = temp ; 
        
 /*-----------------------------------------------------*/

         System.out.print("end ");
        System.out.println(tempchs);
        
  }

}

execution result
start abcd
end cabd

the question I want to ask is, before I entered function, I used tempchs to temporarily store the entered abcd, but when it successfully turned abcd into cabd, my tempchs changed?

the result of the change, shouldn"t it only change the chs itself?

Apr.12,2021

java is passed by reference by default. In the
code, "char [] tempchs = chs; / / storing abcd into tempchs" actually points chs and tempchs to the same memory area where the actual object is stored.

so the actual content changes, and so does the result of access by reference.

there are deep and shallow copies of this content, but it's really the difference between value passing and reference passing, and figuring out this will help you understand how java manipulates variables and uses memory.

if you want to achieve the desired effect, use the java.util.Array class
to change "char [] tempchs = chs; / / save abcd in tempchs"
to "char [] tempchs = Arrays.copyOf (chs, chs.length); / / save abcd in tempchs"

you can also refer to the source implementation of Arrays.copyOf to see how deep copies are handled.

Menu