Java constant pool Comprehension and summary

Source: Internet
Author: User

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;

Integer I1 = +=; System.out.println (I1==i2); // Output 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 Cache code:  public  static  Integer valueOf (int   i) { assert  integercache.high >=     127;  if  (i >= integercache.low && i <=  Integercache.high)  return  integercache.c     Ache[i + (-integercache.low)];  return  new   Integer (i);}  
Integer i1 = n=; System.out.println (I1==i2); // Output False

The two types of floating-point type wrapper class float,double do not implement constant pool technology.

Double i1=1.2;D ouble i2=1.2; System.out.println (I1==i2); // Output False

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.

Integer i1 =new integer (+); System.out.println (I1==i2); // Output False

An example of a richer integer

 Integer i1 = 40;integer i2  = 40;integer i3  = 0;integer i4  = new  Integer (40 = new  Integer (40 = new  integer (0 "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" + (+ = = i5 + I6));  
I1=i2   truei1=i2+i3   truei1=i4   falseI4=i5   false I4=i5+i6   true40=i5+i6   true
    1. 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";   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.

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

String str1 = "str"= "ing"= "str" + "ing"= str1 += = STR4); // false  = "string"= = STR5); // true

Java Basics: Concatenation of strings

Special Case 1
 Public Static FinalString A = "AB";//constant A Public Static FinalString B = "CD";//constant B Public Static voidMain (string[] args) {String s= A + B;//initializes two constants with A + connectionString t = "ABCD"; if(s = =t) {System.out.println ("s equals t, they are the same object"); } Else{System.out.println ("s are 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

 Public Static FinalString A;//constant A Public Static FinalString B;//constant BStatic{A= "AB"; B= "CD"; }    Public Static voidMain (string[] args) {//initializes two constants with A + connectionString 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 are 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.
    • String s1 = new String ("XYZ"); How many objects did the create?
      considers the class load phase and the actual execution time. The
      (1) class is loaded on only one class at a time. "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.

    • java.lang.String.intern ()
      Another important feature of running a constant pool with respect to the class file constants pool is the dynamic , the Java language does not require constants must be compiled only to produce, that is, not pre-placed in the class file of the constant pool content to enter the method area to run the frequent pool, the runtime may also put new constants in the pool, this feature is used by developers more is The Intern () method of the String class. The
      String's intern () method 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) {       new String ("Computer");    = S1.intern ();    = "Computer";   System.out.println ("S1 = = s2?") "+ (S1 = = s2));   System.out.println ("s3 = = s2?") "+ (s3 = = s2));}
Falsetrue

An example of a richer string comparison

 Public classTest { Public Static voidMain (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) + ""); System.out.println ((Hello= = ("Hel" + "lo") + ""); System.out.println ((Hello= = ("Hel" +lo) + ""); System.out.println (Hello= = ("Hel" +lo). Intern ());} }classOther {StaticString Hello = "Hello"; } PackageOther ; Public classOther { Public StaticString Hello = "Hello"; }
true true true true false true
    1. 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.

[2015-08-26]

From:http://www.jianshu.com/p/c7f47de2ee80

















Java constant pool Comprehension and summary

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.