Primitive assignment

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
toctave
Posts: 2
Joined: Mon Oct 28, 2019 7:59 pm
Contact:

Primitive assignment

Post 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);
}
}

admin
Site Admin
Posts: 10065
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Primitive assignment

Post 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/
If you like our products and services, please help us by posting your review here.

toctave
Posts: 2
Joined: Mon Oct 28, 2019 7:59 pm
Contact:

Re: Primitive assignment

Post by toctave »

Thank you very much !! That was very helpful

Post Reply

Who is online

Users browsing this forum: No registered users and 119 guests