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

# primitive type casting problem.........

Hamraj Kulshreshtha
Ranch Hand
Posts: 31
Hi,

During the casting of primitive type values i have found that long to float is implicitly casted .
But as per the size of both primitives, long is 64 bit and float is 32 bit.
But still why java allows the casting from long to float.
Because as per java rule we can't narrowing the casting implicitly.

I have put the code also for better understanding of the afore said things:

class PrimitiveTest
{
static void go(Integer l)
{
System.out.println("Integer");
}
static void go(float f)
{
System.out.println("double");
}
public static void main(String[] args)
{
long b = 5;
go(b);
}
}

Sergey Petunin
Ranch Hand
Posts: 44
When you cast an integer number to a float or a double number, you can loose precision anyway. So practically float can hold any long number, but with a bigger loss of precision than double. See this example:

The output is

Thus no explicit cast is needed, but you have to remember about the loss of precision, as neither compiler nor runtime won't tell you about it.

Srinivasan thoyyeti
Ranch Hand
Posts: 557
5.1.2 Widening Primitive Conversion
The following 19 specific conversions on primitive types are called the widening primitive conversions:

* byte to short, int, long, float, or double
* short to int, long, float, or double
* char to int, long, float, or double
* int to long, float, or double
* long to float or double
* float to double

long is integer(without decimal) type. it's stored in
2'complement form.
size = 64 bits.
Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float is decimal type. it's stored in IEEE format. size = 32 bits
Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).

Hence its widening. Storage format is the key here not no of bits.

Kelvin Chenhao Lim
Ranch Hand
Posts: 513
Hamraj's question is a good one, though. Personally, I do agree that Java should at least issue a warning when you assign a long to a float or double, or an int to a float. But it is what it is, unfortunately. Still, it's good that you're at least aware of the possibility of losing precision, since a surprising number of programmers I work with don't even know about that.

Originally posted by Serge Petunin:
When you cast an integer number to a float or a double number, you can loose precision anyway.

This isn't always true. An int will always be exactly representable in a double, since double values use 52 bits for the mantissa. But long values may indeed lose precision as you mentioned.