• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Why == operator return true?  RSS feed

 
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?
 
Marshal
Posts: 67164
169
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().
 
Sheriff
Posts: 10445
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
 
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!