integer - Using == operator in Java to compare wrapper objects -
i'm reading scjp java 6 kathy sierra , bert bates , book confusing me much. on page 245 state following code below.
integer i1 = 1000; integer i2 = 1000; if(i1 != i2) system.out.println("different objects"); //prints output different objects
then on next page have following code
integer i3 = 10; integer i4 = 10; if(i3 == i4) system.out.println("same objects"); //prints output same objects
i'm confused! when try out on own seems cannot use == compare same way use equals() method. using == gives me 'false' if integer variables set same value (i.e. 10). correct? using == compare same integer object (with same values) result in 'false'
the key answer called object interning. java interns small numbers (less 128), instances of integer(n)
n
in interned range same. numbers greater or equal 128 not interned, hence integer(1000)
objects not equal each other.
Comments
Post a Comment