• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

long and float

 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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"
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why does the compiler does this narrowing conversion.

Pls. provide more details.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic