next up previous
Next: 1.2.2 Object Types Up: 1.2.1 Primitive Types Previous: 1.2.1.0.1 Numeric Constants

1.2.1.0.2 Conversions Between Types [Optional]

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 byte} \rightarrow {\tt short} \rightarrow {\tt int} \ri...
...ow {\tt long}
\rightarrow {\tt float} \rightarrow {\tt double}
\end{displaymath}

Note that the notion of generality here is imperfect in some situations. The conversion of a long to a float, for example, will often lose 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 (byte) 127}
\end{displaymath}

When converting from one bounded integer type to another, 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.2.2 Object Types Up: 1.2.1 Primitive Types Previous: 1.2.1.0.1 Numeric Constants
Corky Cartwright 2003-07-07