Java constant Pool

Source: Internet
Author: User

The Java heap is a run-time data area in which objects allocate space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, because it is at runtime to allocate memory dynamically, Java garbage collector will automatically take away these no longer use data. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.

The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variable data (int, short, long, byte, float, double, Boolean, char) and object handle (reference).

Stack has a very important particularity, is that there is data in the stack can be shared. Suppose we both define

int a = 3;    int b = 3;  

The compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then finds out if there is a value of 3 in the stack, and if it does not, it stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3.

At this point, if you make a=4 again, then the compiler will re-search the stack for 4 values, if not, then store 4 in, and a point to 4; Therefore the change of a value does not affect the value of B.

It is important to note that this sharing of data with two object references also points to an object where this share is different, because the modification of a does not affect B, which is done by the compiler, which facilitates space saving. An object reference variable modifies the internal state of the object, affecting another object reference variable.

String is a special wrapper class data. Can be used:

New String ("abc");    = "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.

    1. String str1 = "abc";    = "abc";   System.out.println (str1//true   // you can see that str1 and str2 are pointing to the same object. = new String ("abc");      =new String ("abc");   System.out.println (str1//  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

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, we need to know the result. Java ensures that a string constant has only one copy.

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.

Example:

    1. String s0= "Kvill";   string S1=new string ("Kvill");   String S2new 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 the same Unicode string constant in the constant pool, if any, returns its reference, if not, in the usual Add a string of Unicode equal to STR in the volume pool and return its reference; see the example.

Example:

    1. String s0= "Kvill";   string S1=new string ("Kvill");   string S2=new string ("Kvill");   System.out.println (s0= =S1)   ;" **********" );   S1.intern ();   S2// assign a reference to "Kvill" in the constant pool to   S2System.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:

Example:

    1. 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.

5. About Equals () and = =:

This is simple for string to compare whether the Unicode sequence of the two strings is equivalent, if equal returns true, and = = is the same as the address of the two strings, that is, a reference to the same string.

6. About the string is immutable

This said again a lot, as long as we know that the string instance once generated will not be changed, such as: string Str= "kv" + "ill" + "+" ans "; There are 4 string constants, first "KV" and "ill" generate "Kvill" in memory, and then "Kvill" and "Generate" Kvill "in memory, and finally generated" Kvill ans ", and the address of the string to the STR, This is because the "immutable" of string produces a lot of temporary variables, which is why it is recommended to use StringBuffer, because StringBuffer can be changed.

Here are some string-related FAQs:

Final usage and understanding in string

Final New StringBuffer ("111"); Final New StringBuffer ("222"); a=b; // This sentence compilation does not pass Final New StringBuffer ("111"); A.append ("222"); // compiled by

As you can see, final is valid only for the reference "value" (that is, the memory address), which forces the reference to point only to the object that was initially pointed to, and changes its point to cause a compile-time error. Final is not responsible for the change in the object it points to.

Several examples of string constant pool problems

Here are a few common examples of comparative analysis and understanding:

    1. String a = "A1";    = "a" + 1;    // result = True   String a = "atrue";    = "a" + "true";    // result = True   String a = "a3.4";    = "a" + 3.4;    //

Analysis: JVM for string constant "+" number connection, the program compile period, the JVM will be the constant string "+" connection optimization to the concatenated value, take "a" + 1, the compiler is optimized in class is already A1. The value of its string constants is determined at compile time, so the final result of the above program is true.

    1. String a = "ab";    = "B";    = "a" + BB;    //

Analysis: JVM for string reference, because in the string "+" connection, there is a string reference exists, and the reference value in the program compilation period is not determined, that is, "a" + BB can not be optimized by the compiler, only during the program run time to dynamically allocate and the new address after the connection to B. So the result of the above program is also false.

    1. String a = "ab";    Final String BB = "B";    = "a" + BB;    //

Analysis: The only difference between [3] is that the BB string has a final decoration, and for a final modified variable, it is parsed at compile time to a local copy of the constant value stored in its own constant pool or embedded in its byte stream. So at this point the "a" + BB and "a" + "B" effect is the same. Therefore, the result of the above program is true.

    1. String a = "ab";    Final String BB = GETBB ();    = "a" + BB;    // result = False    Private Static String GETBB () {  return "B";   

Analysis: The JVM for the string reference BB, its value in the compilation period can not be determined, only after the program run time call method, the return value of the method and "a" to dynamically connect and assign the address to B, so the result of the above program is false.

From the above 4 examples can be obtained:

String s = "a" + "B" + "C";

is equivalent to string s = "abc";

String  a  =  "a";   String  b  =  "B";   String  c  =  "C";   String  s  =   a  +  b  +  

This is not the same, the end result equals:

  1.  StringBuffer temp = new   StringBuffer ();     Temp.append (a). Append (b). append (c); String s  = temp.tostring ();  //  public  class   Test { public  static  void   Main (string args[]) {string s  = null  ;  for  (int  i = 0; i <; I++) {s  + = "A" ; }  }  } 

Every time you do it, you produce a StringBuilder object and then throw it away after append. The next time the loop arrives, it re-generates the StringBuilder object and then append the string so that it loops until the end. If we use the StringBuilder object directly for Append, we can save N-1 time to create and destroy objects. So for applications that want to concatenate strings in a loop, the StringBuffer or Stringbulider objects are generally used for append operations.

The Intern method of the string object is understood and analyzed:

    1.  public   Class   Test4 { private  static  String a = "ab"  public  static  void   main (string[] args) {String S1  = "a"   ;  String s2  = "B" ;  String s  = S1 + S2; System.out.println (s  = = a); // false  System.out.println (s.intern () = = a); // true   

       

The problem with Java is that it is a constant pool. For the s1+s2 operation, a new object is recreated in the heap, and s holds the contents of the new object in the heap space, so s is not equal to the value of a. When you call the S.intern () method, you can return the address value of s in the constant pool, because the value of a is stored in a constant pool, so the values of s.intern and a are equal.

Summarize

A reference to the local variable data and objects (String, Array, object, and so on) that are used to hold some raw data types in the stack. But not the object content

The heap contains objects created using the New keyword.

A string is a special wrapper class whose reference is stored in the stack, and the object content must be set differently (Chang and heap) depending on how it was created. Some compile time has been created, stored in a string constant pool, and some runtime is created. Use the new keyword to store in the heap.

Java constant Pool

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.