next up previous
Next: 1.3.2 Object Types Up: 1.3.1 Primitive Types Previous: 1.3.1.0.1 Numeric Constants

1.3.1.0.2 Conversions Between Types

Java will automatically convert any numeric type to a more ``general'' numeric type demanded by context. The following list gives the primitive numeric types in increasing order of generality:

\begin{displaymath}{\tt\small byte} \rightarrow {\tt\small short} \rightarrow {\...
...}
\rightarrow {\tt\small float} \rightarrow {\tt\small double}
\end{displaymath}

Note that the notion of generality here is imperfect in spots.Co nversion of a long to a float for example will often result in a loss of precision. In fact, even the conversion of a really large long value to a double can lose precision.

Java provides explicit conversion operators called casts to convert a numeric type to a less general type. A cast is simply a type name enclosed in parentheses used a prefix operator. For example, the following expression casts the int constant 127 to the type byte

\begin{displaymath}{\tt\small (byte) 127}
\end{displaymath}

When converting from one bounded integer type to another one Java silently truncates leading digits if the output type is shorter than the input type. Watch out!


Finger Exercise: In DrJava, convert the maximum long value to double. (Do not type the 20+ digits for this constant!) What do you get? Convert the maximum long value to type float. What do you get? Why? Try converting the maximum long value minus 1 to double and back again. Do you get the same result?


next up previous
Next: 1.3.2 Object Types Up: 1.3.1 Primitive Types Previous: 1.3.1.0.1 Numeric Constants
Corky Cartwright
2000-01-07