Is Java passed by value or by reference?

Source: Internet
Author: User
Tags float double

Original: http://topic.csdn.net/t/20060605/13/4801113.html

 

(Unagain)

 

I recently read a post and asked "is Java passed by value or by reference ?". I thought it was quite simple. To be more accurate, I also looked at langspec3.0 on this issue. I wrote this article at a glance.

I am not sure whether my point of view is correct, so I am posting it here and hope you can discuss it together.

In addition, it is better to paste it on a blog.
Http://blog.csdn.net/UnAgain/archive/2006/06/05/774039.aspx

1. Data Type
1.1 primitivetype (simple type)
1.2 referencetype (reference type)
2. Variables
2.1 simple type variables
2.2 reference type variable
3. Assignment and transfer
3.1 assignment of Objects
3.2 Transfer
3.3 can the final variable be changed?
3.4 assignment and transfer of packaging classes

1. Data Type
Java has two types of data:
Primitivetype (simple type)
Referencetype (reference type)

1.1 primitivetype (simple type)
(Reference: langspec-3.0/typesvalues.html #4.2)

Primitivetype is classified as follows:

Primitivetype:
Numerictype
Boolean

Numerictype:
Integraltype
Floatingpointtype

Integraltype: one
Byte short int long char

Floatingpointtype: one
Float double

Primitivetype is a predefined Java type and is named using reserved words. Such as int, long, and float. Therefore, its packaging class is not primitivetype.
1.2 referencetype (reference type)
(Reference: langspec-3.0/typesvalues.html #4.3)
Referencetype has three types: Class, interface, and array.

2. Variables
(Reference: langspec-3.0/typesvalues.html #4.12)
A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type (§ 4. 2) or a reference type (§ 4. 3 ).
A variable is a storage unit associated with a specific type. The associated type is sometimes called the compile-time type of the variable, that is, it can be either a simple type or a reference type.
2.1 simple type variables
A variable of a primitive type always holds a value of that exact primitive type.
Variables of the simple type always hold values of the simple type.
2.2 reference type variable
A variable of a class type T can hold a null reference or a reference to an instance of class T or of any class that is a subclass of T. A variable of an interface type can hold a null reference or a reference to any instance of any class that implements the interface.

Variables of the class t can hold null references, or instance references of the class T and its subclass. Variables of the interface type can hold null references, or any instance reference of classes that implement this interface.

Note: Unlike langspec2.0, 3.0 introduces the concept of generic type, which includes the concept of type variable. The above T is a type variable.
3. Assignment and transfer
As mentioned above, the following conclusions can be drawn:
1) values assigned to simple type variables are passed by value. That is to say, the value is directly stored in the storage unit of the variable.
2) For variables of the reference type, the value assignment is to store the reference of the original object (which can be understood as the entry address) in the storage unit of the variable.
3.1 assignment of Objects
Assignment of simple types is easy to understand. Here we only discuss the assignment of objects. All instances of the reference type are the objects we often call.
In this case, except null, the initial value assignment of any variable is divided into two steps:
1) create an object instance
2) Assign the reference of the object instance to the variable.

For example:
Object O1 = new object ();
3.2 Transfer
The transfer is implemented by assigning values between variables. In the previous post, I said this sentence. From the perspective of variables, the value assignment between variables is a value transfer. Now let me explain my point of view.

Here is an example:
// The base class of all classes in Java is object by default, which is not described here.
Class object1 {}
Class object2 {}

Object O1, O2;

O1 = new object1 ();

O2 = O1;
O2 = new object2 ();

At this time, what is the type of O1? Is it object1 or object2? The correct answer is object1.
Another example:
Class word {
String word;
Public word (string word ){
This. Word = word;
}
Public void print (){
System. Out. println (Word );
}
}

Word O1, O2;

O1 = New Word ("every day ");

O2 = O1;
O2 = New Word ("every night! ");

W1.print ();

What will happen? "Every day" or "every night! "? It is still "every day ".

