Java Reference
In-Depth Information
System.out.println(i1 == i2); // Output: false
System.out.println(i1 < i2); // Output: false
System.out.println(i1 > i2); // Output: false
i2 = 30001;
System.out.println(i1 < i2); // Output: true
System.out.println(i1+i2); // Output: 60001
Withoneexception,thisexample'soutputisasexpected.Theexceptionisthe i1 ==
i2 comparisonwhereeachof i1 and i2 contains30000.Insteadofreturningtrue,as
is the case where each of i1 and i2 contains 127, i1 == i2 returns false. What is
causing this problem?
Examinethegeneratedcodeandyouwilldiscoverthat Integer i1 = 127; is
convertedto Integer i1 = Integer.valueOf(127); and Integer i2 =
127; isconvertedto Integer i2 = Integer.valueOf(127); .Accordingto
valueOf() 'sJavadocumentation,thismethodtakesadvantageofcachingtoimprove
performance.
Note valueOf() isalsousedwhenaddingaprimitive value toacollection. For
example, col.add(27) is converted to col.add(Integer.valueOf(27)) .
Integer maintains an internal cache of unique Integer objects over a small
range of values. The low bound of this range is -128, and the high bound defaults
to 127. However, you can change the high bound by assigning a different value to
system property java.lang.Integer.IntegerCache.high (via the
java.lang.System class's String setProperty(String prop, String
value) method—I demonstrated this method's getProperty() counterpart in
Chapter 4 ) .
Note Eachof Byte , Long ,and Short alsomaintainsaninternalcacheofunique
Byte , Long , and Short objects, respectively.
Because ofthecache, each Integer.valueOf(127) call returnsthesame In-
teger object reference, which is why i1 == i2 (which compares references)
evaluates to true. Because 30000 lies outside of the default range, each In-
teger.valueOf(30000) callreturnsareferencetoanew Integer object,which
is why i1 == i2 evaluates to false.
Incontrastto == and != ,whichdonotunboxtheboxedvaluespriortothecomparis-
on,operatorssuchas < , > ,and + unboxthesevaluesbeforeperformingtheiroperations.
Search WWH ::




Custom Search