Converting and Casting Numeric Data in Java

By Doug Lowe

From time to time, you need to convert numeric data of one type to another in Java. You may need to convert a double value to an integer, or vice versa. Some conversions can be done automatically; others are done using a technique called casting.

Automatic conversions in Java

Java can automatically convert some primitive types to others and do so whenever necessary. The image below shows which conversions Java allows. Note that the conversions shown with dotted arrows below may cause some of the value’s precision to be lost. An int can be converted to a float, for example, but large int values won’t be converted exactly because int values can have more digits than can be represented by the float type.

automatic conversions in java
Numeric type conversions that are done automatically.

Whenever you perform a mathematical operation on two values that aren’t of the same type, Java automatically converts one of them to the type of the other. Here are the rules Java follows when doing this conversion:

  • If one of the values is a double, the other value is converted to a double.
  • If neither is a double but one is a float, the other is converted to a float.
  • If neither is a double nor a float but one is a long, the other is converted to a long.
  • If all else fails, both values are converted to int.

Type casting

Casting is similar to conversion but isn’t done automatically. If you want to convert a double to an int, for example, you must use casting.

When you use casting, you run the risk of losing information. A double can hold larger numbers than an int, for example. In addition, an int can’t hold the fractional part of a double. As a result, if you cast a double to an int, you run the risk of losing data or accuracy, so 3.1415 becomes 3, for example.

To cast a primitive value from one type to another, you use a cast operator, which is simply the name of a primitive type in parentheses placed before the value you want to cast. For example:

double pi = 3.1314;

int iPi;

iPi = (int) pi;

Note that the fractional part of a double is simply discarded when cast to an integer; it isn’t rounded. For example:

double price = 9.99;

int iPrice = (int) price;

Here iPrice is assigned the value 9. If you want to round the double value when you convert it, use the round method of the Math class.