This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Customer Requirements for Developers and have Marcho Behler on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Difference between xxxValue() methods and casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Customer Requirements for Developers this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference between xxxValue() methods and casting" Watch "Difference between xxxValue() methods and casting" New topic
Author

Difference between xxxValue() methods and casting

Nidhi Sar
Ranch Hand

Joined: Oct 19, 2009
Posts: 252

The xxxValue() methods of numeric wrappers seem to work just like casting.

Please take a look at the following simple program:


The last line prints true.

So what is the advantage of providing these methods in Java language?

Thanks,
Nidhi


"A problem well stated is a problem half solved.” - Charles F. Kettering
SCJP 6, OCPJWCD
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 20050
    
  30

The casting was not introduced until Java 5.0, and it implicitly calls xxxValue() in the background.

When you (implicitly or explicitly) cast a Float to a float (or Integer to int etc) the compiler calls floatValue() (intValue() etc). This will give a NullPointerException if the Float (Integer etc) is null.
When you (implicitly or explicitly) cast a float to a Float (or int to Integer etc) the compiler calls valueOf (which is available for all primitive types).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Nidhi Sar
Ranch Hand

Joined: Oct 19, 2009
Posts: 252

Rob,

That is very interesting. Thanks for sharing the info!!

Nidhi
Ulrika Tingle
Ranch Hand

Joined: Nov 24, 2009
Posts: 92
Nidhi Sar wrote:
That is very interesting.


The automatic conversion between primitives and their corresponding wrapper classes is called autoboxing (which was introduced in version 5).

 
Don't get me started about those stupid light bulbs.
 
subject: Difference between xxxValue() methods and casting
 
It's not a secret anymore!