Java string pool and String Heap Memory Allocation

Source: Internet
Author: User

The Java Runtime Environment has a string pool maintained by the string class. When executing the statement string STR = "ABC", first check whether the string "ABC" exists in the string pool. If yes, directly assign "ABC" to STR, if it does not exist, create a new character string "ABC" in the string pool, and then assign it to Str. When executing the statement string STR = new string ("ABC"), create a new string "ABC" regardless of whether the string pool contains the string "ABC" (note: the new string "ABC" is not in the string pool), and then it is paid to Str. The efficiency of the previous statement is high, and the efficiency of the latter statement is low, because the new string occupies memory space. String STR = new string () creates an empty string, which is the same as string STR = new string.

Public StringIntern()

Returns the canonicalized representation of string objects.

A string pool with an initial null value, which consistsStringPrivate maintenance.

When the intern method is called, if the pool already containsStringObject string (Useequals(Object)Method), returns the string in the pool. OtherwiseStringThe object is added to the pool, and thisStringObject reference.

It follows the following rules: For any two stringssAndt, When and only whens.equals(t)Istrue,s.intern() == t.intern()Onlytrue.

String. Intern ();
Another note: the constant pool exists in the. Class file and is loaded by JVM during runtime and can be expanded. The intern () method of string is a method to expand the constant pool. When a string instance STR calls the intern () method, Java checks whether the constant pool has the same UNICODE String constant, if yes, its reference is returned. If no, a string with Unicode equal to STR is added to the constant pool and Its Reference is returned.
Example 3:
String S0 = "kvill ";
String S1 = new string ("kvill ");
String S2 = new string ("kvill ");
System. Out. println (S0 = S1 );
S1.intern ();
S2 = s2.intern ();
System. Out. println (S0 = S1 );
System. Out. prntln (S0 = s1.intern ());
System. out. println (s0 = s2 );
Result:
False
False // although s1.intern () is executed, its return value is not assigned to s1
True
True
Finally, let's get rid of a wrong understanding:
Someone said, "Use String. the intern () method can save a String class to a global String table. If a unicode String with the same value already exists in this table, this method returns the address of an existing String in the table, if there is no String with the same value in the table, register your own address to the table. "If you understand this global String table as a regular eating, the last sentence "register your address to the table if there is no string with the same value in the table" is incorrect.
Example 4:
String s1 = new String ("kvill ");
String s2 = s1.intern ();
System. out. println (s1 = s1.intern ());
System. out. println (s1 + "+ s2 );
System. out. println (s2 = s1.intern ());
The result is:
False
Kvill kvill
True
We didn't declare a "kvill" constant, so there was no "kvill" in the constant pool at first. When we call s1.intern (), a "kvill" constant is added to the constant pool, the original "kvill" that is not in the constant Pool still exists, so it is not "registering your own address in the constant pool.


Example 5:
String str1 = "java"; // point to the String pool
String str2 = "blog"; // point to the String pool

String s = str1 + str2; // s refers to the object whose value is "javablog" in the heap. The + operator creates two String objects in the heap, the values of these two objects are respectively "java" "blog ". that is to say, copy these two values from the string pool, create two objects in the heap, create object s, and then assign the heap address of "javablog" to s. is this sentence co-created? String objects!

System. out. println (s = "javablog"); // The result is false.
The Jvm does put the String object of the type such as String str1 = "java"; in the constant pool, but it does so during compilation, while String s = str1 + str2; it is known at the runtime, that is, str1 + str2 is created in the heap, so the result is false.

If you change it to the following two methods:

String s = "java" + "blog"; // directly put "javablog" into the String pool, System. out. println (s = "javablog"); the result is true. Is this sentence created? String objects

String s = str1 + "blog"; // It is allocated in the heap instead of being placed in the String pool. out. the result of println (s = "javablog"); is False. Is this sentence created? String objects

Answer:
String s = new String ("abc"); how many String objects are created?
String s = new String ("abc"); how many String objects are created?

Differences between referenced variables and objects;
The String text "abc" is a String object;
The string object in the pool of literal strings and heap.

I. Reference variables and objects: Except for some early Java books and junk books, people can clearly learn the differences between them.
A aa;
This statement declares the reference variable aa of Class A [we often call it A handle], and the object is generally created through new. So in the question, s is just a reference variable, and it is not an object.

2. All String texts in Java [String constants] Are A String object. Some [especially C programmers] may like to treat a string as A/as a character array in some cases. This is also impossible because there are some internal relationships between strings and character arrays. In fact, it and the character array are two completely different objects.

System. out. println ("Hello". length ());
Char [] cc = {'h', 'I '};
System. out. println (cc. length );

3. Create a String object:
Because a String object is widely used (it is an object, in general, the object is always allocated memory in heap), Java aims to save memory space and Runtime (such as when comparing strings, = faster than equals (). In the compilation phase, all the string texts are put in a pool of literal strings, the text pool becomes part of the constant pool during runtime. The advantage of the text pool is that all the same string constants in the pool are merged, occupying only one space.
We know that for two referenced variables, use = to determine whether their values (references) are equal, that is, to point to the same object:

String s1 = "abc ";
String s2 = "abc ";
If (s1 = s2) System. out. println ("s1, s2 refer to the same object ");
Else System. out. println ("trouble ");

The output here shows that the two strings are saved as an object. That is to say, the above Code only creates a String object in the pool.

Now let's look at the String s = new String ("abc"); statement. Here, "abc" itself is an object in the pool, while executing new String () at runtime,
Copy the objects in the pool to heap, and assign the reference of this object in heap to s. OK. This statement creates two String objects.

String s1 = new String ("abc ");
String s2 = new String ("abc ");
If (s1 = s2) {// statements not executed}

In this case, we can see that although the "content" of the two objects is the same (equals () Judgment), the references held by the two reference variables are different,
How many String objects have been created in the above Code? (Three, one in the pool and two in the heap .)


To sum up, there are two methods to create a string: Two memory areas (pool, heap)

1. The string created by "" quotation marks is in the string pool.

2, new, new when creating a string, first check whether there is a string with the same value in the pool. If there is a string, copy it to the heap and return the address in the heap. If there is no string in the pool, create a copy in the heap and return the address in the heap (Note: At this time, you do not need to copy from the heap To the pool. Otherwise, the string in the heap will always be a subset of the pool, resulting in a waste of pool space.)!

In addition, when assigning values to a string, if the right operand contains one or more string references, A String object is created in the heap and a reference is returned; for example, String s = str1 + "blog ";
You can use "=" to compare two string objects that already exist in the string pool, which is faster than the equals operator.

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.