Java constant Pool

Source: Internet
Author: User

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 is necessary to create some objects quickly and easily, saving a lot of time when the equality variable needs to be created repeatedly. A constant pool is actually a memory space    , which is different from the heap space of objects created with the New keyword.    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 class test{

public static void Main (string[] args) {

S1,s2 in different spaces in the heap

String S1=new string ("Hello");

String S2=new string ("Hello");

System.out.println (S1==S2);//Output False

S3,S4 in the same space in the pool

String s3= "Hello"

String s4= "Hello";

System.out.println (S3==S4);//Output True

}

}

strings created with new string () are not constants and cannot be determined at compile time, so the strings created by new string () are not placed in the constant pool, they have their own address space . the invariance mechanism of the string object (memory) causes a large number of objects to be generated when the string strings are modified, because a new string is generated each time the strings are changed. In order to use memory more efficiently, the constant pool encounters a string string at compile time, it checks to see if the same string string already exists within the pool, and if found, points the reference to the existing string object without creating any new string constant object. Not found to create new again.    So any modification to a string object will result in a new string object, which still exists and waits for garbage collection . Code:

String a = "test";

String b = "Test";

String B = b + "Java";

A, B points to the constant value in the constant pool, "text", b=b+ "Java", after the first point to a constant, the content is "test", by doing A + "Java" operation on B, the value pointed before B has not changed, but at this time B does not point to the original variable value, Instead, it points to another string variable with the content "text Java". The original variable still exists in memory, but the B variable no longer points to it.

Eight 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, the other two kinds of floating-point type of packaging class is 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. some of the corresponding test code:

public class test{

public static void Main (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 127

Integer i1=127;

Integer i2=127;

System.out.println (I1==I2); Output true//value greater than 127 does not fetch objects from a constant pool

Integer i3=128;

Integer i4=128;

System.out.println (I3==I4); Output false

The Boolean class also implements the constant pool technique

Boolean bool1=true;

Boolean bool2=true;

System.out.println (bool1==bool2); Output true//floating-point type wrapper class does not implement constant pool technology

Double d1=1.0;

Double d2=1.0;

System.out.println (D1==D2); Output false

}

}

Code additions to an integer object

public static Integer valueOf (int i) {

Final int offset = 128;

if (i >= -128 && i <= 127) {

return integercache.cache[i + offset];

}

return new Integer (i); }

When you give an int value directly to an integer object, it actually calls the

ValueOf method, and then you assign this value is very special, is 128, then the cache method is not done, the equivalent of a new two of the object. So the two lines of code that define a and B in the question are similar to the following:

Integer a = new integer (128);

Integer b = new 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;

Integer B = 127;

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

It is best to use equals when making object comparisons, allowing you to control it for your own purposes. This leads to Equals () and ==,equals compare the string literal, which is the comparison content, = = comparison reference.

Take a look at the contents of the Integercache class:

private Static Class Integercache {

Private 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 the -128~127 scope, you do not need to redefine the application space, which is the same object---in Integercache.cache, which can improve the efficiency to some extent.

Additions to String

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 for constants, so it is also referenced 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.

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

If there is a reference returned, no then add your own string into the constant pool, note: Just the string part.

so there will be 2 copies, the part of the constant pool is privately owned and managed by the string class, and its share continues to be used by the object life cycle. returns a normalized representation of a string object

a string pool with an initial value of NULL, 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. ------------------------------------Code Demo Supplement-------------------------------------

String s0= "Java";

String S1=new string ("Java");

String S2=new string ("Java");

S1.intern ();

S2=s2.intern (); Assign a reference to "Java" in the constant pool to S2

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

------------------------------------Code Demo Supplement-------------------------------------

String S1=new string ("Java");

String S2=s1.intern ();//s1 checks the constant pool and finds that no copy of its own string goes in.

S2 The address of the constant pool referencing the string

SYSTEM.OUT.PRINTLN (s2 = = S1);//false

System.out.println (S2==s1.intern ());//true

System.out.println (S1==s1.intern ());//False

Java 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.