There is a point that many people, especially beginners, ignore-variables can reference objects, but variables are not objects. What is an object? After the object is initialized, it will occupy a piece of memory space. Strictly speaking, this section of memory space is the object. Objects are created in data segments, while variables exist in code segments. object entry addresses are unpredictable, so programs can only access objects through variables.

Let's go back to our question. First sentence
O1 = New Word ("every day ");
Create a word instance, that is, an object, and assign "Reference" to O1.
Second sentence
O2 = O1;
O1 assigns an object reference to O2. Note that the assigned value is an object reference rather than a reference of O1. Therefore
O2 = New Word ("every night! ");
Create a new object and assign the reference value of the new object to O2.

Because there is a value transfer between O1 and O2, the change to O2 will not affect O1 at all.

There is also a situation that seems to have affected O1. Let's continue with the above example and add a method to word.
Class word {
String word;
Public word (string word ){
This. Word = word;
}
Public void print (){
System. Out. println (Word );
}
Public void setword (string word ){
This. Word = word;
}
}

Word O1, O2;

O1 = New Word ("every day ");
O2 = O1;
O2.set Word ("every night! ");

O1.print ();

The result is "every night! ".

So, does this change O1? Strictly speaking, no. Because O1 only saves the object reference, O1 still holds the object reference after execution. So O1 is not changed. It is changed to the object referenced by O1.
3.3 can the final variable be changed?
Now, let me explain the following questions:

Final Word O3 = New Word ("every day! ");
O3.setword ("every night! ");

Can it be compiled? As we all know about the final definition, O3 is equivalent to a constant. Since it is a constant, how can it be changed?
The answer is yes, yes. I think everyone understands the truth.
3.4 assignment and transfer of packaging classes
As I have read in the past, the basic java types and their packaging classes are passed by values, and the objects are passed by reference. From the langspec perspective, the packaging class is not primitivetype, so it can only be referencetype, while the referencetype variable stores references. Since a reference is saved, a value cannot be passed. So, are these two ideas contradictory?

First, langspec is correct.
Secondly, although the previous point of view is incorrect in principle, it does not affect normal use.

Why is this happening? This is because these packaging classes have a simple type of feature that cannot be changed. Taking string as an example, let's take a look at API specification and we won't find a way to change the string object. Any changes made to the output are the re-creation of the string object, rather than the original object. The variable content is changed, that is, the reference of different objects.

 

 

------------------------------------------------------------------------

(: One riding dust ::):

 

In Java, value passing is always used.
In Java, methods can change the state of object parameters, but cannot change the object reference
Body. That is, when an object instance is created, like this: Apple A = new Apple (); A stores the address of this object instance. The address, that is, when the value of A is passed to a function as a parameter, a itself will not change.
TV sets and remote controls can clearly describe and explain this problem.
The remote control can be seen as a reference copy of the TV. As long as the TV exists, that is, the remote control is used to align it with a TV, and various buttons on the remote control can have various effects on the TV, however, changing the remote control will not affect the TV, and the TV will not change to another TV because of the remote control. At the same time, the remote control can be switched to another TV without aligning with the original TV, which will not affect the original TV. A TV can have multiple remote controls, and as long as a remote control is aligned with the TV, the remote control can change the status of the TV through the buttons on it.
The following code shows the extent to which only values are transmitted on the front:
// Test. Java
Class test {
Private string name;

Public String getname (){
Return name;
}

Public void setname (string name ){
This. Name = Name;
}
}

// Testtransferparameter. Java

Public class testtransferparameter {
Public static void main (string [] ARGs ){
Test A = new test ();
A. setname ("");
Test B = new test ();
B. setname ("B ");
System. Out. println ("before swap:" + "A =" + A. getname () + "; B =" + B. getname ());
Swap (A, B );
System. Out. println ("after swap:" + "A =" + A. getname () + "; B =" + B. getname ());
}

Private Static void swap (Test A, Test B ){
Test temp;
Temp =;
A = B;
B = temp;
System. Out. println ("swaping:" + "A =" + A. getname () + "; B =" + B. getname ());
}

}

Output result:
Before swap: A = A; B = B
Swaping: A = B; B =
After swap: A = A; B = B

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.