Page 1 of 1

Primitive assignment

Posted: Mon Oct 28, 2019 8:15 pm
by toctave
Data types int and float are the same size (32 bits), so why the codes below doen't return 0:

public class testImpl{
public static void main(String[] args){

int i = 1234567890;
float f = i;
System.out.println(i - (int)f);
}
}

Re: Primitive assignment

Posted: Mon Oct 28, 2019 10:42 pm
by admin
Float has the same size in terms of bits but it uses those bits differently from int. Basically, int uses all its bits to store the exact number while a float uses some bits to store most significant bits of the value and rest of the bits to store the exponent. That is why float loses the lower order digits and so, when you covert it back to int, you will get zeros in those positions. For example, when you covert int 1234567890 to float and then back to int, you may get 1234560000.
See this for exact details: https://introcs.cs.princeton.edu/java/91float/

Re: Primitive assignment

Posted: Wed Nov 06, 2019 2:15 pm
by toctave
Thank you very much !! That was very helpful