In-depth exploration of Java constant pool and java constant pool

Source: Internet
Author: User

In-depth exploration of Java constant pool and java constant pool

Java constant pools are generally divided into two types: static constant pools and runtime constant pools.

Static constant pool: constant pool in the class file. The constant pool in the class file contains the string (number) literal value, class and method information, occupying most of the space in the class file.

Runtime constant pool: After the JVM completes the loading class, it loads the constant pool in the class file into the memory and saves it in the method area. The constant pool we usually talk about is the runtime constant pool in the method area. Compared with the constant pool of the CLass file, Java does not require constants to be generated only during compilation, that is to say, it is not the content of the constant pool preset into the CLass file that can enter the constant pool for running in the method area. During running, new constants may also be placed in the pool, the intern () method of the String class is widely used by developers.

Program counter: the assembly line for program execution, indicating which command to execute next time.

Local method Stack: the stack used by JVM to call the operating system method.

Virtual Machine Stack: the stack used by JVM to execute java code

Virtual Machine heap: the place where the object is stored. All new objects in the java program are stored in the heap.

Method Area: stores constants, class information, and static variables. It can be understood as the location where class files are stored in the memory.

Benefits of constant pool:

Constant pool is used to avoid frequent creation and destruction of objects and affect system performance. It shares objects.

For example, in the String constant pool, all the strings are put in a constant pool during compilation.

1. Memory saving space: All strings with the same nominal value in the constant pool are merged, occupying only one space

2. Save running time: when comparing strings, = is faster than equals. For two referenced variables, you can only use = to determine whether the referenced variables are equal, so that you can determine whether the actual values are equal.

= The meaning of basic data types and object representatives is different.

For the basic data type: = compare the value of the basic data type for the object: = compare the memory address of the object in the memory

Packaging class and constant pool of eight basic data types

In Java, most of the basic data type packaging classes implement the constant pool technology, that is, Byte, Short, Integer, Long, Character, Boolean.

Integer i1 = 40;Integer i2 = 40; System.out.println(i1==i2);//true

Byte, Short, Integer, Long, Character. By default, cache data of the corresponding type [-128,127] is created and stored in the constant pool, if the value exceeds this range, a new object will still be created.

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);  }
Integer i1 = 400;Integer i2 = 400; System.out.println(i1==i2);//false

2. The packaging Float and Double types of two floating point numbers do not implement the constant pool technology.

Double d1 = 2.5;Double d2 = 2.5; System.out.println(d1==d2);//false

3. Application constant pool scenario

(1 ). integeri1 = 40; Because Integer is the packaging class of the basic data type int, it is an object, so Java will execute the automatic packing operation during compilation to directly encapsulate the code into Integeri1 = Integer. valueOf (40) to use objects in the constant pool

(2). Integeri1 = newInteger (40); in this case, a new object is created.

Integer i1 = 40;Integer i2 = new Integer(40); System.out.println(i1 == i2);//false

In this case, new Integer does not automatically compress existing constants in the constant pool, but directly generates a new object in the heap.

4. Integer explanation

Integer i1 = 40;    Integer i2 = 40;    Integer i3 = 0;    Integer i4 = new Integer(40);    Integer i5 = new Integer(40);    Integer i6 = new Integer(0);    Integer i7 = 128;    Integer i8 = 128;     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));    System.out.println("i7=i8  " + (i7 == i8));
i1=i2  truei1=i2+i3  truei1=i4  falsei4=i5  falsei4=i5+i6  true40=i5+i6  truei7=i8  false

Explanation: The statement i4 = i5 + i6. Because the + operator is not applicable to Integer objects, the i5 and i6 perform the automatic unpacking operation to add the values, that is, i4 = 40. Then the Integer object cannot be directly compared with the value, so i4 Automatically splits the box into an int value of 40, and finally converts this statement to a value of 40 = 40 for comparison.

String class and constant pool

1. String object Creation Method

String s1 = "abdcd";String s2 = new String("abcd");System.out.println(s1==s2);//false

There are differences between the two creation methods. The first is to take objects in the constant pool, and the second is to create new objects in the heap memory space.

You only need to use new to create a new object in the heap.

2. Connection expression +

(1). Only new objects created using "+" connections between String objects created using "" containing text will be added to the String constant pool.

(2). For other forms such as two object references, the new object is not added to the String constant pool for the object connection created by using the "+" method or the new method.

String str1 = "str";String str2 = "ing"; String str3 = "str" + "ing";String str4 = str1 + str2;System.out.println(str3 == str4);//false String str5 = "string";System.out.println(str3 == str5);//true
Public static final String A = "AB"; // constant Apublic static final String B = "cd"; // constant Bpublic static void main (String [] args) {String s = A + B; // concatenates two constants with + to initialize String t = "abcd"; if (s = t) {System. out. println ("s equals t, they are the same object");} else {System. out. println ("s is not equal to t, they are not the same object");} s is equal to t, they are the same object

Both A and B are constants and their values are fixed. Therefore, the value of s is fixed. It is determined when the class is compiled. That is to say: String s = A + B; equivalent to: String s = "AB" + "cd ";

Public static final String A; // constant Apublic static final String B; // constant Bstatic {A = "AB"; B = "cd ";} public static void main (String [] args) {// concatenates two constants with + to initialize s. 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 is not equal to t, they are not the same object");} s is not equal to t, they are not the same object

Although A and B are defined as constants, they are not immediately assigned values. Before calculating values of s, it is a variable to determine when values are assigned and what values are assigned. Therefore, before being assigned A value, A and B are similar to A variable. S cannot be determined during the compilation period, but can only be created at runtime.

3. Strings1 = newString ("xyz"); how many objects are created?

Consider the class loading stage and actual execution time.

(1) the class is loaded only once for a class ." Xyz "is created and resident when the class is loaded. (If the" xyz "string already exists before the class is loaded, you do not need to create the" xyz "instance for Resident again). The resident string is placed in the global shared String constant pool.

(2) When this code is subsequently executed, the String instance corresponding to the "xyz" literal has been fixed and will not be created again. So this code copies the objects in the constant pool to heap, and transfers the reference of this object in heap to s1.

This statement creates two objects.

4. java. lang. String. intern ()

Another important feature of the runtime constant pool relative to the CLass file constant pool is that it is dynamic. Java does not require constants to be generated only during compilation, that is to say, it is not the content of the constant pool preset into the CLass file that can enter the constant pool for running in the method area. During running, new constants may also be placed in the pool, the intern () method of the String class is widely used by developers.

The intern () method of String searches for whether a equal String exists in the constant pool. If yes, it returns a reference to the String. If no, it adds its own String to the constant pool.

Public static void main (String [] args) {String s1 = new String ("computer"); String s2 = s1.intern (); String s3 = "computer"; System. out. println ("s1 = s2? "+ (S1 = s2); System. out. println (" s3 = s2? "+ (S3 = s2 ));}
s1 == s2? falses3 == s2? true

Summary

The above is all about the in-depth exploration of the Java constant pool in this article, I hope to help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message.

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.