Narrowing Casting

Manual Conversion

Narrowing (explicit) casting goes from a larger type to a smaller one. You must write the target type in brackets, because data may be lost.

Example

public class Main {
    public static void main(String[] args) {
        double price = 99.99;
        int rupees = (int) price;       // decimal part is cut off, not rounded
        System.out.println(rupees);

        long big = 3_000_000_000L;
        int small = (int) big;          // too big for int -> wraps around
        System.out.println(small);

        int code = 66;
        char ch = (char) code;
        System.out.println(ch);

        System.out.println((int) 7.9 + " " + (int) -7.9);
        System.out.println(Math.round(7.9));   // round instead of truncate
    }
}

Output

99
-1294967296
B
7 -7
8

Summary

WideningNarrowing
Directionsmall type to big typebig type to small type
Syntaxautomatic(targetType) value
Data loss?no (except precision for long to float)possible
Exampledouble d = 5;int i = (int) 5.8; gives 5

Exercise: What does (int) (10 / 4.0) print, and why?

Show answer
2
10 / 4.0 is 2.5 (double division), then (int) cuts off the decimal part.