Paul Ngugi

Posted on

Numeric Type Conversions

Floating-point numbers can be converted into integers using explicit casting. If an integer and a floating-point number are involved in a binary operation, Java automatically converts the integer to a floating-point value. So, 3 * 4.5 is same as 3.0 * 4.5.

You can always assign a value to a numeric variable whose type supports a larger range of values; thus, for instance, you can assign a long value to a float variable. You cannot, however, assign a value to a variable of a type with a smaller range unless you use type casting. Casting is an operation that converts a value of one data type into a value of another data type. Casting a type with a small range to a type with a larger range is known as widening a type. Casting a type with a large range to a type with a smaller range is known as narrowing a type. Java will automatically widen a type, but you must narrow a type explicitly.

The syntax for casting a type is to specify the target type in parentheses, followed by the variable’s name or the value to be cast. For example, the following statement

``````System.out.println((int)1.7);

``````

displays 1. When a double value is cast into an int value, the fractional part is truncated. The following statement

``````System.out.println((double)1 / 2);

``````

displays 0.5, because 1 is cast to 1.0 first, then 1.0 is divided by 2. However, the statement

``````System.out.println(1 / 2);

``````

displays 0, because 1 and 2 are both integers and the resulting value should also be an integer.

Casting is necessary if you are assigning a value to a variable of a smaller type range, such as assigning a double value to an int variable. A compile error will occur if casting is not used in situations of this kind. However, be careful when using casting, as loss of information might lead to inaccurate results.

Casting does not change the variable being cast. For example, d is not changed after casting in the following code:

``````double d = 4.5;
int i = (int)d; // i becomes 4, but d is still 4.5
``````

To assign a variable of the int type to a variable of the short or byte type, explicit casting must be used. For example, the following statements have a compile error:

``````int i = 1;
byte b = i; // Error because explicit casting is required
``````

However, so long as the integer literal is within the permissible range of the target variable, explicit casting is not needed to assign an integer literal to a variable of the short or byte type