File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

long and float

 
Mohit Agarwal
Ranch Hand
Posts: 88
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A{
public static void main(String[] a){
long l=51L;
float f=2.5F;
long l1=l*f;//gives compile error
float f1=l*f;//compiles fine
}
}

When an expression involves long and float which casted to which .

Pls. let me know.

I am confused.

Mohit Agarwal
Would Be SCJP.

"The will to win is worthless if you do not have the will to prepare"
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
long is converted to float so that l*f results in a float.


(Changed cast to converted)
[ October 01, 2004: Message edited by: Barry Gaunt ]
 
Mohit Agarwal
Ranch Hand
Posts: 88
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the compiler does this narrowing conversion.

Pls. provide more details.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java performs the following conversions when appropriate:

byte -> short -> long -> float -> double

(char is left out on purpose)

If one of the terms in a binary expression is a floating point number (float or double) then the other term will be converted to a floating point number so that floating point arithmetic can be performed.

The long variable l will be converted to float because a long lies within the range of a float even though the number will lose out on precision.

It's up to the programmer to allocate appropriate types to the variables if greater precision or ranges are desired. I have seen more use of doubles than floats for primitive variable types.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic