This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android 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: 19655
    
  18

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
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).

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Difference between xxxValue() methods and casting
 
Similar Threads
from a mock exam
confusion on casting
Inner Thread Classes
Doubt regarding a program included "static" and "Overriding " concepts
code behaving strangely