Granny's Programming Pearls "inside of every large program is a small program struggling to get out" JavaRanch.com/granny.jsp

# Wrapper problem

Bob CHOI
Ranch Hand
Posts: 127
My code below,

it prints out:

false

Are wrapper classes immutable? Do they use constants pool? Why is the result not true!???

marc weber
Sheriff
Posts: 11343
First, == compares values. For objects, this means references. So if A and B reference different objects, then (A == B) will return false, regardless of how A and B might relate using the equals method.

Second, the code above uses boxing to wrap int values as Integer objects, and this introduces some interesting behavior. According to the JLS (5.1.7)...
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

In this case, 0xFEDC is a hexadecimal representation of 65244, so it is not between -128 and 127. Therefore, there is no guarantee that i1 and i2 will point to the same wrapped instance.

Bob CHOI
Ranch Hand
Posts: 127
Marc, thanks for the reference to JLS.

i'm wonderring why? if both reference variables, namely i1&i2, point to the same constant object, namely oxFEDC, they should have been equal, i mean "=="

In this case, 0xFEDC is a hexadecimal representation of 65244, so it is not between -128 and 127. Therefore, there is no guarantee that i1 and i2 will point to the same wrapped instance.

sorry, i got it above now, thanks again
[ December 14, 2006: Message edited by: Bob CHOI ]

Bob CHOI
Ranch Hand
Posts: 127
modified code below:

class Test011 {

public static void main(String[] args) {

Integer i1 = 0xFEDC;
Integer i2 = 0xFEDC;
System.out.println(i1==0xFEDC);

}

}

it prints out:

true

The reason has to be not 0xFEDC boxed to Integer constant but i1 unboxed to int, hasn't it?

marc weber
Sheriff
Posts: 11343
Originally posted by Bob CHOI:
...i1 unboxed to int, hasn't it?

Yes. (See 15.21.1.)