Why false in (I1 == I2) ? And how to compare them ? In case 3 is all as expected | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why false in (I1 == I2) ? And how to compare them ? In case 3 is all as expected

https://code.sololearn.com/cHCTUQ0JDmD3/?ref=app

14th Aug 2019, 11:13 AM
UraL
3 Answers
+ 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
14th Aug 2019, 11:35 AM
Dlite
Dlite - avatar
+ 1
But when I use println, why is displayed value but not address?
14th Aug 2019, 11:43 AM
UraL
+ 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);
14th Aug 2019, 12:10 PM
zemiak