Java basic knowledge hardening 104:java constant pool comprehension and summary

Source: Internet
Author: User

first, related concepts1. What isConstants

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 pools in the class file

In the class file structure, the first 4 bytes are used to store the magic number, which is used to 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 literal strings, constant values declared final, etc. Symbolic references are concepts 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 a 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 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 packaging classes and constant pools

Most of the basic types of wrapper classes in Java Implement the constant pool technique , i.e. byte,short,integer,long,character,boolean;

1 Integer i1 = +; 2 Integer i2 = +; 3 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 StaticInteger ValueOf (inti) {assertIntegercache.high >= 127; if(I >= integercache.low && i <=Integercache.high)returnIntegercache.cache[i + (-Integercache.low)]; return NewInteger (i);} Integer I1= 400; Integer i2= 400; System.out.println (I1==I2);//Output False

two types of floating-point type wrapper class Float,double does not implement constant pool technology .

Double i1=1.2;D ouble i2=1.2; System.out.println (I1==i2); // Output False
1. Scenarios where a constant pool is applied

(1) Integer i1=40; Java will directly encapsulate the code as an Integer i1=integer.valueof (40) at compile time; the object in the constant pool is thus used .

(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:

1Integer I1 = 40;2Integer I2 = 40;3Integer i3 = 0;4Integer I4 =NewInteger (40);5Integer i5 =NewInteger (40);6Integer I6 =NewInteger (0);7 8System.out.println ("I1=i2" + (I1 = =i2));9System.out.println ("I1=i2+i3" + (I1 = = I2 +i3));TenSystem.out.println ("I1=i4" + (I1 = =I4)); OneSystem.out.println ("I4=i5" + (I4 = =i5)); ASystem.out.println ("I4=i5+i6" + (I4 = = i5 +I6));  -System.out.println ("40=i5+i6" + (+ = = i5 + I6));

Operation Result:

1 i1=i2   true2 i1=i2+i3   true3 i1=i4   false4 i4=i5   false5 i4=i5+i6   true6 40=i5+i6   True 

Explanation: the statement i4 = = i5 + I6, because the + operator does not apply to the integer object , First i5 and I6 for automatic unpacking operations, add value, that is, I4 = =. Then the integer object cannot be directly compared to the numeric value, so the I4 automatically splits to int, which eventually turns to 40 = = 40 for a numeric comparison .

Automatic boxing and unpacking in Java

Iii. String class and Constant pool1. How string objects are created
1 String str1 = "ABCD"; 2 New String ("ABCD"); 3 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.

1 String str1 = "str"; 2 String str2 = "ing"; 3 4 String str3 = "str" + "ing"; 5 String STR4 = str1 + str2; 6 System.out.println (STR3 = = STR4); // false 7 8 String str5 = "string"; 9 System.out.println (STR3 = = STR5); // true

Exception 1:

1  Public Static FinalString A = "AB";//constant A2  Public Static FinalString B = "CD";//constant B3  Public Static voidMain (string[] args) {4String s = A + B;//initializes two constants with A + connection5String t = "ABCD"; 6 if(s = =t) {7System.out.println ("s equals T, they are the same object"); 8}Else {   9System.out.println ("s not equal to T, they are not the same object"); Ten }    One}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

1  Public Static FinalString A;//constant A2  Public Static FinalString B;//constant B3 Static {   4A = "AB"; 5B = "CD"; 6 }   7  Public Static voidMain (string[] args) {8 //initializes two constants with A + connection9String s = A +B; TenString t = "ABCD";  One if(s = =t) { ASystem.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");  the }    - }  -s 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 are created?

consider the class loading 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.

1  Public Static voidMain (string[] args) {2String S1 =NewString ("Computer");3String s2 =S1.intern ();4String s3 = "Computer";5System.out.println ("S1 = = s2?" + (S1 = =s2));6System.out.println ("S3 = = s2?" + (S3 = =s2));7 }8S1 = = S2?false9S3 = = S2?true

An example of a richer string comparison

1  Public classTest {2  Public Static voidMain (string[] args) {3String Hello = "Hello", lo = "Lo";4System.out.println ((hello = = "Hello") + "");5System.out.println ((Other.hello = = Hello) + "");6System.out.println (Other. Other.hello = = Hello) + "");7System.out.println ((Hello = = ("Hel" + "lo") + "");8System.out.println ((Hello = = ("Hel" +lo) + "");9System.out.println (Hello = = ("Hel" +lo). Intern ());Ten }    One } A classOther {StaticString Hello = "Hello"; } -  PackageOther ; -  Public classOther { Public StaticString Hello = "Hello"; } the 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.

Java basic knowledge hardening 104: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.