Whether to pass a value or reference a Java Parameter

Source: Internet
Author: User

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. A reference is a data type that stores the address of an 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, A simple example is provided:

/* 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 [B];
Data [B] = T;
}
Public static void main (string [] ARGs ){
Int [] DATA = new int [10];
For (INT I = 0; I <10; I ++ ){
Data [I] = (INT) (math. Random () * 100 );
System. Out. Print ("" + data [I]);
}
System. Out. println ();
For (INT I = 0; I <9; I ++ ){
For (Int J = I; j <10; j ++ ){
If (data [I]> data [J]) {
Swap (data, I, j );
}
}
}
For (INT I = 0; I <10; I ++ ){
System. Out. Print ("" + data [I]);
}
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.

Related Article

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.