Constants and constant pools in Java

Source: Internet
Author: User

1. Illustrate variable constant literals

1 int a=10; 2 float b=1.234f; 3 String c= "abc"; 4 Final long d=10l;

A,b,c is a variable, d is a constant, both are lvalue; 10,1.234f, "abc", 10L are literal;

2, Chang:

Chang is specifically used to store constants in the memory area, the constant pool is divided into: static constant pool and run-time pool;

Static constant pool: a constant pool in a *.class file, a constant pool in a class file that contains not only strings, numeric literals, but also classes, methods, and occupies most of the space of a class file.

Run a constant pool: a JVM virtual machine after the class mount operation is completed, the constant pool in the class file is loaded into memory and stored in the method area, which we often say is the pool of running constants in the method area.

Note: Java Virtual machine memory is divided into virtual machine stack, virtual machine heap, local method stack, program counter, method area (Jdk8, remove method area, instead of Metaspace region)

2.1 String constant Pool

1 String s1 = "Hello"; 2 String s2 = "Hello"; 3 String s3 = "Hel" + "lo"; 4 string s4 = "Hel" + new String ("Lo"); 5 String s5 = new String ("Hello"); 6 String s6 = S5.intern (); 7 String s7 = "H"; 8 String s8 = "Ello"; 9 String S9 = s7 + s8;10           System.out.println (S1 = = s2);  True12 System.out.println (S1 = = S3);  True13 System.out.println (S1 = = S4);  False14 System.out.println (S1 = = S9);  False15 System.out.println (S4 = = S5);  False16 System.out.println (S1 = = S6);  True

The Java program is compiled and run in two steps:

S1 = = s2, compile, the literal "Hello" directly into the class file in the constant pool, so that the reuse, loaded in the run constant pool, S1, S2 point to the same memory address, so equal.

S1 = = s3, compile, this stitching will be optimized, the compiler directly spelled well, in the class file is optimized to string s3 = "Hello", so S1 = = S3 was established.

S1 = = S4, at compile time, how the new String ("Lo") is generated is not deterministic, is an unpredictable part, the compiler does not optimize, you must wait until run time to determine the result, the resulting reference in the heap, not the method area, so the address must be different.

S1 = = S9 compile, S7, S8 in the assignment when the string literal used, but stitching into S9, S7, S8 as two variables, are unpredictable, compiler is compiler, it is not possible when the interpreter, so do not optimize, wait until the runtime, S7, S8 stitching into the new string, The address in the heap is not deterministic and cannot be the same as the S1 address in the method area constant pool.

S4 = = S5 have no explanation, absolutely not equal, both are in the heap, but the address is different.

S1 = = S6 These two equals are fully attributed to the Intern method (manually adding constants to the constant pool), S5 in the heap, the content is Hello, the Intern method tries to add the hello string to the constant pool, and returns its address in the constant pool. Because the hello string is already in the constant pool, the Intern method returns the address directly, whereas S1 points to the constant pool at compile time, so S1 and S6 point to the same address, equal.

2.2 8 basic types of wrapper classes and object pools

Most of the basic types of wrapper classes in Java implement the constant pool technique, which is byte,short,integer,long,character,boolean, and the other two types of floating-point wrapper classes are not implemented. Also byte,short,integer,long,character these 5 types of integer wrapper classes can use object pooling only when the corresponding value is less than or equal to 127, which is why the object is not responsible for creating and managing objects greater than 127 of these classes.

1  Public classtest{2 3  Public Static voidMain (string[] args) {4 5    //5 Kinds of byte,short,integer,long,character objects of plastic packaging class,6 7    //you can use a constant pool when the value is less than 1278 9Integer i1=127;Ten  OneInteger i2=127; A  -System.out.println (I1==I2)//Output True -  the    //when the value is greater than 127, the object is not taken from the constant pool -  -Integer i3=128; -  +Integer i4=128; -  +System.out.println (I3==I4)//Output False A  at    //the Boolean class also implements the constant pool technique -  -Boolean bool1=true; -  -Boolean bool2=true; -  inSystem.out.println (bool1==bool2);//Output True -  to    //floating-point type wrapper class does not implement constant pool technology +  -Double d1=1.0; the  *Double d2=1.0; $ Panax NotoginsengSystem.out.println (D1==D2)//Output False -  the   +  A } the  +}

2.3 Viewing constant pools

1 String s = "HI";

After compiling the code into a class file, open the class file in binary format with Winhex.

The structure of the class file:

1. The beginning of the 4 bytes is the class file magic number, used to identify this is a class file, white session point is the file header, both: CA FE BA be.

2. Followed by 4 bytes is the Java version number, where the version number is 34, is compiled with JDK8.

3. Next is the constant pool entrance, the entrance with 2 bytes to identify the constant pool constant number, in this case the value is 1 A, the decimal is 26, that is, there are 25 constants, where the No. 0 constant is a special value, so there are only 25 constants.

4. Constant pools hold various types of constants, they all have their own type, and all have their own storage specifications, string constants start with 01 (1 bytes), and then the string length is recorded in 2 bytes, then the actual contents of the string. In this case: 01 00 02 68 69.

The next thing to say about running a constant-time pool, because the run-time pool is in the method area, we can set the method area size by JVM parameters:-xx:permsize,-xx:maxpermsize, which indirectly limits the constant pool size.

Assume that the JVM startup parameter is:-xx:permsize=2m-xx:maxpermsize=2m, and then run the following code:

1//Hold reference to prevent automatic garbage collection 2 list<string> List = new Arraylist<string> (); 3         4 int i = 0;5         6 while (true) {7     /// Manually add constant 8 List.add (string.valueof (i++) to the constant pool by using the Intern method     . Intern ()); 9}

The program immediately throws: Exception in thread "main" Java.lang.outOfMemoryError:PermGen space exception. PermGen space is the method area, sufficient to illustrate the Chang in the method area.

In Jdk8, the method area is removed and replaced with the Metaspace region, so we need to use the new JVM parameter:-xx:maxmetaspacesize=2m, which is still running as above code, throws: Java.lang.OutOfMemoryError: Metaspace exception. Similarly, the run-time constant pool is divided in the Metaspace area.

Reference:

Touch Java constant Pool

Constants and constant pools in Java

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.