• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why == operator return true?  RSS feed

 
Dinesh Kumar J
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i =10;
Integer j = new Integer(10);
System.out.println(i==j);


Output: true

Same thing happens for all the 8 Primitive datatypes.

For String or another objects, if we create objects in the above way, it returns false. But for Primitive data types == operator returns true. Why?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66264
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
j is being auto-unboxed to an int. At that point it's primitives that are being compared.

It wouldn't work with Strings because Strings are objects and must be compared with .equals().
 
Jaikiran Pai
Sheriff
Posts: 10447
227
IntelliJ IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has been asked numerous times before. Here's a post containing links to those discussions http://www.coderanch.com/t/497028/java/java/possible-please-explain#2238663
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dinesh Kumar Kumar wrote:For String or another objects, if we create objects in the above way, it returns false.

Well, for one thing, you can't create other objects the same way (ie, with literals).

Second, primitives are NOT objects, so chances are that they will behave differently.

Third (and this is a tip) when comparing a primitive with an object - which will usually be its wrapper type - be explicit about what you want to happen.
Your (i==j) above could be interpreted in two ways:
(i == j.intValue())
or
(Integer.valueOf(i) == j)
and the two comparisons are different: The first is a value comparison, the second an identity comparison, and they work very differently.

Even better still, use equals(). That way there's no possible ambiguity.

HIH

Winston
 
Dinesh Kumar J
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all for clarifying my doubt.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!