I. Related Concepts
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.
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
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.
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.
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
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
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
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
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
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.
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.
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.
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
- 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".
[TURN]JAVA Constant Pool Comprehension Summary