When Java passes a parameter, the difference between the value of the pass and the reference

Source: Internet
Author: User

Reprint please indicate source, original address: http://blog.csdn.net/h28496/article/details/44732713

Learning Zhenghaipeng in PKU


When I recently reviewed the nine sorting algorithms, unexpected discoveries were made by bubbling sort, inserting sort, selecting sort, etc. in-place sort,

Sort (a);
The output of A is a new array already lined up.

However, sort (a) is used when sorting by Out-place and so on. After that, the output is still the original array!

Why is it? Please look at the code and the comments inside:


Package Zhp.outplace_sort;import ZHP. Tools;public class Test {public static void main (string[] args) {int[] A1 = {1, 2, 3, 4, 5};int[] A2 = {1, 2, 3, 4, 5};F1 ( A1); F2 (A2); Tools.print (A1); Output array tools.print (A2);} /** * Method Changes the value of the parameter (in the original memory unit operation), after the method ends the parameter value is changed. */public static void F1 (int[] a) {for (int i = 0; i < a.length; i++) {a[i]++;}} /** * After the parameter points to a new address in the method, the parameter will still point to the original address after the method ends. */public static void F2 (int[] a) {a = new int[]{2, 3, 4, 5, 6}}

Output:

2 3 4) 5 6
1 2 3) 4 5


Got it.



When Java passes a parameter, the difference between the value of the pass and the reference

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.