(original
thread here)
Hi,
I did a little more investigation using
Java 6. It appears that a Wrapper Object is == to a primitive, if the value of the Wrapper Object is exactly equal to the value of the primitive. Please see the output of a
test program that I wrote:
The fact that there is a pool of bytes in the range of 127 to -128 in the JVM doesn't seem to come into play in these comparisons. The type of the Wrapper Object doesn't seem to make any difference either; it is strictly a value based comparison.
Regards,
Harry
The output of the program is listed below:
C:\TEMP>java Dumper
Byte B1 = new Byte((byte)127);
Byte B2 = 127;
Byte B3 = 129; \\ compiler error
Byte B3 = new Byte((byte) 129); \\ == -127
byte b2 = 127;
byte b3 = -127; \\ == (byte)129
Integer I1 = new Integer( 127 );
Integer I2 = new Integer( 128 );
Integer I3 = new Integer( 32769 );
Short S1 = new Short((short)127);
Short S2 = new Short((short)128);
Short S3 = new Short((short)32769);
int i2 = 128;
int i3 = 32769;
short s1 = 127;
short s2 = 128;
long l2 = 128;
B1 == 127 is true
B2 == 127 is true
B3 == -127 is true
B3 == b3 is true
S1 == 127 is true
S2 == 128 is true
S1 == s1 is true
Short S3 = new Short((short)32769);
S3.shortValue() = -32767
S3 == i3 is false.
S3 == -32767 is true
S3 == (long)-32767 is true
S2 == l2 is true
I1 == 127 is true
I2 == s2 is true
I3 == 32769 is true
S2 == I2 \\ compiler error
\\ incomparable types
C:\TEMP>