Java basics: whether to pass the value or reference in Java

Source: Internet
Author: User
Java basics: whether to pass the value or reference-Linux general technology-Linux programming and kernel information. The following is a detailed description. 1. Simple types are passed by value

When Java method parameters are of simple type, they are passed by value ). This can be illustrated through a simple example:

/* Example 1 */
/**
* @ (#) Test. java
* @ Author fancy
*/
Public class Test {
Public static void test (boolean test ){
Test =! Test;
System. out. println ("In test (boolean): test =" + test );
}
Public static void main (String [] args ){
Boolean test = true;
System. out. println ("Before test (boolean): test =" + test );
Test (test );
System. out. println ("After test (boolean): test =" + test );
}
}

Running result:

Before test (boolean): test = true
In test (boolean): test = false
After test (boolean): test = true

Although the value of the passed parameter is changed in the test (boolean) method, it does not affect the source variable of this parameter, that is, main (String []) the test variable in the method has no effect. It indicates that when the parameter type is simple, it is passed by value. When a simple type of variable is passed as a parameter, the parameter value is actually copied to the method function. How can we change the value in the method function, the result only changes the copied value, not the source value. 2. What is reference
In Java, whether to pass values or references is mainly due to the transfer of objects because simple types in Java are not referenced. Since the argument mentions the reference, we must know what the reference is to solve this problem.
To put it simply, a reference is like an object name or alias (alias). An object in the memory will request a space to store data. Based on the object size, it may take up different sizes of space. When accessing an object, we do not directly access the data of the object in the memory, but access it through reference. Reference is also a data type. We can think of it as something similar to a pointer in C language, it indicates the address of the object in the memory-but we cannot observe what the address is.
If we define more than one reference pointing to the same object, these references are different, because the reference is also a data type and requires a certain amount of memory space to save. But their values are the same, indicating the location of the same object in the memory. For example

String a = "Hello ";
String B =;

Here, a and B are two different references. We use two definition statements to define them. But their values are the same and all point to the same object "Hello ". Maybe you still think it is not intuitive, because the value of the String object itself cannot be changed (such as B = "World"; B =; this situation does not change the value of the "World" object, but changes the value of its reference B to point to another String object ). Let's use StringBuffer as an example:

/* Example 2 */
/**
* @ (#) Test. java
* @ Author fancy
*/
Public class Test {
Public static void main (String [] args ){
StringBuffer a = new StringBuffer ("Hello ");
StringBuffer B =;
B. append (", World ");
System. out. println ("a is" + );
}
}

Running result:

A is Hello, World

In this example, both a and B are referenced. When the value of the object indicated by B is changed, the value of the object indicated by a is also changed from the output result. Therefore, both a and B point to the same object, that is, a StringBuffer object containing "Hello.

Here I have described two key points:

1. Reference is a data type that stores the address of the object in the memory. This type is not a simple data type that we usually call or a class instance (object );
2. Different references may point to the same object. In other words, an object can have multiple references, that is, variables of this type.
3. How are objects transmitted?
There are two ways to pass an object: "It is passed by value" and "it is passed by reference ". These two statements have their own principles, but they are not analyzed in essence, which leads to a debate. Now that we know what a reference is, we can analyze how an object is transmitted as a parameter. Take a program as an example:

/* Example 3 */
/**
* @ (#) Test. java
* @ Author fancy
*/
Public class Test {
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 );
}
}

Running result:

Hello, World!

Test (string) calls the test (StringBuffer) method and passes the string as a parameter. Here, string is a reference, which is beyond doubt. As mentioned above, reference is a data type and is not an object, so it cannot be passed by reference. So it is passed by value. What is its value? Is the object address.
It can be seen that objects are passed by value as parameters, right? Error! Why is the error? Let's look at another example:

/* Example 4 */
/**
* @ (#) Test. java
* @ Author fancy
*/
Public class Test {
Public static void test (String str ){
Str = "World ";
}
Public static void main (String [] args ){
String string = "Hello ";
Test (string );
System. out. println (string );
}
}

