All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are. (Excerpt from references Alaxy.com:8080/interview/index.jsp? INTV=18)
The parameters of all methods in
Java are passed values. However, Java does manipulate objects by reference, and all object variables themselves are references.
originally all methods are passed values, there is no reference to the said!
give a few examples to see:
Example 1:
public class TestRef1 {
public static void Test (StringBuffer str) {
str = new StringBuffer (", world!");
}
public static void Main (string[] args) {
StringBuffer string = new StringBuffer ("Hello");
test (string);
System.out.println (string);
}
}
Run Result: Hello
Example 2:
public class TestRef2 {
public static void Test (String str) {
str = ", world!";
}
public static void Main (string[] args) {
string = new String ("Hello");
test (string);
System.out.println (string);
}
}
Run Result: Hello
Example 3:
public class TestRef3 {
public static void Test (StringBuffer str) {
str.append (", world!");
}
public static void Main (string[] args) {
StringBuffer string = new StringBuffer ("Hello");
test (string);
System.out.println (string);
}
Run Result: Hello, world!
first of all I think: The above three examples are the values, no reference.
Second, we think:
1, different references can point to the same object;
2, the value of the String object itself is immutable (like B = "world"; b = A; this does not change the value of the object of "world", but rather changes the value of its reference B to point to another String object a);
3, "=" is an assignment operator. The assignment modifies the object reference, not the object itself.
according to the above,
1, str = ", world!"; and str = new StringBuffer (", world!"); are assignment operations that modify the reference of the object Str to point to a new object without changing the object itself (here is ", world!" and new StringBuffer (", world!") )。 So string is not affected by it.
2, Str.append (", world!"); This changes the object itself, not the object reference.
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