"Reprint" Java Constant pool

Source: Internet
Author: User

This essay is reproduced, the original paste address: Java constant pool understanding and summary.

(In fact, Java's Chang is a bit like the constant store of storing string constants in C + +).

I. Related Concepts
  1. What is a constant
    A constant is represented by a final modified member variable, which cannot be changed once the value is given!
    There are three final modified variables: Static variables, instance variables, and local variables, representing three types of constants, respectively.

  2. Constant pool in the class file
    In the class file structure, the first 4 bytes are used to store the magic number, which determines whether a file can be accepted by the JVM, then 4 bytes to store the version number, the first 2 bytes to store the minor version number, the last 2 to store the major version number, and then the constant pool to hold the constant. Because the number of constants is not fixed, the entry for the constant pool places a U2 type of data (Constant_pool_count) to store the constant pool capacity count value.
    A constant pool is primarily used to hold two major classes of constants: literal (Literal) and Symbolic reference (symbolic References), which is equivalent to the concept of Java language-level constants, such as text strings, such as the constant value declared as final, the symbolic reference is the concept of compilation principles, including the following three types of constants:

    • Fully qualified names for classes and interfaces
    • Field names and descriptors
    • Method name and descriptor
  3. Run-time constant pool in the method area
    Running a constant pool is part of the method area.
    class file In addition to the class version, fields, methods, interfaces, and other descriptive information, there is also a constant pool, for the compilation period generated by the various literal and symbolic references, which will be loaded in the class load into the method area of the run constant pool.
    Another important feature of running a constant pool relative to a class file's const pool is its dynamic nature , and the Java language does not require constants to be generated only at compile time, which means that the contents of the constant pool in the class file are not pre-placed to enter the method area to run the frequent pool. It is also possible to put new constants into the pool during the run, which is the intern () method of the string class used by developers.

  4. The benefits of a constant pool
    Chang is to avoid the frequent creation and destruction of objects and affect the performance of the system, which realizes the sharing of objects.
    For example, a string constant pool in which all string literals are placed in a constant pool during the compilation phase.
    (1) Save memory Space: All the same string constants in a constant pool are merged, occupying only one space.
    (2) Save run Time: when comparing strings, = = is faster than Equals (). For two reference variables, only = = To determine whether the reference is equal, you can also determine whether the actual value is equal.

  5. Meaning of double equals = =
    A double equals sign is applied between the basic data types, and their values are compared.
    A double equals sign is applied between the composite data types (classes), comparing their storage addresses in memory.

Two. 8 basic types of wrapper classes and constant pools
  1. Most of the basic types of wrapper classes in Java implement constant pool technology,
    namely Byte,short,integer,long,character,boolean;

    40;Integer i2 = 40;System.out.println(i1==i2);//输出TRUE

    These 5 wrapper classes create the corresponding type of cached data for the value [-128,127] by default, but beyond this range the new object is still created.

    //Integer 缓存代码 :public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
    400;Integer i2 = 400;System.out.println(i1==i2);//输出false
  2. The two types of floating-point type wrapper class float,double do not implement constant pool technology.

    Double i1=1.2;Double i2=1.2;System.out.println(i1==i2);//输出false
  3. Scenarios where a constant pool is applied
    (1) Integer i1=40; Java, when compiled, encapsulates the code directly Integer i1=Integer.valueOf(40); to use objects in a constant pool.
    (2) Integer i1 = new Integer(40); In this case, a new object is created.

    40;Integer i2 = new Integer(40);System.out.println(i1==i2);//输出false
  4. An example of a richer integer

    integer i1 = 40;integer i2 = 40;integer i3 = 0;integer i4 = new Integer (40); Integer i5 = new Integer (40); integer I6 = new Integer (0); System.out.println ( "I1=i2" + (I1 = = i2)); System.out.println ( "I1=i2+i3" + (I1 = = i2 + i3)); System.out.println ( "I1=i4" + (I1 = = i4)); System.out.println ( "i4=i5" + (i4 = = i5)); System.out.println ( "I4=i5+i6" + (I4 = = i5 + I6)); System.out.println ( "40=i5+i6" + (40 = = i5 + I6));   
    i1=i2   truei1=i2+i3   truei1=i4   falsei4=i5   falsei4=i5+i6   true40=i5+i6 true

    Explanation: The statement i4 == i5 + i6 , because the + this operator is not applicable to the integer object, first i5 and I6 for the automatic unpacking operation, the numerical addition, that is i4 == 40 . The integer object cannot be directly compared with the numeric value, so the I4 automatically splits to an int of 40, which turns 40 == 40 out to be a numeric comparison.
    Automatic boxing and unpacking in Java

Three. String class and Constant pool
  1. How string objects are created

      String str1 = "abcd";  String str2 = new String("abcd"); System.out.println(str1==str2);//false

    These two different methods of creation are differentiated, the first is to take objects in a constant pool, and the second is to create a new object directly in the heap memory space.
    As long as you use the new method, you need to create an object.

  2. Join expression +
    (1) A new object created by using a "+" connection between a string object that uses quotation marks to contain text is added to the string pool.
    (2) for all "+" connection expressions that contain new objects (including null), the new object will not be added to the string pool.

    "str";String str2 = "ing";String str3 = "str" + "ing";String str4 = str1 + str2;System.out.println(str3 == str4);//falseString str5 = "string";System.out.println(str3 == str5);//true

    Java Basics: Concatenation of strings

    • Special Case 1
      Publicstatic final String A =  "AB"; //constant Apublic static final String B = " CD "; //constant Bpublic static void main ( String[] (args) {String s = A + B; //the two constants with the + connection to s for initialization of String t =  "ABCD"; if (s = = t) {System.out.println ( "s equals T, they are the same object");} else {System.out.println ( "s not equal to T, they are not the same object"),}} s equals T, they are the same object   
      A and B are constants and the values are fixed, so the value of S is also fixed, which is determined when the class is compiled. In other words: String s=a+b; Equivalent to: String s= "AB" + "CD";
    • Special Case 2
      PublicStaticFinal String A;//constant Apublic static final String B; //constant Bstatic {A =  "AB"; B =  "CD";} public static void main (string[] args) { //initializes two constants with A + connection to S to initialize String s = A + B; String t =  "ABCD"; if (s = = t) {System.out.println ( "s equals T, they are the same object");} else {System.out.println ( "s not equal to T, they are not the same object");} s are not equal to T, they are not the same object   
      A and B are defined as constants, but they are not immediately assigned. It is a variable when they are assigned and what value they are given before the value of S is calculated. So A and B are similar in nature to a variable before being assigned. Then s cannot be determined at compile time and can only be created at runtime.
  3. String s1 = new String("xyz");How many objects have you created?
    Consider the class load phase and the actual execution time.
    (1) Class loading occurs only once for a class. "XYZ" is created and resides when the class is loaded (if there are already "xyz" strings residing before the class is loaded, you do not need to recreate the "XYZ" instance that is used to reside). The strings that reside are placed in a constant pool of strings that are shared globally.
    (2) When this code is subsequently run, the string instance corresponding to the "XYZ" literal is fixed and will no longer be created repeatedly. So this code copies a copy of the object in the constant pool into the heap, and gives the reference to the object in the heap to S1 hold.
    This statement creates 2 objects.

  4. Java.lang.String.intern ()
    Another important feature of running a constant pool relative to a class file's const pool is its dynamic nature , and the Java language does not require constants to be generated only at compile time, which means that the contents of the constant pool in the class file are not pre-placed to enter the method area to run the frequent pool. It is also possible to put new constants into the pool during the run, which is the intern () method of the string class used by developers.
    The Intern () method of string finds whether there is a equal equal string in the constant pool, if any, returns a reference to the string, and if not, adds its own string into the constant pool.

    public static void main(String[] args) { String s1 = new String("计算机"); String s2 = s1.intern(); String s3 = "计算机"; System.out.println("s1 == s2? " + (s1 == s2)); System.out.println("s3 == s2? " + (s3 == s2));}
    falses3 == s2? true
  5. An example of a richer string comparison
    PublicClassTest {PublicStaticvoidMain(string[] args) {String Hello ="Hello", lo ="Lo"; System.out.println (Hello = ="Hello") +" "); System.out.println ((Other.hello = = Hello) +" "); System.out.println (Other. Other.hello = = Hello) + "Hel" + "Lo") + "); System.out.println ((Hello = = ( "Hel" +lo)) +  "Hel" +lo). Intern ());}} class other { static String hello =  "Hello";} package other; public class other {public static String hello = Span class= "hljs-string" > "Hello"; } 
    true true true true false true
    In the same package, the reference is from the same string object.
    Under different classes of the same package, references are from the same string object.
    Under different packages, the same string object is still referenced from the same class.
    It can be recognized as the same string when it is translated into. class, and is automatically optimized to constants, referencing from the same string object.
    A string created at run time has a separate memory address, so it is not referenced from the same string object.



Wen/DreamWorks (Jane book author)
Original link: http://www.jianshu.com/p/c7f47de2ee80
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author". reference:http://blog.csdn.net/cpcpcp123/article/details/51285312.

"Reprint" 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.