Running result:

Hello

Why? Because the str parameter is a reference, and it is different from the string parameter, although they are all references of the same object. Str = "World" changes the value of str to point to another object. However, the object indicated by str has changed, but it does not affect "Hello, in addition, because the string and str are different references, the change of str does not affect the string, as shown in the example.
The result is the argument that the parameter is passed by value. So, when an object is used as a parameter, it is passed by reference? Also wrong! Because the previous example does show that it is passed by value.
As a result, just like the question of whether the light is a wave or a particle, the answer to the question of passing parameters in the Java method can only be: passing by value is also passed by reference, the results are different only when the reference object is different.

4. correctly view the problem of passing a value or passing a reference
To view the problem correctly, you must understand why such a problem occurs.
In fact, the problem comes from C rather than Java.
In C, there is a data type called pointer, so when a data is passed to a function as a parameter, there are two ways: Pass the value, or pass the pointer, their difference, you can use a simple example:/* Example 5 */

/**
* @ (#) Test. c
* @ Author fancy
*/
Void Swapvalue (int a, int B ){
Int t =;
A = B;
B = t;
}
Void SwapPointer (int * a, int * B ){
Int t = *;
* A = * B;
* B = t;
}
Void main (){
Int a = 0, B = 1;
Printf ("1: a = % d, B = % d \ n", a, B );
Swapvalue (a, B );
Printf ("2: a = % d, B = % d \ n", a, B );
SwapPointer (& a, & B );
Printf ("3: a = % d, B = % d \ n", a, B );
}

Running result:

1: a = 0, B = 1
2: a = 0, B = 1
3: a = 1, B = 0

As you can see, passing parameters by pointer can easily modify the values passed in through parameters, but passing by value won't work.
When Java grew up, many C programmers started to learn Java. They found that using methods similar to Swapvalue still cannot change the values of simple data types passed through parameters, however, if it is an object, its members may be changed at will. So they thought it was like a problem of passing values/pointers in C. But Java does not have pointers, so this problem becomes a problem of passing values/passing references. Unfortunately, it is not appropriate to discuss this issue in Java.
The final purpose of discussing such a problem is to figure out the situation in which we can conveniently change the parameter value in the method function and make it valid for a long time.

In Java, there are two ways to change the value of a parameter. First, use the "=" value assignment to directly change the value, such as Example 1 and Example 4. Second, for reference of some objects, change the member data through a certain channel, such as example 3. In the first case, the change does not affect data other than the method, or the source data. The second method, on the contrary, will affect the source data-because the object indicated by the reference has not changed, changing its member data is essentially changing the object.
5. How to Implement methods similar to swap
If I have two int-type variables a and B, what should I do if I want to write a method to exchange their values?
The conclusion is disappointing-no way! Therefore, we can only discuss the specific situation. Take the sorting of frequently used exchange methods as an example:

/** Example 6 */
/**
* @ (#) Test. java
* @ Author fancy
*/
Public class Test {
Public static void swap (int [] data, int a, int B ){
Int t = data [a];
Data [a] = data ;
Data= T;
}
Public static void main (String [] args ){
Int [] data = new int [10];
For (int I = 0; I <10; I ++ ){
Data= (Int) (Math. random () * 100 );
System. out. print ("" + data);
}
System. out. println ();
For (int I = 0; I <9; I ++ ){
For (int j = I; j <10; j ++ ){
If (data> Data [j]) {
Swap (data, I, j );
}
}
}
For (int I = 0; I <10; I ++ ){
System. out. print ("" + data);
}
System. out. println ();
}
}

Running result (Case 1 ):

78 69 94 38 95 31 50 97 84 1
1 31 38 50 69 78 84 94 95 97

The swap (int [] data, int a, int B) method actually changes the member data of the object indicated by data internally, that is, the second method to change the parameter value discussed above. I hope you can solve the problem in a similar way.

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.