Java parameter passing

Source: Internet
Author: User

1. Code examples
Basic types are passed as parameters
 Public class TestPass1 {    publicstaticvoid testpass (int  t) {        = 2 ;    }      Public Static void Main (string[] args) {        int t = 9;        System.out.println ("Before testpass:t =" + t);        Testpass (t);        System.out.println ("After testpass:t =" + t);}    }
Results:

Before testpass:t = 9

After Testpass:t = 9

Object is passed as a parameter
 Public class TestPass2 {    publicstaticvoid  testpass (StringBuffer strbuf) {        Strbuf.append ("World");    }      Public Static void Main (string[] args) {        new stringbuffer ("Hello");        System.out.println ("before Testpass:strbuf" + strbuf);        Testpass (STRBUF);        System.out.println ("after Testpass:strbuf" + strbuf);}    }
Results:

Before Testpass:strbuf Hello
After testpass:strbuf Hello World

Object is passed as a parameter
 Public classTESTPASS3 { Public Static voidTestpass (StringBuffer strbuf) {strbuf=NewStringBuffer ("World"); }     Public Static voidMain (string[] args) {StringBuffer strbuf=NewStringBuffer ("Hello"); System.out.println ("Before Testpass:strbuf" +strbuf);        Testpass (STRBUF); System.out.println ("After Testpass:strbuf" +strbuf); }}
Results

Before Testpass:strbuf Hello
After Testpass:strbuf hello

2. Analysis
1. The base type is stored in the stack in Java, and the value is stored directly. 2. The object type is stored in the heap in Java, but the address of the object is stored in the heap, and the value of the object is placed in memory. 3. So we can see from the above example: TestPass1 is passed the value, so does not change the TESTPASS2 is actually passed the address of the object, change the address point to the object, so it will change the TESTPASS3 is passed the address, but the address again point to the new object, So it doesn't change
.

Java parameter passing

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.