cache pool

public class Test {
public static void main(String args[]) {
String hi1 = “Hello”;
String hi2 = “Hello”;
String hi3 = “Hell” + “o”;
String hi4 = “Hell”;
hi4 += “o”;

Integer one1 = 1;
Integer one2 = 0;
one2 += 1;

Integer many1 = 256;
Integer many2 = 255;
many2 += 1;

A: System.out.println(hi1 == hi2);
B: System.out.println(hi1 == hi3);
C: System.out.println(hi1 == hi4);
D: System.out.println(one1 == one2);
E: System.out.println(many1 == many2);




  • == return true if two objects point to the same reference because the objects are not primitive type
  • have string pool
  • internpublic String intern()

    Returns a canonical representation for the string object.

    A pool of strings, initially empty, is maintained privately by the class String.

    When the intern method is invoked, if the pool already contains a string equal to this String object

 as determined by the equals(Object) method, then the string from the pool is returned.
 Otherwise, this String object is added to the pool and a reference to this String object is returned.
  • compiler checks the string pool
  • complier checks that at the initialization of strings
  • “hell” + “o” creates two strings
  • there will be two strings with value “hello” in the string pool
    If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive),
 then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
means there will be Integer pool like the string pool for Integers between -128 and 127
  • why? for optimization

for example, if not so, Boolean b = true will create many objects without optimization

but with optimization, the fact is there will only two Boolean objects in the pool

Boolean x = true;
Boolean y = true;
System.out.println(x == y);   => true

  • boxed primitive cannot be cached too many because the objects is relatively large

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s