Search⌘ K

Conversions between Numeric Data Types

Explore how Java handles numeric data type conversions in arithmetic expressions. Understand implicit coercion from smaller to larger types and how to use explicit type casting to convert between incompatible types, including truncation behavior when converting from floating-point to integers. This lesson helps you write accurate numeric assignments and expressions in Java.

We'll cover the following...

When writing an arithmetic expression or assigning a numeric value to a variable, the data types of the values involved are significant. In certain cases, Java implicitly converts a value from one data type to another, based on the context in which the values appear. At other times, we must explicitly tell Java to make a conversion. Failure to do so in these cases can lead to either incorrect results or an error message. This lesson examines data-type conversions beginning with the implicit ones.

Coercion

So far, when we have assigned a value to a variable, we have been careful to match their data types. For example, we assigned a double value to a double variable. Matching data types is not always necessary, however. We can assign a value whose data type is in the following list to a variable whose data type is either the same or appears to the right in the list:

byte → short → int → long → float → double

For example, we can assign an int to a double variable, as in

double realNumber = 8;

An implicit type conversion, that is, a coercion, from int ...