• 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
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

Automatic conversion of float to double in numeric promotion

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi I am new to Java, and I am trying to figure out the automatic conversion of float to double.

for example: double x = 39.21; float y = 2.1; c= x+y; the book said this will not compile because floating point literals are assumed to be double. So, if we wanted this to work we would have to initialize float y= 2.1f . But what I don,t understand is if y is automatically assumed to be a double , making x and y the same data type. Why does this code not compile?.

2) Also short x=14; float y=13; double z =30;  c= x*y/z; here short is converted into an int and in the numeric operation x*y, 'x' gets converted to a float. My question is since float is not initialized with an f. shouldn't float value of y be assumed as a double and  and hence in x*y shouldn't 'x' be promoted to a double instead of float ?

Could really use some help related to this. Thanks.
 
Marshal
Posts: 26909
82
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mau Dc wrote:for example: float y = 2.1; the book said this will not compile because floating point literals are assumed to be double. So, if we wanted this to work we would have to initialize float y= 2.1f .



Yes, literals like "2.1" are assumed to be double. And yes, if you want to assign that number to a floating-point variable you have to write "2.1f" to make it a float literal.

But what I don,t understand is if y is automatically assumed to be a double , making x and y the same data type. Why does this code not compile?.



But no! What makes you think that y is assumed to be a double? Yes, certain literals are assumed to be double, but that rule doesn't apply to variables. If you declare a variable to be of type float -- as in that example -- then it's a float variable.
 
Ranch Hand
Posts: 4716
9
Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
very good answer Paul.
 
reply
    Bookmark Topic Watch Topic
  • New Topic