This is a much-discussed topic in the Java field. However, so far I have found that many people have not figured it out (including myself, of course ). Until I read this articleArticle"Does Java pass by reference or pass by value? .
From this, I found a very interesting thing: graphics are more understandable and intuitive than text. In the above article, I think you only need to look at the figure (the painting is awesome) and you will be able to understand the principle.
For ease of understanding, I will give a general summary:
1. What are the differences between pass-by-reference and pass-by-value?
We recommend the following article "The reference is unknown", which is a clear explanation:What is pass by value? What is pass by reference? For example, pass by value is the "separation" of data, and pass by reference is the "original" of data.
2. pass-by-reference/value occurs only when the methods parameter is passed.
Everyone knows that all object variables in Java are reference, but this has nothing to do with what we call pass-by-reference/value. Pass-by-reference/value only appears in the method call, that is, the method parameters are passed through pass-by-reference or pass-by-value.
3. in Java, both pass-by-value methods are used to pass method parameters.
All parameters in Java are transmitted using pass-by-value, whether it is primitive type (INT, short, float, etc.) or objects.
4. differentiate mutable objects and immutable objects)
These two objects are very likely to cause misunderstanding. Let's look at the two examples below:
Ex 1:
Public class test {
Public static void test (string Str ){
STR = "world"; // 1
}
Public static void main (string [] ARGs ){
String string = "hello ";
Test (string );
System. Out. println (string );
}
}
Running result:
Hello
-----------------------------
Ex 2:
Public class test {
Public static void test (stringbuffer Str ){
Str. append (", world! "); // 2
}
Public static void main (string [] ARGs ){
Stringbuffer string = new stringbuffer ("hello ");
Test (string );
System. Out. println (string );
}
}
Running result:
Hello, world!
Why can one change, while the other cannot? In fact, this is a problem caused by immutable and mutable objects. According to the first article, you should easily understand that string is an immutable objectCodeThe STR variable at 1 has been changed to the reference (Value assignment statement is equivalent to new) pointing to another object, that is, it only modifies another object, and stringbuffer is a variable object, in code 2, it modifies the same object.