Deep understanding of Java reference types

Source: Internet
Author: User
Tags java reference

Deep understanding of Java reference types

types in Java can be categorized into two main categories: value types and reference types. A value type is a basic data type (such as int, double, and so on), whereas a reference type refers to all types except the basic variable type, such as the type defined by class. All types in memory are allocated a certain amount of storage space (parameters are allocated in the use of storage space, after the method call is completed, the storage space will disappear automatically), the basic variable type only a piece of storage space (allocated in the stack), and the reference type has two storage space ( A piece in the stack, a piece in the heap), in the function call when Java is a value or a reference, this estimate many people are now very confused, the following with graphics and code to explain:

In the reference type at the time of the argument is not allocated in the heap of memory to store the variable C point to the A (), but to a point to the same instance of a, this is the same as in C + + pointers, first declare the pointer variable a,b,c,d at the time of the parameter, let a point to the memory that C points to. It is obvious that references in Java are similar in principle to pointers in C + +, but remember that Java has no pointers, only references. Here are some specific code to discuss the reference:

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:

Package test;

Public class Test {

Exchange values for two variables

Public Static void Swap (int A,int b) {

int c=a;

A=b;

B=c;

System. out. println ("A:" +a);

System. out. println ("B:" +b);

}

Public Static void Main (string[] args) {

int c=10;

int d=20;

Swap (C,D);

System. out. println ("After Swap:");

System. out. println ("C:" +d);

System. out. println ("D:" +c);

}

}

Operation Result:

A:20

B:10

After Swap:

C:20

D:10

It is not difficult to see, although in the Swap (A, a) method changes the value of the passed in parameters, but the parameter source variable itself has no effect, that is, the main (string[]) method of the B variable has no effect. 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 the C + + language that indicates the 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 that requires a certain amount of memory (stack, stack space) to be saved. But their values are the same, indicating the location of the same object in memory (heap, heap space). Like what:

String a= "This is a text!";

String b=a;

It is not difficult to see from the above code and graphical examples that 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 "This is a text!". note, however, that 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).

, the value of start B is "Word" which the Green Line points to, then b=a; Make B point to Word that the red line points to.

Here I have described two points:

(1) A reference is a data type (stored in a stack) that holds the address of the object in memory (heap, stack space), 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?

As you learn, you may have questions about how objects are delivered, whether the object is passed by value or passed by reference?

(1) Considered to be "passed by value":

Package test;

Public class Test {

Public Static void Sample (int a) {

a+=20;

System. out. println ("A:" +a);

}

Public Static void Main (string[] args) {

int b=10;

Sample (b);

System. out. println ("B:" +b);

}

}

Operation Result:

A:30

B:10

In this code, modifying the value of variable A does not change the value of variable B, so it is "value passing".

(2) Deemed to be "passed by reference":

Package test;

Public class Test {

Public Static void Sample (StringBuffer a) {

A.append ("Changed");

System. out. println ("A:" +a);

}

Public Static void Main (string[] args) {

StringBuffer b=New StringBuffer ("This is a test!");

Sample (b);

System. out. println ("B:" +b);

}

}

Operation Result:

A:This is a test! Changed

B:this is a test! Changed

In the function of sample (StringBuffer), the value of reference A is modified, and the value of B also changes, so it is "passed by reference"!

So object (remember that everything in Java is an object, whether it's an int a or string A; The two variables a are objects) in what way are they passed? The answer can only be that it is passed by value and passed by reference, but usually the basic data type (such as int,double, etc.) we think is "value passing", and the custom data type (class) We think it is "reference passing".

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.

C A data type in a language is called a pointer, so when you pass a data as an argument to a function, there are two ways: pass a value, or pass a pointer. When a value is passed, modifying the value of a variable in a function does not change the value of the original variable, but it is changed by the pointer.

void Swap (int a,int b) {int c=a;a=b;b=c;}

void Swap (int *a,int *b) {int c=*a;*a=*b;*b=c;}

int c=10;

int d=20;

Swap (C,D); Does not change the value of C, D

Swap (&C,&D); Change the value of C, D

Many C programmers began to turn to Java, and they found that using a method like Swapvalue (t,t) (when T is a value type) still cannot change the value of a simple data type passed in by argument, but if T is a reference type, it may 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.

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? There are many ways to do this, and here's an easy way to do this:

Package test;

Public class Test {

Public Static void Swap (int[] a) {

int c=a[0];

A[0]=A[1];

A[1]=c;

}

Public Static void Main (string[] args) {

int [] a=new int[2];

a[0]=10;

a[1]=20;

Swap (a);

System. out. println (A[0]);

System. out. println (a[1]);

}

}

Arrays make it easy to exchange data sources for value types, but one way to do this is to encapsulate all the variables in a class and implement them by reference types.

Deep understanding of Java reference types

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.