Java Value Delivery

Source: Internet
Author: User

Do you really understand the value-passing of Java? What is the value of the value that is passed in Java? If it is a basic data type. You may have answered very simply. But what if it's an object? Are you sure you're clear? Look at code first.

Java code

 PackageCom.basic;  Public classTest {/**         * @paramargs*/         Public Static voidMain (string[] args) {StringBuffer buffer=NewStringBuffer ("Colin");             Schange (buffer);         SYSTEM.OUT.PRINTLN (buffer); }                   Public Static voidSchange (stringbuffer str) {str=NewStringBuffer ("Huang"); }         }   

What is the result of the above code? Are you right?

The result of the output is Colin.

Let's change the code.

Java code

 PackageCom.basic;  Public classTest {/**         * @paramargs*/         Public Static voidMain (string[] args) {StringBuffer buffer=NewStringBuffer ("Colin");             Schange (buffer);         SYSTEM.OUT.PRINTLN (buffer); }                   Public Static voidSchange (StringBuffer str) {//str= New StringBuffer ("Huang"); Str.append ("Huang"); }         }

The result of the output is Colin Huang.

Why is this the result? Explained in detail below:

Java does use references to maintain object, and all object variables are a reference. But in the method pass, Java is indeed a value pass. What is the value of that? For object, this value is a reference to the object of the descendant. Copy a copy of this quote. Then, at least two references point to the same incoming object. Reference:

So, let's figure out the two codes above.

Schematic code One

Then the schematic code two

In code one, copy's reference, which points to a new object. But the original object is still unchanged.

In code two, copy of the reference, the original object changed.

This is the value pass for Java.

Java Value Delivery

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.