Sub topic 12
Conversions and Casts
A conversion changes a value from one type to another. Java performs some conversions automatically. Others need a cast, which tells Java which type you want.
Conversions matter because a new type may not hold the same value as the old one.
Automatic conversions
A widening conversion moves a number to a type that can hold at least as wide a range of values. A range is the set of values a type can hold.
Java performs these widening conversions automatically:
byte → short → int → long → float → double
For example, Java converts 7 from int to double here:
class WideningExample {
public static void main(String[] args) {
int whole = 7;
double number = whole;
System.out.println(number);
}
}The output is 7.0. Java can also convert char to int, long, float, or double.
A wider range does not always mean exact values. For example, float cannot store every int exactly. Converting the int value 16777217 to float gives the nearest available value, 16777216.
Casts and lost information
A narrowing conversion moves a value to a type that may not hold it exactly or may have a smaller range. It often requires a cast. Write the type in parentheses before the value:
(int) price
When you cast a floating-point value such as 19.99 to int, Java drops the part after the decimal point. It does not round to the nearest whole number. For example, -19.99 becomes -19.
Casting a large whole number to a smaller integer type can also change its value. The result is not necessarily the closest value that fits.
Try conversions in a program
Save this program as ConversionExample.java. Compile it with javac ConversionExample.java, then run it with java ConversionExample.
class ConversionExample {
public static void main(String[] args) {
int whole = 7;
double widened = whole;
double price = 19.99;
int units = (int) price;
long large = 2147483648L;
int changed = (int) large;
int total = 7;
int people = 2;
double castBefore = (double) total / people;
double castAfter = (double) (total / people);
System.out.println(widened);
System.out.println(units);
System.out.println(changed);
System.out.println(castBefore);
System.out.println(castAfter);
}
}The L suffix marks the large number as a long literal. The program prints:
7.0
19
-2147483648
3.5
3.0The cast of large changes its value because 2147483648 is too large for an int. Check that a value fits before using a narrowing cast.
The last two results show why the cast’s position matters. When both numbers in a division are integers, Java drops the fractional part. Casting total to double before division gives 3.5. Casting after division cannot bring back the lost half.
Exercise
What values do a and b have after int a = (int) 8.9; and double b = (double) 5 / 2;?
Show answer
a is 8 because the cast drops the fractional part. b is 2.5 because the cast happens before division.