Summary of parameter passing problems in Java

Source: Internet
Author: User
Summary of parameter passing problems in Java

Summary of parameter passing problems in Java

Start with two examples:

1)
Public class Test2 {

Public static void main (string [] ARGs ){
Stringbuffer A = new stringbuffer ("");
Stringbuffer B = new stringbuffer ("B ");
Operate (A, B );
System. Out. println (a + "," + B );
}

Static void operate (stringbuffer X, stringbuffer y ){
X. append (y );
Y = X;
}
}
Output: AB, B

2)
Public class Test2 {

Public static void add3 (integer I ){
Int val = I. intvalue ();
Val + = 3;
I = new INTEGER (VAL );
}

Public static void main (string ARGs []) {
Integer I = new INTEGER (0 );
Add3 (I );
System. Out. println (I. intvalue ());
}
}
Output: 0

First, we should understand that all parameter passing in Java is passed by value. If it is a basic type, copy a basic type to the input method. If it is a reference, copy a reference variable to the input method. If you understand these two points, you can understand the problems related to the method operation object. It is better to draw a picture pointing to an object to fully understand it.
Question 1st: When the operate method is called, two copies x and y that reference A and B are passed in. Both x and y point to the object referenced by the original A and B. X. append (y) performs operations on the object to which it points (that is, the object to which a points. X = Y, however, only two copy variables are assigned values, which does not affect the objects pointed to by original B. So the object that B points to is still B.
Question 2nd, I = new INTEGER (VAL) is just a reference copy pointing to another object, and the original I still points to the object new INTEGER (0.
If we grasp that all values in Java are transmitted and all the values are copied, we can solve similar problems.

 

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.