+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

8/14/2019 11:13:53 AM

UraL

4 Answers

New Answer

+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

+2

UraL When using "==" operator on objects it compares references (if two objects are same in memory) not their contents/values. It seems for Integer objects created with int value in the range -128 to 127 (both inclusive) two objects will always compare equal. To compare one Integer object to another Integer object use Integer.compareTo method I1.compareTo(I2) returns 0 if I1 == I2 (numerically) < 0 if I1 < I2 and > 0 if 11 > I2 Also the constructor Integer(int) and Integer(String) has been deprecated since Java 9

+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);