This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explicit casting

 
rohit kumar
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!!
 
Mohit Jain
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.lang.Math:
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.

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


rohit:
USP
I hope you didn't mean this:


Yours,
Bu.
 
rohit kumar
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks ranchers I missed out that 2.0 is a double so the entire exp evaluates to adouble
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic