Java Foundation-Constant pool

Source: Internet
Author: User

In the class file, "constant pool" is the most complex and most noteworthy content.

Java is a dynamically connected language, the role of a constant pool is very important, in addition to the constant pool contains the various basic types defined in the code (such as int, long, and so on) and the object type (such as string and array) of the constant value also contains some of the textual form of symbolic references, such as:

The fully qualified name of the class and interface;
The name and descriptor of the field;
Methods and names and descriptors.

In C, if a program calls a function in another library, the position of the function in the library (that is, the offset from the beginning of the library file) is written in the program at the time of the connection, and the function is called directly to the address at runtime;

In the Java language, this is not the case, and everything is dynamic. At compile time, if a call to another class method or a reference to another class field is found, the record into the class file can only be a symbolic reference in text form, and during the connection, the virtual machine will find the corresponding method or field according to the text information.

So, unlike the so-called "constants" in the Java language, the "constant" content in a class file is not rich, and these constants are concentrated in one area of the class, followed by one, which is called a "constant pool."

The constant pool technique in Java, which occurs when an object is needed, can be taken out of the pool (if one is not created in the pool), and it will save a lot of time when you need to repeat the creation of equal variables. A constant pool is actually a memory space, unlike the heap space where objects created with the New keyword are located. This article only discusses Java constant pool technology from the Java user's point of view, and does not involve the principle and implementation method of constant pool. Personally, if you are really focused on Java, you have to have a certain understanding of these details. But it is not necessary to know the principle and the concrete way to implement it.

1, constants in the pool objects and objects in the heap

 Public classtest{Integer I1=NewInteger (1); Integer I2=NewInteger (1); //I1,i2 in different memory spaces in the heap, respectivelySystem.out.println (I1==I2);//Output False

Integer i3=1; Integer I4=1; //I3,i4 points to the same memory space in a constant poolSystem.out.println (i3==I4);//Output True//Obviously, I1,i3 is in a different memory space.System.out.println (I1==I3);//Output False}

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 . Here are some of the corresponding test codes:

 Public classtest{ Public Static voidMain (string[] args) {//5 Kinds of byte,short,integer,long,character objects of plastic packaging class,//you can use a constant pool when the value is less than 127Integer I1=127; Integer I2=127; System.out.println (I1==I2)//Output True//when the value is greater than 127, the object is not taken from the constant poolInteger i3=128; Integer I4=128; SYSTEM.OUT.PRINTLN (i3==I4)//Output False//the Boolean class also implements the constant pool techniqueBoolean bool1=true; Boolean bool2=true; System.out.println (Bool1==BOOL2);//Output True//floating-point type wrapper class does not implement constant pool technologyDouble D1=1.0; Double D2=1.0; System.out.println (D1==D2)//Output False  }}

3,string also implements the constant pool technology

The string class is also a much-used class in Java, and also implements the technique of constant pooling for the convenience of creating a String object, the test code is as follows:

 Public classtest{ Public Static voidMain (string[] args) {//s1,s2 in different spaces in the heapString S1=NewString ("Hello"); String S2=NewString ("Hello"); System.out.println (S1==S2)//Output False//S3,S4 in the same space in the poolString S3= "Hello"; String S4= "Hello"; System.out.println (S3==S4);//Output True}}

Integer encapsulation:

   Public Static Integer valueOf (int  i) {         finalint offset =N;          if // must cache            return Integercache.cache[i + offset];         }           return New Integer (i);       }

When you give an integer object an int value, in fact it calls the ValueOf method, and then you assign this value is very special, is 128, then does not have the cache method, the equivalent of the new two of the object. So the two lines of code that define a and B in the question are similar to the following:

New Integer (thenew Integer (128);

I'll ask you this time, what is the result of the output? You know it's false. If you change this number to 127, then execute:

Integer A = 127= 127;

System.out.println (A = = B);
The result is: true

From the above, it is best to use equals when comparing objects, which is easy to control according to our own purposes.

Take a look at the contents of the Integercache class:

 private  static  class   Integercache { private  Span style= "color: #000000;" > Integercache () {}  static  final Integer cache[] = new  integer[-( -128) + 127 + 1 static   { for  (int  i = 0; i < cache.length; I++)      Cache[i]  = new  Integer (i-128

Because cache[] is a static array in the Integercache class, that is, it only needs to be initialized once, that is, static{... } section, so if the integer object is initialized with a range of -128~127, there is no need to redefine the application space, which is the same object---in Integercache.cache, which can improve the efficiency to some extent.

The Intern () method of string finds whether there is a equal equal string in the constant pool.

If any, returns a reference, without adding its own string into the constant pool,

Note that just the string part,

So there will be 2 copies, the part of the constant pool is held and managed by the string class, and its share continues to be used by the object life cycle.

API Explanation:

Returns a normalized representation of a string object.

An initially empty string pool, which is privately maintained by the class string.

When the Intern method is called, if the pool already contains a string equal to this string object (which is determined by the Equals (object) method), the string in the pool is returned. Otherwise, this string object is added to the pool, and a reference to this string object is returned.

It follows for any two strings s and T, and s.intern () = = T.intern () is true only if and only if S.equals (t) is true.

All literal strings and string-assignment constant expressions are internal. String literals are defined in the §3.10.5 of Java Language specification.

 String s0= "java" ;   string S1  =new  String ("java"  =new  String ("java"  =s2.intern (); //   System.out.println (S0  ==s1); // false intern returns no reference variable received ~ s1.intern (); equals Scrap code.   System.out.println (S0  ==s1.intern ()); // true   System.out.println (S0  ==s2); // true  
  String s1=New string ("Java");   String S2=s1.intern (); // S1 checking the constant pool find that you're not copying your   own string in. // S2 The address of the constant pool referencing the string     = = S1); // false   System.out.println (S2==s1.intern ()); // true   System.out.println (S1==s1.intern ()); // false Finally, the story of equals () and = = is used to compare strings, be sure to use equals, do not use = =

Java Foundation-Constant pool

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.