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 argument
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!!!
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 ]
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).