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