File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes boxing/unboxing operations on equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "boxing/unboxing operations on equals()" Watch "boxing/unboxing operations on equals()" New topic

boxing/unboxing operations on equals()

Ravinder Singh
Ranch Hand

Joined: Mar 06, 2006
Posts: 54
Here is another one...this time using equals() method.

Object class equals() method is used to test object equality ie. to see if two instances of the same type are "meaningfully equal".

Q. The above doesn't compile saying:

Why int pi in the code above not boxed (wrapped) to an Integer object while invoking equals()? The code compiles and runs when the same expression is changed to i.equals(pi), in which case the argument pi IS wrapped.

GANESHKUMAR Parthsarathi

Joined: Jan 11, 2006
Posts: 13
you can not invoke a method from a primitive type. I guss that's the reason.

Correct me if i'm wrong.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Obviously you cannot dereference a primitive. But why is it not boxed and compared with equals?
That in my opinion is a rather inefficient way of doing things.
First box an int then compare the values bitwise of two ints contained in two Integer objects?
Nonsense! The language designers are trying keep the language efficient and try to prevent
the programmer writing code that is "nonsense".

The other way around using Integer.equals() on i and boxing the argument pi from int to Integer. That is (in my opinion) an OK scenario but still inefficient.
i could have been obtained from a Collection and you want to know if it's value is pi. So you would simply have to unbox i and compare it with pi (i.intValue() == pi).

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Ravinder Singh
Ranch Hand

Joined: Mar 06, 2006
Posts: 54
Thanks Barry (and Ganesh) for your clarifications...
I agree. Here's the link:
subject: boxing/unboxing operations on equals()
It's not a secret anymore!