• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does an object equals primitive?  RSS feed

 
Pete Letkeman
Ranch Foreman
Posts: 917
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

So why is it that an Integer object, which is an object reference after all, equals a primitive int value?
I know that there is a cache of numbers, however 981 is outside of that range isn't it?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pete Letkeman wrote:
So why is it that an Integer object, which is an object reference after all, equals a primitive int value?
I know that there is a cache of numbers, however 981 is outside of that range isn't it?


When an Integer instance is compared with a primitive int, Java will unbox the Integer and compare the values.

Henry
 
Pete Letkeman
Ranch Foreman
Posts: 917
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahh, that makes sense, I had forgotten about autoboxing and autounboxing.
I suspect that this is the case with most/all primitives and their object counter parts. 

Thanks for clearing this up for me.
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that is just how java makes up for not having everything an object. in Scala, for instance, there are no primitives. everything is an object, including methods.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They keep promising to get rid of the distinction between objects and primitives: roll on that day
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
campbell, i must admit that java started it all. it still backs it. scala would be nothing without both the java runtime and the API
 
ramesh suri
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Integer.java class equals() method compares the value.
== compares the reference of the object.
So eachtime new keyword is used, a new object is created in a memory.
Here is Integer.java equals() method implementation
integer.java
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!