Java Quick Tip: ints and doublesPosted by RoboDuke on Saturday, 8 December 2007
Class Notice- Please join RoboDuke's new Java Class Group, and use the group for class questions!
Why do we choose to use doubles instead of floats for decimal numbers? And why do we use int for whole numbers instead of short, byte or long? It turns out when Java sees the constant 25.20, it assumes that it is a double. Therefore, it is very simple for Java to do
double hourlyWage = 25.20;
since it is assigning the number 25.20 to a chunk of memory that is exactly the right size for it to fit. However, we saw on page 51, that if we wanted to use a float variable, we would need to do
float hourlyWage = 25.20f;
Seems odd? The reason is that because, referring to page 51, you are trying to take the number which Java stores in 64 bits (the size of a double and Java considers the number 25.20 a double) and shove it into a 32 bit hole (the size of a float). Java refuses to do so unless you specifically tell her (bet you didn't know she was a female) it is ok, because of problems with putting something big into a small hole. The way you tell her is by placing the f at the end of the number to indicate that you want it considered a float.
The same rule holds for whole numbers. The constant 167 is considered by Java to be an int data type. You would have no problem with
int num= 167;
long num = 167;
(this second one puts a 32 bit number in a 64 bit hole)
But could run into problems with
short num = 167;
byte num = 167;
Note that I said could. Java will actually allow you to do this if it really fits (see our example code) but complains if it does not fit. Moral of the story: Stick to ints and doubles unless you have a reason to use something else!