Widening Casting

Automatic Conversion

Widening (implicit) casting happens automatically when you put a smaller type into a larger type. No data is lost.

byte -> short -> int -> long -> float -> double
         char -> int

Example

public class Main {
    public static void main(String[] args) {
        int items = 9;
        double itemsAsDouble = items;   // int -> double automatically
        long bigCount = items;          // int -> long
        char letter = 'A';
        int letterCode = letter;        // char -> int
        System.out.println(items + " " + itemsAsDouble + " " + bigCount + " " + letterCode);
    }
}

Output

9 9.0 9 65

Widening in Expressions

Example

In an expression, Java converts the smaller operand to the larger type before calculating.

public class Main {
    public static void main(String[] args) {
        int total = 7;
        int count = 2;
        System.out.println(total / count);        // int / int  -> int
        System.out.println(total / 2.0);          // int / double -> double
        System.out.println((double) total / count);
    }
}

Output

3
3.5
3.5

Note: 7 / 2 is 3 in Java because both are int. This surprises many beginners when calculating averages.