This book is now obsolete Please use CSAwesome instead.
3.6. Casting Variables¶
Run this code to find how Java handles division and what casting can do to the results.
Java assumes that if you are doing division with integers that you want an integer result and it will throw away any fractional part (part after the decimal point). But, if you use a mixture of integers (int) and floating point (double) numbers Java will assume that you want a floating point result. If you have integers and you want a floating point result from some mathematical operation cast one of the integers to a double using (double) as shown above. By casting we don’t mean something to do with fishing, but it is a similar idea to casting a pot in clay. In Java when you cast you are changing the “shape” (or type) of the variable to the right of the cast to the specified type.
Is the result of 1.0 divided by 3 what you expected? Java limits the number of digits you can save for any
double number to about 14-15 digits. You should be aware that the accuracy of any calculation on a computer is limited by the fact that computers can only hold a limited number of digits.
Check your understanding