Java parameter mode-value passing or reference passing

Source: Internet
Author: User

Java parameter mode-value passing or reference passing

Arguments are passed by value instead of by reference. The Java application has only one parameter passing mechanism that is passed by value. It is written to expose a pervasive myth that Java applications pass parameters by reference to avoid common programming errors that result from relying on the "pass by reference" behavior.
Some of the feedback from this excerpt suggested that I was confused about the problem, or that it was completely mistaken. Many disagree with my readers using the C + + language as an example. So in this column I'll use C + + and Java applications to further illustrate some of the facts.
   Key points
After reading all the comments, the question finally dawned on the exam tip: At least one major problem has been confusing. Because the object is passed by reference. The object is indeed passed by reference, and the excerpt does not conflict with it. The excerpt says that all parameters are passed by value-another parameter. The following is true: Never pass an object in a Java application, but only pass an object reference. Therefore, the object is passed by reference. But it is important to distinguish how the parameters are passed, which is the intent of the excerpt. The fact that Java applications pass objects by reference does not imply that Java applications pass parameters by reference. Parameters can be object references, while Java applications pass object references by value.
   parameter Passing in C + + and Java applications
A variable in a Java application can be one of the following two types: a reference type or a base type. When passed as a parameter to a method, the two types are handled the same way. Both types are passed by value, and no one is passed by reference. This is an important feature, as shown in the following code example.
Before continuing with the discussion, it is important to define both the terms passed by value and passed by reference. Passing by value means that when a parameter is passed to a function, the function receives a copy of the original value. Therefore, if the function modifies the parameter, only the copy is changed, and the original value remains unchanged. Passing by reference means that when a parameter is passed to a function, the function receives the memory address of the original value instead of a copy of the value. Therefore, if the function modifies the parameter, the original value in the calling code changes accordingly.
These are important, please pay attention to the following conclusions, these are I think the above article in the essence and the final conclusion:
1. Objects are passed by reference
2. Java applications have and only one parameter passing mechanism, that is, passing by value
3, passing by value means that when a parameter is passed to a function, the function receives a copy of the original value
4. Passing by reference means that when a parameter is passed to a function, the function receives the memory address of the original value, not the copy of the value
Let's start with the exam. 1th: Objects are passed by reference
Indeed, I do not think we have any questions, such as:
Class Test01
{
public static void Main (string[] args)
{
StringBuffer s= New StringBuffer ("good");
StringBuffer s2=s;
S2.append ("afternoon.");
System.out.println (s);
}
}
Objects s and S2 point to the same address in memory and therefore point to the same object.
How do I explain that "objects are passed by reference"?
This means that an object assignment is a reference to an object, so the object is passed by reference, is there a problem?
The output of the program run is:
Good afternoon.
This shows that S2 and s are the same object.
One thing to clarify here is that the object is actually a value, because the object is a pointer, and this assignment is the assignment between pointers, so in Java it is said to be a reference. (What is a reference?) No, it's an address. What is the address, but is an integer value)
Take a look at the following example:
Class Test02
{
public static void Main (string[] args)
{
int i=5;
int i2=i;
i2=6;
System.out.println (i);
}
}
What is the result of the program? 5!!!
What this means is that the original data type is passed by value, and this by-pass also refers to the behavior when the assignment is made.

