Passing problems by value and by reference in Java

Source: Internet
Author: User

It is important to believe that this is a problem for many beginners of Java, because unlike C,c++,java it is clear that pointers are removed because pointers tend to be more convenient and cause code insecurity, and make programs very complex and difficult to understand. Java Discard pointers simply do not have a clear pointer definition in the Java language, essentially, each new statement returns a reference to a pointer. But most of the time, Java does not care how to manipulate the "pointer", much less like in the operation of C + + pointers as scary, the only thing to pay more attention to when the function is passed the object. So, beginners of Java don't have to spend too much effort to understand, but for a real Java programmer This problem is the foundation. Talk less, go straight to the chase:

is it a value or a reference in Java?

The question is as divergent as the question of whether light is a wave or a particle. But first, let's be clear: regardless of the type of Java parameter, pass a copy of the parameter (reference thinking in Java): When you ' re passing primitives into a method, you get a dis TINCT copy of the primitive. When you ' re passing a reference to a method, you get a copy of the reference).

The variables in Java are divided into the following two categories:

(1) Basic type variables (int,long,double,boolean,float, Byte,char), for these variables, Java is passing a copy of the value (same as C + +), that is, assigning itself to a copy of the transfer, even if their own copies of the changes, they will not change;

(2) Object type variable. Java passes a copy of the reference (copying a pointer to an address) rather than a copy of its own actual value. Why do you do this? The reason is simple because the object type is placed inside the heap (when the new object is actually a memory space in the heap to hold the object, the pointer to the object in the stack), so access to the object in the heap is slower than the basic type data, on the other hand because the object type itself is relatively large, If you use the method of copying object values, you not only waste memory but also slow.

This is explained in the thinking in Java: Whether it is a primitive type or an object type, it is a pass value. This argument is to refer to the copy also as a "value", but also can say the past, but I still prefer to pass by value and by reference to pass separate better understanding.

Note: The string type in Java is also an object-type variable, so it passes a copy of the reference. String is a non-mutable class, and its value or pass-through is no different.


The theory is done, here are a few examples:

NUM1: basic type of transmission

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);

}


}


Operation Result:

Before Test (Boolean): Test = True

In Test (Boolean): Test = false//passed in a copy of the Boolean type, the copy changed but the original value does not change

After Test (Boolean): Test = True

NUM2: Passing Object types

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! The object is modified by referencing the copy to find the address and then modifying the value inside.

NUM3: About passing string

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);

}


}

A glance at the output should be: World

But the actual result is: Hello,string is not passed by reference? Did something go wrong?

Check for the following reasons:

Execute str = "world"; in this sentence, the system automatically generates a new string object, sets the value of the new object to "world", and assigns the reference to the STR,STR as a copy of the original string, changing the value of the copy. Then it is not related to the original value. When the test function is executed, STR is released with no changes to the contents of the original memory address. So the output hello,num2 in Str.append (", world!"); is not the same, StringBuffer is to produce a piece of memory space, related to the increment, delete, change operations are in it, so this sentence is in the same memory, that is, modified the original value, Str pointed to the reference has not changed.

The level is limited, hope the great God to give a supplement, Thank you!

This article is from the "Development communication, Common progress" blog, please be sure to keep this source http://smile2015.blog.51cto.com/9250194/1629685

Passing problems by value and by reference in Java

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.