• Post Reply Bookmark Topic Watch Topic
  • New Topic

float problem  RSS feed

 
gaurav chaudhary
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what's the difference between declaration of x & y

thanks in advance
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
None.
 
Surasak Leenapongpanit
Ranch Hand
Posts: 341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Refer to 5.1.2 "Widening Primitive Conversion" from "The Java Language Specification 2nd Edition"
- int to long, float or double
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They even look the same when disassembled with javap.
Both

and

result in the following output using javap -c Foo
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
None.

is it? 0f is forced to a float while 0 is forced to a double which is then narrowed to a float to fit in the float.
In this particular instance the result is the same of course. In other circumstances different results may well arise.
Think of things like

d would (if memory serves) produce a float widened to a double while d2 would produce a double directly.
The precision of the result in d2 would be greater.
Note: this example is very contrived and might not be entirely correct but it serves the purpose.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

0f is forced to a float while 0 is forced to a double which is then narrowed to a float to fit in the float.

But all this is happening at compile time, so there really is no actual difference. (BTW, I'd think that 0 is an int literal. Is it really converted to a double before being narrowed to a float?)


d would (if memory serves) produce a float widened to a double while d2 would produce a double directly.

Actually, 1/3 produces an int of the value 0.
And if I remember correctly, 1/(3f) produces a double. I would be surprised if (1/3)f where a valid expression, but I didn't check.
Note: this example is very contrived and might not be entirely correct but it serves the purpose.

You are, of course, correct that you can find circumstances where using the f qualifier (is that the correct term?) makes a difference - else there wouldn't be a need for it. But in the specific example of the original poster, it doesn't.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!