Conversion and coercion in Java
Archive - Originally posted on "The Horse's Mouth" - 2004-11-22 15:04:21 - Graham EllisThe accuracy and conversion of primitive arithmetic variables in Java is something that I'm questioned on regularly.
Ideally in Java, you'll perform arithmetic on two pieces of data of an identical type, and the result returned will be of the same type. However, if you perform a calculation on two different types the "least accurate" will be coerced up to the accuracy of the second. For example, integer is coerced to float which in turn may be coerced to a double.
What does this mean?
Calculation | types | Result type | Stored in variable of type |
---|---|---|---|
a = 5.0/2 | D/I | D | D |
b = 5/2.0F | I/F | F | F or D |
c = 5/2 | I/I | I | I L F or D |
d = 5/2.0 | I/D | D | D |
I - int
L - long
F - float
D - double
Note that a constant such as 2.0 id double, whereas 2.0f or 2.0F is float.
If you wish to save a result into a "less accurate" variable, you may do so by casting it. For example
a = (float) (5/2.0)
will convert an integer up to a double for the division through coersion and will then cast it back to a float before saving it in the variable a
Select here for a download of my "variables in Java" training notes released under an open training notes license. Further examples of simple variable use in Java can be found in our modules resource centre.