• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between xxxValue() methods and casting

 
Nidhi Sar
Ranch Hand
Posts: 252
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Posts: 20817
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Nidhi Sar
Ranch Hand
Posts: 252
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob,

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

Nidhi
 
Ulrika Tingle
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!