Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# doubt on casting

MInu
Ranch Hand
Posts: 517
float is 32 bit in size and long 64 still then it is possible to do as follows

float a = 10.003f;
long l = 922l;
a=l;

so is it not broadning.
can you please explain.
[ January 19, 2005: Message edited by: minu su ]

Stevica Vucicevic
Greenhorn
Posts: 10
It does not only depend on the type of the primitives but on the value they hold!
In your example the code compiles find and the result of a = 922.0
You would only have a problem as using 4398046511103 for example would result in lost precision.

I hope this answer will satisfy your need!

cheers!

Mike Gershman
Ranch Hand
Posts: 1272
Stevica's analysis would be correct if a and l were final. Since they are not final, the compiler can not rely on the initial values and must consider all possible values.

The javac error message "possible loss of precision" is misleading because the rules on casting fom an integer type to a floating point type are based on magnitude, not precision. Java considers conversion from any integer type to any floating point to be a widening conversion not requiring an explicit cast because there may be a loss of precision but there is no loss of overall magnitude.

A float can easily hold the largest possible long. A long goes up to 2^63-1. A float can at least hold up to 2^127.

This is from section 5.1.2 of the Java Language Specification:
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (�4.2.4).

ankur rathi
Ranch Hand
Posts: 3830

this is a simple diagram to remember .
note : when you are going left to right , you don't need to cast ( byte -> short => putting byte into short )
and if you are going right to left , then you need to cast .
[ January 19, 2005: Message edited by: rathi ji ]