Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

Boxing & unboxing

sakthi karthik
Greenhorn
Posts: 28
i cant understand the following expalanation. can anyone please explain this

Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");

Produces the output:
different objects
meaningfully equal

Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");

This example produces the output:
same object
meaningfully equal

The equals() method seems to be working, but what happened with ==
and != ? Why is != telling us that i1 and i2 are different objects, when == is saying
that i3 and i4 are the same object? In order to save memory, two instances of the
following wrapper objects will always be == when their primitive values are the same:
Boolean
Byte
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127

Ulf Dittmer
Rancher
Posts: 42968
73
Short and Integer from -128 to 127

Does 10 fall into this range? How about 1000?

sakthi karthik
Greenhorn
Posts: 28
now i understand , thank you

vinal sen
Ranch Hand
Posts: 37
But Karthik,

do remember

produces "not equal".