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 explicit casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "explicit casting" Watch "explicit casting" New topic

explicit casting

rohit kumar

Joined: May 27, 2007
Posts: 9
This is an excerpt from "Begining Java 5" Wrox by Ivor Horton

"Method Function Argument Type Result Type
round(arg) calculates the nearest float or double of type int for
integer to the argument a float argument.
value. of type long
for a double

the expression to the right of averageFruit1 should not be explicily casted according to the author but the compiler shows me error "possible loss of precision" Is it a typographical error in the book
N.B. the problem gets sorted out with the following explicit casting:

expecting a quick response from ranchers as has always been your USP!!!
Mohit Jain
Ranch Hand

Joined: Jun 04, 2007
Posts: 74
Hi Rohit

Refer to java.lang.Math.
round() method has two overloaded forms. The one used in given code accepts a 'double' parameter as a result it is supposed to return a 'long' value.

Without explicit cast it will act like <int-variable> = <long-value> which will result in error.
If the arguement to round() method is a 'float' you wont be required to do explicit cast because it will call the second overloaded form of round() method that returns an integer instead of long value.

I hope it clarifies your doubt.
[ July 13, 2007: Message edited by: Mohit Jain ]

SCJP 5.0, SCWCD in progress
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
static longround(double a)
Returns the closest long to the argument.
static intround(float a)
Returns the closest int to the argument.

Depending on the argument, the return type could be either long or int.

averageFruit1 = Math.round((numOranges1+numApples1)/2.0);

cannot compile. The oranges and apples are float (-> return type int) but the 2.0 is a double literal, so the whole thing in between the brackets is a double value (-> return type long).
Casting this line to int would compile, but would also be bad design.
Instead it should be divided through 2f or 2.0f (a float literal).

I hope you didn't mean this:


all events occur in real time
rohit kumar

Joined: May 27, 2007
Posts: 9
thanks ranchers I missed out that 2.0 is a double so the entire exp evaluates to adouble
I agree. Here's the link:
subject: explicit casting
It's not a secret anymore!