Reference passing and value passing problems in Java

Source: Internet
Author: User

1. Refer to the value first:
String a = "God";//a stored in the stack God stores two objects in the head (heap)
String B=a;
A points to the God object in the heap
B=a; Note B also points to the God object in head; B=a only creates an object B
At this point the b= "other God" does not change the original value of B because the string class is the final decorated class, so when the assignment is made, a new other object is created in the team and then the B is directed to the other God object.

Let's take a data exchange operation.

public void swap (int a,int b) {
int temp=a;
A=b;
B=a;
System.out.println (A + "=" +b); 10 20
}
Main () {

int a=20;

b=10;
Swap (A, b);
System.out.println (A + "=" +b); 20 10

}
You can see that the A/b value in the Main method does not change, so he is the value passed

2. Reference delivery
void method (StringBuffer sb) {
Sb.append ("zzz");
}
Main () {
StringBuffer sb=new StringBuffer ("DD");
Method (SB);
System.out.println (Sb.tostring ());

}
You can see that the value of SB becomes ddzzz, a pair should be able to have many reference variables, but they are all working on the same object

Summary: Common data types such as (int, double) are value passes, and the objects that you define are reference passes.

Reference passing and value passing problems 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.