Getting Started with Java Learning: Method parameter transfer (function transfer problem)

Source: Internet
Author: User

Introduction: We know that C + + has two parameter passing methods, value invocation and reference invocation. Some programmers think that the Java programming language uses reference calls to objects, which in fact are not.

Because of the universality of this misunderstanding, the question is described below.

So use a simple code to illustrate the problem:

1     //If the method parameter is a reference to the input, then we will exchange two pointers (that is, references)2      Public Static voidSwap (employee x, employee y)3     {4Employee temp =x;5x =y;6y =temp;7     }8     9     TenEmployee A =NewEmployee ("Alice", 5000); OneEmployee B =NewEmployee ("Trcy", 5000); A      -  -Swap (A, b);//In fact, there is only one pass-through value Pass in Java, except that the copy is a reference, and the copy version of the reference is still pointing to the original object. 

Summary: After the exchange we expect the result should be, a refers to Trcy, b refers to Alice, but the result is not

1 Alice 2 Trcy

Print the result, a still references Alice, B still references Trcy. It shows that swap is closely swapping two copies.

With the end of the swap method call, the memory of the two copies is freed, and the swap does no work;

From Java Core technology:

1. A method cannot modify a parameter of a basic data parameter type (built-in type, Boolean value)

2. A method can modify the state of an object parameter.

3. A method cannot modify an object parameter to refer to a new object.

Getting Started with Java Learning: Method parameter transfer (function transfer problem)

Related Article

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.