aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes long and float Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "long and float" Watch "long and float" New topic
Author

long and float

Mohit Agarwal
Ranch Hand

Joined: Mar 30, 2004
Posts: 88
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

Joined: Aug 03, 2002
Posts: 7729
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 ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Mohit Agarwal
Ranch Hand

Joined: Mar 30, 2004
Posts: 88
Why does the compiler does this narrowing conversion.

Pls. provide more details.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: long and float