JAVA_SE basics -- 46. Reference data type variables. value exchange [exclusive in-depth analysis]

Source: Internet
Author: User

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.

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.