Next question: Java applications have only one parameter passing mechanism, which is passed by value
Class Test03
{
public static void Main (string[] args)
{
StringBuffer s= New StringBuffer ("good");
StringBuffer s2=new StringBuffer ("bad");
Test (S,S2);
System.out.println (s);//9
SYSTEM.OUT.PRINTLN (S2);//10
}
static void Test (StringBuffer s,stringbuffer S2) {
System.out.println (s);//1
SYSTEM.OUT.PRINTLN (S2);//2
S2=s;//3
S=new StringBuffer ("new");//4
System.out.println (s);//5
SYSTEM.OUT.PRINTLN (S2);//6
S.append ("hah");//7
S2.append ("hah");//8
}
}
The output of the program is:
Good
Bad
New
Good
Goodhah
Bad
Quiz Tip: Why is the output like this?
The emphasis here is on the "parameter passing mechanism", which is different from the delivery mechanism when assigning statements.
We see that the output of 1, 2 is exactly the same as our forecast
3 point S2 to s,4 and point S to a new object
So 5 of the output prints the contents of the newly created object, while 6 prints the contents of the original S
7 and 82 places to modify object content, but why is the output of 9 and 10 so?
Java applications have only one parameter passing mechanism, which is passed by value.
At this point, I would like to summarize my final views on this issue and a method that I think can help you understand:
We can understand the objects in Java as pointers in C + +
For example, in C + +:
int *p;
Print (p);//1
*p=5;
Print (*p);//2
1 What is the result of printing, a 16-binary address, and 2 what is the result of printing? 5, which is what the pointer is pointing to.
Even though the pointer is actually a 32-bit integer in C + +, we can understand the value of a long type.
And in Java, what an object s is, is also a pointer, is an int (for the JVM), we are directly using (that is, the case of S2=s, but for System.out.print (s), the case of the exception, Because it is actually dangling Huangliang ystem.out.print (s.tostring ())) object when it is an int integer, this can simultaneously explain the assignment of the reference and the arguments when the pass value (in both cases is directly used), and we are in S. XXX in such cases when s is in fact the C + + *s in this use. This kind of different results in different usage situations is a simplification that Java has made for us, but it can be misleading for C + + programmers. There are many cases in Java that are automatically identified and handled according to the context, and here is a bit of an extreme scenario:
Class T
{
public static String t= "T";
public static void Main (string[] args)
{
T T =new t ();
T.T ();
}
static void T () {
System.out.println (t);
}
}
(for content that is automatically identified by context, interested people can look at our translated Java rules later)
1. Objects are passed by reference
2. Java applications have and only one parameter passing mechanism, that is, passing by value
3, passing by value means that when a parameter is passed to a function, the function receives a copy of the original value
4. Passing by reference means that when a parameter is passed to a function, the function receives the memory address of the original value, not the copy of the value
   three words summed up:
1. The object is to pass the reference

2. The original type is the pass value

3.String type because there is no function to provide its own modification, each operation is reborn into a string object, so special treatment. Can be considered as a pass value.

==========================================================================

public class Test03 {
public static void Stringupd (String str) {
str = str.replace ("J", "L");
System.out.println (str);
}
public static void Stringbufferupd (StringBuffer BF) {
Bf.append ("C");
SYSTEM.OUT.PRINTLN (BF);
}
public static void Main (string[] args) {

/**
* For basic type and string (special) is the value of the
*
* Output Lava,java
*/
string S1 = new String ("Java");
STRINGUPD (S1);
System.out.println (S1);

/**
* For the image, the reference is the same as the reference.
*
* Output Javac,javac
*/
StringBuffer bb = new StringBuffer ("Java");
STRINGBUFFERUPD (BB);
System.out.println (BB);
}
}

Analysis: Just like the light is the wave or particles of the issue of the same controversy, for the Java parameter is the transfer of value or reference to the problem, there are many wrong understanding and understanding. The first thing we need to figure out is that regardless of the type of Java parameter, a copy of the parameter is passed. In this case, the classic explanation given by thinking in Java is when you ' re passing primitives to a method, you get a distinct copy of the primitive. When you ' re passing a reference to a method, you get a copy of the reference. (if Java is a pass-through, a copy of the value is passed, and if Java is a reference, the referenced copy is passed.) )

In Java, variables fall into the following two categories:

① for basic type variables (int, long, double, float, Byte, Boolean, char), Java is a copy of the value passed. (Java and C + + are the same here)

② for all object-type variables, Java is a copy of the reference. In fact, the essence of the reference copy is to copy the pointer to the address, but Java is not as obvious as C + + in the * and & symbols. (here Java differs from C + +, in C + +, when a parameter is a reference type, a real reference is passed instead of a reference copy)

It is important to note that the string type is also an object type variable, so it must be a reference copy. Do not be fooled by string as a basic variable type because it is very easy to use in Java and does not require new. Just a string is a non-mutable class, making it no different to pass a value or pass a reference.

For the basic type, the value of the transfer is to copy one of their own copies, even if their own copy of the change, you do not change. For an object type, it passes a reference copy (similar to a pointer in C + +) to its own address, rather than a copy of its own actual value. Why did you do it? Because the object type is placed in the heap, on the one hand, the speed relative to the basic type is relatively slow, on the other hand, the object type itself is relatively large, if the re-copying the object value of the method, waste memory and slow. Just like you want to Zhang San (Zhang San equivalent function) Open the warehouse and check the contents of the library (warehouse equivalent address), it is necessary to create a new warehouse (and put the same goods) to Zhang San? No need, you just need to copy a key (reference) to send to Zhang San, Zhang San will take the spare key (quote copy, but timeliness, function end, key destruction) Open the warehouse.

In this case, many classic books, including Thinking in Java, are interpreted as: "Both the base type and the object type are values. "This is not a mistake either, because they treat the reference copy as a" value ". But I think: the value of the transfer and the reference is two different content, there is no need to put the two together, get together is more difficult to understand.

Java parameter mode-value passing or reference passing

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.