Reputation: 2796
int x = 10;
int y = 10;
Integer x1 = new Integer(10);
Integer y1 = new Integer(10);
System.out.println(x == y);
System.out.println(x1 == y1);
The first sop will print true whereas the second one will print false. What is the actual problem ?
Upvotes: 0
Views: 91
Reputation: 2691
first sop print true because int x and y contains same bit pattern for 10.
In second approach x1 and y1 are both different object reference variable of Integer type so they are point to different object in memory that's why in second sop you will get false.
if you want to check two Integer's equality you can use
x1.equals(y1)
it will return true.
Upvotes: 0
Reputation: 1874
The second one is comparing Object Id's.Since every object is having a unique Id it is returning false.
Upvotes: 2
Reputation: 3534
The second approach is not checking the values rather the objects.
If you want to compare the values of 2 Integer objects you would have to use appropriate methods like compareTo(Integer)
Like mentioned in the comments if you want to check for equality only you can use equals
Upvotes: 2