About parameters for Java methods

Source: Internet
Author: User

Just see the function of C + +, that is, in C + + In addition to reference types of formal parameters, the other is a copy of the argument (personal summary).

Vaguely remember that the parameters of the method in Java are the same thing, so manual testing.

Results

The parameters of a method in Java are value passing , even if it is a reference type, and a copy of the reference itself (pointing to the same object) is passed.

Personally, it is easier to understand variables of reference types in Java as pointers.

Test code

Importorg.junit.Test; Public classtestfunction {@Test Public voidTestint () {intA = 3; intb = 4;        Swap (A, b); System.out.println (A+ "---" +b); } @Test Public voidteststring () {String a= "hehe"; String b= "What";        Swap (A, b); System.out.println (A+ "---" +b); } @Test Public voidTestinner () {Inner a=NewInner (); A.setage (10); Inner b=NewInner (); B.setage (20);        Swap (A, b); System.out.println (A.getage ()+ "---" +b.getage ()); }    /*** Basic type, is value passed, so the original object is not modified * *@paramA *@paramb*/     Public voidSwapintAintb) {a+=b; b= A-b; A-=b; }    /*** String is also value passed *@paramA *@paramb*/     Public voidSwap (String A, string b) {string TMP=A; A=b; b=tmp; }    /*** Reference, pass the reference itself, similar to the address.     So it's just a copy that doesn't affect the original value. * @paramA *@paramb*/     Public voidswap (Inner A, Inner b) {Inner tmp=A; A=b; b=tmp; }    /*** Inner class*/    classinner{Private intAge ;  Public voidSetage (intAge ) {             This. age=Age ; }         Public intGetage () {return  This. Age; }    }}

Add

Most of the time, we are using members of incoming objects (reference types), so this is not a problem. Because the referenced copy still points to the same object.

About parameters for Java methods

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.