"Reprint" Whether Java is a value or a reference

Source: Internet
Author: User

1. Simple types are passed by value

The Java method's arguments are simple types, which are passed by value (pass by value). This can be explained by a simple example:

/ * Example 1 * //*** @ (#) Test.java* @author Fancy */ Public classTest { Public Static voidTestBooleanTest) {test =! Test; System.out.println ("in Test (Boolean): Test ="+ test); } Public Static voidMain (string[] args) {BooleanTest = true; System.out.println ("Before Test (Boolean): Test ="+ test);        Test (test); System.out.println ("After Test (Boolean): Test ="+ test); }}

Operation Result:

before Test (Boolean): Test = True
In Test (Boolean): Test = False
After Test (Boolean): Test = True

It is not difficult to see that although the value of the passed parameter has been changed in the test (Boolean) method, there is no effect on the parameter source variable itself, that is, the test variable in the main (string[]) method. That means that when the parameter type is a simple type, it is passed by value. When passing a variable of a simple type in the form of a parameter, the value of the parameter is actually passed into the method function, then how to change its value in the method function, the result is to change only the copy value, not the source value.

  2. What is a reference

Whether Java is a value or a reference, the problem is mainly on the object's delivery, because the simple type in Java does not have a reference. Since the argument mentions the reference to this thing, in order to understand the problem, we have to know what the reference is.

Simply put, a reference is like the name or alias of an object, and an object in memory requests a piece of space to hold the data, depending on the size of the object, it may need to occupy a different amount of space. When accessing an object, we do not directly access the object's in-memory data, but instead access it by reference. A reference is also a data type, and we can think of it as something like a pointer in C, which indicates an object's address in memory--except that we can't see what the address is.

If we define more than one reference to the same object, then these references are not the same, because the reference is also a data type and requires a certain amount of memory space to be saved. But their values are the same, indicating that the same object is in the memory position. Like what

String a = "Hello";
String B = A;

Here, A and B are different two references, and we use two definition statements to define them. But their values are the same, pointing to the same object "Hello". You may also find it not intuitive because the value of the String object itself is immutable (like B = "world"; b = A; This is not a change to the value of the "World" object, but instead it changes the value of its reference B to another string object, a). So let's use StringBuffer to give an example:

/ * Example 2 * / /** * @ (#) Test.java * @author Fancy  */  Public class Test {public    staticvoid main (string[] args) {        new StringBuffer ("Hello");        StringBuffer B = A;        B.append (", World");        System.out.println ("A is" + a);}    }

Operation Result:

A is Hello, the
world

In this example, both A and B are references, and when the value of the object indicated by B is changed, the value of the object indicated by a is changed from the output result. So both A and B point to the same object, which is a StringBuffer object that contains "Hello".

Here I have described two points:

    1. A reference is a data type that holds the address of an object in memory, which is not the simple data type that we normally call or the class instance (object);
    2. Different references may point to the same object, in other words, an object can have more than one reference, that is, a variable of that class type.

  3. How are the objects delivered?

There are two ways of saying that objects are passed, that is, "it is passed by value" and "it is passed by reference". Each of these two arguments has its own rationale, but they are not analyzed in nature, which is caused by controversy.

Now that we know what the reference is, it's time to analyze how the object is passed as a parameter. Let's take a program as an example:

/ * Example 3 * / /** * @ (#) Test.java * @author Fancy  */  Public class Test {public    staticvoid Test (stringbuffer str) {        str.append (", World !");    }     Public Static void Main (string[] args) {        new StringBuffer ("Hello");        Test (string);        System.out.println (string);}    }

Operation Result:

Hello, world!.

Test (string) called the test (StringBuffer) method and passed the string as a parameter. Here the string is a reference, which is unquestionable. As mentioned earlier, a reference is a data type and not an object, so it is not possible to pass by reference, so it is passed by value, what is its value? Is the address of the object.

