Transferred from: http://developer.51cto.com/art/201104/254715.htm
Is Java really a value or a reference? It is believed that very few people can answer correctly. The general argument is that for the basic data type (integer, float, character, Boolean, etc.), the value is passed, and for reference types (objects, arrays), a reference is passed. The basic type is passed, and no one has any doubts about it; the problem is on the reference type.
In order to introduce the topic, may wish to take a look at the following example, you can correctly give the results of the program run?
- /**
- * @ (#) Swap.java
- *
- *
- * @author
- * @version 1.00 2007/1/5
- */
- public class Swap {
- Public Swap () {}
- public static void Main (string[] args) {
- Changer C = new Changer ();
- String stra = "Mighty";
- String strb = "Mouse";
- C.swap (Stra, STRB);
- System.out.println (stra + "" + strb);
- string[] Strarr = new string[ 2];
- strarr[ 0] = stra;
- strarr[ 1] = STRB;
- C.swap (Strarr);
- System.out.println (strarr[ 0] + "" + strarr[ 1]);
- }
- static class Changer {
- Public < T > void Swap (t A, T b) {
- T temp = A;
- A = b;
- b = temp;
- }
- Public < T > void Swap (t[] t) {
- if (T.length < 2) {
- System.out.println ( "error!");
- return;
- }
- T temp = t[ 0];
- t[ 0] = t[ 1];
- t[ 1] = temp;
- }
- }
- }
The correct operation result of the above program is:
Mighty Mouse
Mouse Mighty
Are you correct?
Let's analyze: Why do the above results appear?
To analyze this problem, we must have some knowledge of the layout of the data in the program in memory. There are 3 variables related to string in the main program above, and the layout can be as follows:
When the swap (stra, STRB) function is called, the copy value of the reference type Stra, STRB is passed, so any changes to the parameters in the function do not affect the values of stra and strb, whereas when the swap (Strarr) is called, the Strarr copy value is passed. Any changes to the parameters in the program still do not affect the value of the Strarr, but the change in swap (t[] T) is not the value of Strarr, but the value of strarr[0] and strarr[1, which is the value of the object pointed to by the reference type Strarr, thus strarr[ 0] and the value of strarr[1] has changed.
From the above analysis, we can conclude that, for reference types, arguments are still passed by value, but it is not entirely unreasonable to pass by reference, except that the reference object is not the reference type itself, but rather the object that the reference type points to.
Java Classic question: value and pass-through?