Conversions between Numeric Data Types

In this lesson, we will look at both implicit and explicit data-type conversions.

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 to double occurs.

We cannot, however, assign a double value to an int variable. For example, the following is illegal:

int integerPart = realNumber; // ILLEGAL!

This statement is illegal even if realNumber contains an integer value such as 25.0. This difficulty does not mean that we cannot extract the integer part of a real number, as you will see shortly.

Get hands-on with 1200+ tech skills courses.