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

# primitive casting

Arnav Velimala
Ranch Hand
Posts: 37
Dear All,

While I was trying to digest the topic of casting, I got one doubt.
I'm following K&B book. On Page 183, there is this example -

The large-value-into-small-container conversion is referred to as narrowing and requires an explicit cast.
My question is ... why there is a chance of losing info?
Why explicit casting is required?
Even though both int and float are same size containers - 32bits.

Thanks,
-A

Zaheer Ahmed
Greenhorn
Posts: 22

In the above example the trailing data after the point is truncated. That is:

The above code prints 100 in the output truncating any data after the decimal place. So you lost 0.001 in the integer variable that got truncated.

Secondly, explicit casting is required if you need to assign a bigger variable into smaller variable such in the example above, you need to do an explicit cast. Thats kind of assuring the compiler that I know what I am doing (Bert)...

Hope this helped!
[ June 20, 2008: Message edited by: Zaheer Ahmed ]

Arnav Velimala
Ranch Hand
Posts: 37

Secondly, explicit casting is required if you need to assign a bigger variable into smaller variable

How float is considered a bigger variable than int?
Because both have the same 32bits.

Zaheer Ahmed
Greenhorn
Posts: 22

Secondly, explicit casting is required if you need to assign a bigger variable into smaller variable

Let me clarify this more... Casting is not required only when you are assigning a variable of 8 bits to another one that is 16 bits, but its also required when there is an expected loss of data.

When assigning a float to an int we have possible loss of precision due to the fact float sets aside memory for representing decimal places but int does not.

Hope this helps...

Henry Wong
author
Marshal
Posts: 21735
85
How float is considered a bigger variable than int?
Because both have the same 32bits.

It's not based on bits, it's based on range -- interestingly, Java doesn't really care much about precision either.

Anyway, the range of an int is from -2,147,483,648 to 2,147,483,647. And the range of a float is from -3.40282346638528860e+38 to +3.40282346638528860e+38.

So, as you can see even though an int and a float are both 32 bits, a float covers a much bigger range. In fact, a float has a bigger range than a long, even though a long is 64 bits and a float is 32 bits.

Henry

Ranch Hand
Posts: 71
Hi Rancher ,

However both int and float have 32-bit width .
But float can store integer as well as floating point number whereas
int can contain only integer numbers .

When you say
float somefloat = 25.45f ;
int a = somefloat ;
There is a risk that digit after decimal point will be lost .
That is why , compiler forces you to da explicit cast .