PDA

Click to See Complete Forum and Search --> : [RESOLVED] Simple Casting


eranga262154
Dec 10th, 2006, 10:08 PM
Hi all,

I do some testing on casting and confused with followings. First check the given code.

Code 1,

int x = 10;
float y = 15.2f;
int z = x + (int)y;
System.out.println(z);

Code 2,

int x = 10;
float y = 15.2f;
System.out.println(x + y);

Code 3,

int x = 10;
float y = 15.2f;
int z = x + y;
System.out.println(z);

My explanations on these are as follows.

On code one try to printout z, is an int type. So that it’s need to casting float into int. Result is 25. It’s ok.

On code two result is 25.2 because on println() method if any variable in a group of concatenated variables is a string, Java gets it as a single String.

On the last code I’m confusing. It is wrong. Why it is not possible automatic casting since int and float are 32bits long.

Can you guys make a note on this.
Thanks.

DeadEyes
Dec 11th, 2006, 03:36 AM
I imagine that example three causes a loss of precision but you as the developer have not explicitly stated that such a loss is ok.

CornedBee
Dec 11th, 2006, 07:18 AM
Bit size has nothing do with it. float is a floating point number, which means that any conversion between it and int can result in loss of precision.

eranga262154
Dec 12th, 2006, 01:14 AM
I imagine that example three causes a loss of precision but you as the developer have not explicitly stated that such a loss is ok.


Dear friend,

Don't worry about precision loosing. Just say that my explanation is ok.

Thanks

eranga262154
Dec 12th, 2006, 01:18 AM
Bit size has nothing do with it. float is a floating point number, which means that any conversion between it and int can result in loss of precision.

But I'm confusing with that bit size. Both float and int are in same length. Then why it is not possible.

CornedBee
Dec 12th, 2006, 03:58 AM
Again: because bit size doesn't matter. float can represent the number 0.5, while int cannot. Thus, converting this float to an int causes loss of precision.
(The converse is true, too. float cannot exactly represent the number 2^31 - 1, which int can.)

eranga262154
Dec 12th, 2006, 08:36 PM
Thanks CornedBee,

I got your point.

Sebouh
Dec 28th, 2006, 08:38 AM
Actually it has nothing to do with the bit size.
Int is represented in 32 bits in 2's complement. So the whole 32 bits represent the number. Floats are represented in 32 bits but in a different way. Starting fromt he most significant bit, bit 31 is a sign bit. Then bits 30 to 23 represent the exponent to the power 2. And the remaining bits 22 to 0 represent the significand or numbers after the decimal point.
So float has more precision since it has a way of representing real numbers.

eranga262154
Jan 1st, 2007, 08:27 PM
Int is represented in 32 bits in 2's complement. So the whole 32 bits represent the number. Floats are represented in 32 bits but in a different way.

So that in simply way all things depend on its way of construction.

Thanks