JAVA method of parameter by value, pass problems cited

Let me talk about the conclusion:

JAVA only by value, is not passed by reference

 

Some junior partner mistakenly thought it was rumored references, because:

Look at a few examples:

Example 1 :

result:

Resolution:

 

example 1

in the swap process, a, b values are exchanged, and does not affect num1, num2. Because, a, b values of only from num1, num2 is copied. That is, a, b content equivalent num1, num2 a copy of a copy no matter how the changes will not affect the original itself.
By way of example above, we know a method can not modify a basic data type parameter, and the object is not the same as a parameter reference, see example2.
Example 2

result:

Resolution:

Before exchange:

2 Example

array is initialized copy of arr is an object reference, that is to say when the same array and a pointing arr array object. Therefore, the external change of the reference object will be reflected in the corresponding object.
By example2 We have seen a change in implementation status of the object parameter is not a difficult task. The reason is simple, the method is to get a copy of the referenced object, object references and references to other copies of the same object at the same time.
Many programming languages (in particular, C ++ and Pascal) offers two ways parameters are passed: the value of calls and call references. Some programmers consider Java programming language is a reference to an object used to call, in fact, this understanding is wrong. Because of this misunderstanding has a certain universality, it is a counter-example is given below in detail with elaborate the problem.

example 3

result:

Analysis:

Before the exchange:

After the exchange:

It can be clearly seen from the above two pictures:  the method does not change the object stored in the variable in the referenced s1 and s2. parameters x and y swap method is initialized to the two copies of the referenced object, this method is that the two copies of the exchange

 

reference:

https://zhuanlan.zhihu.com/p/101328868

《JAVA核心技术卷一》

 

发布了161 篇原创文章 · 获赞 71 · 访问量 11万+

Guess you like

Origin blog.csdn.net/yxpandjay/article/details/103953643