The string class constant pool in Java is detailed

Source: Internet
Author: User
Tags wrapper

Test1:

 Package stringtest;  Public class test1 {    /**     @param  args     * /     Publicstaticvoid  main (string[] args) {        = "A1";         = "a" + 1;        System.out.println (a= =b);    } // true }

Test2:

 Packagestringtest; Public classTest2 {/**     * @paramargs*/     Public Static voidMain (string[] args) {String a= "AB"; String BB= "B"; String b= "a" + BB;//compiler cannot be determined as a constantSystem.out.println (a==b); }//false}

TEST3:

 Packagestringtest; Public classTest3 {/**     * @paramargs*/     Public Static voidMain (string[] args) {String a= "AB"; FinalString BB = "B"; String b= "a" + BB;//BB Plus Final is a constant that can be determined in the compiler BSystem.out.println (a==b); }//true}

TEST4:

 Packagestringtest; Public classtest4 {/**     * @paramargs*/     Public Static voidMain (string[] args) {String a= "AB"; FinalString BB =GETBB (); String b= "a" + BB;//BB is returned through the function, although know it is final, but do not know what is specific, to run until the time to know the value of BBSystem.out.println (a==b); }//false    Private StaticString GETBB () {return"B"; }}

TEST5:

 Packagestringtest; Public classTEST5 {/**     * @paramargs*/    Private StaticString a = "AB";  Public Static voidMain (string[] args) {String S1= "a"; String S2= "B"; String s= s1 + s2;//usage of +System.out.println (s = =a); System.out.println (S.intern ()= = a);//the meaning of intern}//flase True}

TEST6:

 Packagestringtest; Public classTest6 {/**     * @paramargs*/    Private StaticString A =NewString ("AB");  Public Static voidMain (string[] args) {String S1= "a"; String S2= "B"; String s= S1 +S2; System.out.println (S==a); System.out.println (S.intern ()==a); System.out.println (S.intern ()==A.intern ()); }//Flase false True}

A string constant pool is detailed:

1.String uses private final char value[] to store strings, which means that the string content stored in this object cannot be modified after the string object is created, that is, the string type is immutable ( Immutable). The String class has a special creation method, which is created using the "" double quotation marks. For example, new string ("I Am") actually created 2
String object, one is "I am" Through "" "double quotation marks created, and the other is created by new. But they created a different period,
One is the compile period, one is the runtime!java the + operator for string type, you can directly use + to connect two strings. The run-time call to the Intern () method of the String class can add objects dynamically to the string pool.
  
Example 1
String S1 = "sss111";
This statement ibid.
String s2 = "sss111";
System.out.println (S1 = = s2); Result is True
Example 2
string S1 = new String ("sss111");
String s2 = "sss111";
System.out.println (S1 = = s2); The result is false
Example 3
string S1 = new String ("sss111");
S1 = S1.intern ();
String s2 = "sss111";
System.out.println (S1 = = s2);//result is true
Example 4
string S1 = new String ("111");
String s2 = "sss111";
String s3 = "SSS" + "111";
String s4 = "SSS" + S1;
SYSTEM.OUT.PRINTLN (s2 = = s3); True
SYSTEM.OUT.PRINTLN (s2 = = S4); False
SYSTEM.OUT.PRINTLN (S2 = = S4.intern ()); True
  

   the results above are analyzed and summarized as follows:

    1. The strings created by using the "" quotation marks alone are constants, and the compilation period is determined to be stored in the string pool;

2, objects created with the new String ("") are stored in the heap and are newly created at run time;

3, using a string connector that contains only constants, such as "AA" + "AA" created is also a constant, the compilation period can be determined, has been determined to store in the string pool;

4, the object created by using a string connector containing a variable, such as "AA" + S1, is created at run time and stored in the heap;

There are several frequently-tested interview questions:
  
string S1 = new String ("S1");
String s2 = new String ("S1");
How many string objects are created above?
Answer: 3, build 1 in constant pool during the compilation period, create 2 in the runtime heap. (Creates an object on the heap once for each new created with new, and creates it in quotation marks if it is already in the constant pool, not created)

String S1 = "S1";
String s2 = S1;
S2 = "S2";
What is the string in the object that S1 points to?
Answer: "S1". (never forget the string immutable, S2 = "S2"; actually S2 's point is changed, because you can't change a string,)

--------------------------------------------------------------------------------------------------------------- -----------------------------------

String is a special wrapper class data. Can be used:
String str = new String ("abc");
String str = "ABC";
Two forms, the first is to create new objects with new (), which is stored in the heap. A new object is created each time the call is made.
The second is to create an object reference to the string class in the stack str, and then through the symbol reference to the string constant pool to find there is no "ABC", if not, the "ABC" into the string constant pool, and the Str point to "ABC", if there is already "ABC" The STR directly points to "ABC".

Use the Equals () method when comparing values within a class, and when testing two wrapper classes for reference to the same object, use = =, the following example illustrates the above theory.
String str1 = "abc";
String str2 = "abc";
System.out.println (STR1==STR2); True
You can see that str1 and str2 are pointing to the same object.

String str1 =new string ("abc");
String str2 =new string ("abc");
System.out.println (STR1==STR2); False
The new method is to generate different objects. Each time one is generated.

So the second way to create multiple "abc" strings, in memory in fact there is only one object. This writing is advantageous and saves memory space. At the same time it can improve the speed of the program to some extent, because the JVM will automatically determine whether it is necessary to create new objects based on the actual data in the stack. In the case of string str = new String ("abc"), the code creates a new object in the heap, regardless of whether the string value is equal or not, and it is necessary to create a new object, thereby aggravating the burden of the program.

On the other hand, it is important to note that when you define a class using a format such as String str = "ABC", you always want to assume, of course, that the object that created the string class is Str. Worry about traps! The object may not have been created! Instead, it might just point to an object that was previously created. Only through the new () method can you guarantee that a new object is created each time.
because of the immutable nature of the string class, you should consider using the StringBuffer class to improve program efficiency when a string variable needs to change its value frequently.
1. The string is not the first of 8 basic data types, string is an object.
Because the default value of the object is NULL, the default value of string is also null, but it is a special object that has some features that other objects do not have.

2. New string () and new String ("") are all declarations of a new empty string, that is, the empty string is not null;

3. String str= "Kvill"; string Str=new string ("Kvill") difference

See Example 1:

String s0= "Kvill";
String s1= "Kvill";
String s2= "kv" + "ill";
System.out.println (S0==S1);
System.out.println (S0==S2);
The result is:
True
True

First of all, we need to know the results as the TaoJava ensures that there is only one copy of a string constant.
Because the "Kvill" in S0 and S1 in the example are string constants, they are determined at compile time, so s0==s1 is true, and "kv" and "ill" are also string constants, and when a string is concatenated by multiple string constants, it is itself a string constant. So S2 is also parsed as a string constant at compile time, so S2 is also a reference to "Kvill" in the constant pool. So we come to s0==s1==s2; The string created with the new string () is not a constant and cannot be determined at compile time, so the string created by new string () is not placed in a constant pool and has its own address space.

See Example 2:
String s0= "Kvill";
String S1=new string ("Kvill");
String s2= "kv" + new string ("ill");
System.out.println (S0==S1);
System.out.println (S0==S2);
System.out.println (S1==S2);
The result is:
False
False
False

In Example 2, S0 or "Kvill" in a constant pool, s1 because it cannot be determined at compile time, is a reference to the new object "Kvill" that was created at run time, S2 because there is a second part new String ("ill") so it cannot be determined at compile time, so it is also a newly created object " Kvill "The application of the", and understand that this will know why the result is obtained.

4. String.intern ():
One more point: the constant pool that exists in the. class file is loaded by the JVM at run time and can be expanded. The Intern () method of string is a method of extending a constant pool, and when a string instance str calls the Intern () method,Java looks for a constant pool with a string constant of the same Unicode, and if so, returns a reference to it, and if not, adds a string of Unicode equal to STR in the constant pool and returns its reference; see example 3 for clarity.

Example 3:
String s0= "Kvill";
String S1=new string ("Kvill");
String S2=new string ("Kvill");
System.out.println (S0==S1);
System.out.println ("**********");
S1.intern ();
S2=s2.intern (); Assign a reference to "Kvill" in the constant pool to S2
System.out.println (S0==S1);
System.out.println (S0==s1.intern ());
System.out.println (S0==S2);
The result is:
False
**********
False//Although S1.intern () is executed, but its return value is not assigned to S1
True//Description S1.intern () returns a reference to "Kvill" in a constant pool
True

Finally I break a wrong understanding: Some people say, "using the String.intern () method, you can save a string class to a global string table, if a Unicode string with the same value is already in the table, Then the method returns the address of the existing string in the table, and if there are no strings of the same value in the table, register your own address in the table "If I interpret this global string table as Chang, his last word," if there are no strings of the same value in the table, register your own address in the table "Is wrong:

See 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 ());
Results:
False
Kvill Kvill
True

In this class we do not have the reputation of a "kvill" constant, so the constant pool in the beginning there is no "Kvill", when we call S1.intern () in the constant pool after the new "Kvill" constant, the original is not in the constant pool "Kvill" still exists, is not " Register your own address in the constant pool.
S1==s1.intern () is false to indicate that the original "Kvill" still exists; S2 is now the address of "Kvill" in the constant pool, so there is S2==s1.intern () true.

The string class constant pool in Java is detailed

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.