JAVA_SE basics -- 46. Reference data type variables. value exchange [exclusive in-depth analysis]
Requirement: Define the positions of two elements in a function exchange array.
Code 1:
Import java. util. *; class Demo3 {public static void main (String [] args) {// create an int-type array int [] arr = {10, 20, 30, 40}; System. out. println (before the exchange value: + Arrays. toString (arr); // The Badge 0 and 1 changeValue (arr,) in the arr array; System. out. println (after the exchange value: + Arrays. toString (arr);} // value exchange in the array public static void changeValue (int [] arr, int index1, int index2) {int temp = arr [index1]; arr [index1] = arr [index2]; arr [index2] = temp ;}}
Do you think that the exchange value is successful ???
Code 1: running result:
The final result is different from what you think ~... . . But the result is: the exchange value is successful.
Next we will understand the memory diagram.
A graphic is suspect, unless you cannot understand
Cause analysis: the main () method and changeValue () method operate on the same object. The operation is the same Array object. Therefore, the exchange value is successful.