Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equality doubt

 
Ravindra Harige
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


why the output of above code is

and not

??

regards
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has come up recently. Search the forums for it.

Of course, using == to compare the values of objects is almost always wrong anyway.
 
Ricky Martaputra
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that's the autoboxing feature..

Compare two Integers with '==' only return true with between -128 to 127.
Otherwise, it returns false.
 
prateek chaudhari
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its all about references comparison.

If I am not wrong ..You have crated 4 Integer objects, when you compare object references using == then the values inside reference (which is something how to get object values from heap) is checked while when you use equals() method which is inherited by every class in Java you compare the values pointed by the reference variables.

So its not necessary that always your first condition evaluates to true.

but your second condition will always evaluate to true,(Till values are same.) cause equals() is overridden in Integer class.
[ August 09, 2007: Message edited by: prateek chaudhari ]
 
Ravindra Harige
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot !
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic