• 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

Primitive typecasting

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i am preparing for scjp 1.6 and while trying out some code experiments on primitive typcasting i found some unusual behaviour on floating point numbers.
can anyone help me explain whats happening here..


byte ca = (byte)128; // needs an explicit cast because 128 is 32 bit int.
ca = (byte) ca + 12; //explicit cast because evaluting exp is implicitly converted to 32 bit int.

the above code is understandable.



but in the following code

float m = (float) 23.6; // explicit cast because floating points are 64 bit doubles by default and works fine.

...........................................................................................................................................................................................................................

m = (float) m + 5.7; // error . .. why???


why does this line of code doesnt complile. i have given an explicit cast for converting the evaluated double to float. then too it shows an error.
may i know the reason for this behavoiur.

thanks.
regards.
 
Greenhorn
Posts: 24
Android Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code:

Gives a compile error because you're casting m to float. So the statement becomes m (float) + 5.7 (double) = double.

There are two ways to accomplish what you want:

Or

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi there, even the first example that you gave will give a compile time error, you need to cast it like this...

amu
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic