• Post Reply Bookmark Topic Watch Topic
  • New Topic

AutoBoxing, ==, != & equals  RSS feed

 
Sridhar Iyer
Greenhorn
Posts: 5
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Can somebody let me know why the output for this is so different ? I understand the concept but I don't understand why is it behaving so differently for different values.





Output:

I and J are not equal
A and B have same values
A equals B
 
Gaurangkumar Khalasi
Ranch Hand
Posts: 187
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sridhar Iyer,
Welcome to Java Ranch...

In order to save memory, two instances of the following wrapper objects (created through boxing), will always be == when their primitive values are the same:
■ Boolean
■ Byte
■ Character from \u0000 to \u007f (7f is 127 in decimal)
■ Short and Integer from -128 to 127
 
Sridhar Iyer
Greenhorn
Posts: 5
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your reply GaurangKumar. I understand, why the statement after == is getting printed and the one you have given is from Sierra Kathy book. But I don't understand why is it behaving differently for different values.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sridhar Iyer wrote:But I don't understand why is it behaving differently for different values.

What different values? All we can go by is what you've posted, and the results seem perfectly reasonable to me if you look at Gaurangkumar's post.

The fact is, you should NEVER use '==' to compare objects. ALWAYS, ALWAYS, ALWAYS use equals(),

(was that loud enough?)

[Edit] I should probably add that the reason is that if the class doesn't have an equals() method, it will use Object's, which works exactly like '=='.

If it does define one (and if you ever write one), the very first statement in it should be:Winston
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sridhar Iyer wrote:Can somebody let me know why the output for this is so different ? I understand the concept but I don't understand why is it behaving so differently for different values.

Tell us, in your own words, what you understand about the concept. What is the difference between == and equals?
 
Sridhar Iyer
Greenhorn
Posts: 5
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I get it now. The point I missed here is
"Short and Integer from -128 to 127"


Thank you all for your time.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!