This shows that the object is passed by value when it is a parameter, right? Wrong! Why wrong, let's look at another example:

/ * Example 4 * / /** * @ (#) Test.java * @author Fancy  */  Public class Test {public    staticvoid Test (String str) {        ' world ';    }     Public Static void Main (string[] args) {        "Hello";        Test (string);        System.out.println (string);}    }

Operation Result:

Hello

Why is that? Because the parameter str is a reference, and it is different from string references, although they are all references to the same object. str = "World" Changes the value of STR to another object, but the object that Str points to changes, but it does not have any effect on "Hello", and because string and Str are different references, the change of STR does not cause any The results as shown in the example.

The result is a reversal of the argument's passing by value. So, is the object passed by reference when it is a parameter? Also wrong! Because the previous example does show that it is passed by value.

As a result, just as the light is the problem of waves or particles, the Java method's parameters are the question of what to pass, and the answer can only be: that is, by value is passed by reference, but with different references, the results are different.

  4. Correct view of the issue of the value of the pass or the reference

To look at the problem correctly, we have to figure out why there is such a problem.

In fact, the problem stems from C, not Java.

There is a data type in C that is called a pointer, so when you pass a data as a parameter to a function, there are two ways: pass the value, or pass the pointer, their difference, can use a simple example to illustrate:

/ * Example 5 * //*** @ (#) test.c* @author Fancy */voidSwapvalue (intAintb) {intt = A;    A = b; b = t;}voidSwappointer (intAint* b) {intt = * A;    * a = * b; * b = t;}voidMain () {intA =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);}

Operation Result:

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

As you can see clearly, passing parameters by pointer can easily modify the values passed in through the parameters, but not by value.

As Java grew, many C programmers began to turn to Java, and they found that using a swapvalue-like approach still did not change the values of the simple data types passed in by parameters, but if it was an object, it might change its members arbitrarily. So they think it's a lot like the C language, the problem of passing the value/pointer. However, there are no pointers in Java, so this problem has evolved into a value/pass-through reference problem. Unfortunately, it is not appropriate to put this issue in Java for discussion.

The ultimate goal of discussing such a problem is simply to figure out what is the most convenient way to change the value of a parameter in a method function and make it work long-term.

In Java, there are two cases of changing the value of the parameter, the first, using the assignment number "=" to directly assign the value to change it, such as Example 1 and Example 4, and the second, for some object reference, through a certain way to change its member data, such as Example 3. In the first case, the change does not affect the method's data other than that of the method, or it directly says the source data. The second method, in contrast, affects the source data-because the object referenced by the reference does not change, and the change to its member data is essentially the object that is changed.

5. How to implement a swap-like approach

The question of whether to pass a value or to refer to it has been solved, but we still cannot solve the problem: if I have two variables A and b of int, I want to write a method to exchange their values, what should I do?

The conclusion is disappointing-there is no way! Therefore, we can only discuss the specific situation, with the usual use of the exchange method of sorting as an example:

/** Example 6 * //*** @ (#) Test.java* @author Fancy */ Public classTest { Public Static voidSwapint[] Data,intAintb) {intt = Data[a];        Data[a] = data[b];    DATA[B] = t; } Public Static voidMain (string[] args) {int[] data =New int[Ten]; for(inti =0; I <Ten; i++) {Data[i] = (int) (Math.random () * -); System.out.print (" "+ data[i]); } System.out.println (); for(inti =0; I <9; i++) { for(intj = i; J <Ten; J + +) {if(Data[i] > Data[j])                {Swap (data, I, j); }            }        } for(inti =0; I <Ten; i++) {System.out.print (" "+ data[i]);    } System.out.println (); }}

Run results (one of the conditions):

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

The swap (int[] data, int a, int b) method internally actually alters the member data of the object indicated by data, the second method of changing the value of the parameter as discussed above. I hope you can extrapolate and use similar methods to solve related problems.

"Reprint" Whether Java is a value or a reference

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.