+ 1
Why false in (I1 == I2) ? And how to compare them ? In case 3 is all as expected
4 ответов
+ 2
Using the "new" keyword create objects, whose actual values are stored on the "heap", the address of these heap objects are what are stored in the variables.
Integer i1 = new Integer(100);
Integer i2 = new Integer(200);
creates two different objects, (although the same value) and stores the location of these objects in variables i1 and i2.
When you compare them via == ,you actually compare their addresss, which aren't the same
+ 1
But when I use println, why is displayed value but not address?
+ 1
use I1.intValue() == I2.intValue() instead,
or I1.equals(I2);
println() calls Integer.toString() method, which get value from object
//try this case 4. compare result to case 3 :
Integer I5 = 130, I6 = 130;
System.out.printf("%d, %d, %b\n", I5, I6, I5==I6);