Java Storage Location Classic example

Source: Internet
Author: User

String a= "a";
String b= "B";
String c= "AB";
String d= "AB";
String e=a+b;

The memory used to store the data in the program is divided into four blocks
1. Global zone (static zone)
2, text constant area: the constant string is placed in this area, that is, we often talk about the constant pool.
3. Stack: The parameter value of the stored function, the value of the local variable, etc.
4. Heap area (heap): storage Object

When we define a string
String a = "a";
A in the stack area, "a" is a string constant in the constant pool
String B = "B";
b in the stack area, "B" in the constant pool
String c= "AB";
C in the stack area, "AB" in the constant pool
String d= "AB";
D in the stack area, this time the constant pool has "AB", so directly using the already have the "AB"
So the same "AB" in the constant pool that C and D are pointing at this time
String e=a+b;
E in the stack area, A+b actually produces a new string object, since it is a string object, so the result "AB" is placed in the heap area, that e points to the "AB" in the heap
In this case, the C==d is true,c==e to False
////////////////////////////////////
Also, if you define a string object
String str1 = new String ("AB");
STR1 in the Stack area, create the "AB" string object in the heap area
String str2 = new String ("AB");
STR2 is in the stack, and a new "AB" object is also created in the heap area, but not the same as the "AB" just now.
The equivalent of two string objects in the heap area, but the content is just "AB".

So STR1==STR2 is false.

A constant string inside a constant pool can be reused, but it must be the string you use directly, like A +
b This form Although the result is "AB", but not the use of the string constant "AB"

Transferred from: http://blog.sina.com.cn/s/blog_4b622a8e0100c296.html

Java Storage Location Classic example

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.