Java constant pooling technology
The common point in Java is to say that constant pooling technology is Java-level caching technology, which can easily and quickly create an object. When an object is needed, get it from the pool (if there is no one, create one and put it into the pool). When the same variable is needed next time, you don’t need to recreate it, thus saving space.
Eight basic types of Java wrapper classes and object pools
The basic types of wrapper classes in java, including Byte, Boolean, Short, Character, Integer, and Long, implement constant pooling technology (except Boolean, they are only supported for values less than 128)
For example, Integer object
Integer i1 = 100;Integer i2 = 100;// The above two lines of code, using the automatic boxing feature, compiled into // Integer i1 = Integer.valueOf(100);// Integer i2 = Integer.valueOf(100);System.out.println(i1 == i2);Integer i3 = 128;Integer i4 = 128;System.out.println(i3 == i4);
Execution results:
truefalse
Reason I'll look at the source code of the valueOf() of the Integer object
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; // Recreate an Integer object that is not in this range return new Integer(i);}Only Integer objects of -128~127 will be cached in IntegerCache, and constant pooling technology is used.
private static class IntegerCache { ... static final Integer cache[];// The cache of the IntegerCache class is modified with final, it is a static array that plays a cache role}Constant pool of String class
The constant pool of String type is quite special. The constant pool of String class is placed in java heap in jdk7. How to use it includes:
• Directly use literal declarations, such as String s = "abc";
•Use String.intern();
The above brief discussion on Java constant pool is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.