Type Casting (Widening & Narrowing) in Java
Casting converts a value from one type to another. Widening happens automatically whenever no information could be lost β an int assigned to a double, for instance, since every int value fits inside double's much larger range. Narrowing goes the other direction, from a larger or more precise type into a smaller one, and Java requires it to be written explicitly, with the target type in parentheses, precisely because it can lose information.
That explicit syntax is a safety rail: writing double d = 5; compiles without comment, but int i = d; does not β the compiler forces int i = (int) d; instead, so truncation is something the code's author visibly chose rather than something that happened silently. A narrowing cast can lose the fractional part of a decimal or wrap a value that's outside the target type's range, exactly like the overflow behavior primitive types already show.
Widening
A smaller or less precise type converts automatically into a larger, more precise one: byte to short to int to long to float to double, with no cast needed.
Narrowing
A larger or more precise type converts into a smaller one only with an explicit cast β the target type written in parentheses in front of the value.
Why the compiler demands it
Narrowing can lose information β a fractional part, or magnitude outside the new type's range β so Java requires the cast to be visible in the source rather than letting it happen silently.
Truncation, not rounding
Casting a double to an int simply chops off everything after the decimal point; it does not round to the nearest whole number.
Casting between unrelated reference types
Casting one object reference type to another, unlike primitive casting, only works if the object is genuinely an instance of the target type β Java checks that at runtime and throws a ClassCastException if it isn't.
public class CastingDemo { public static void main(String[] args) { int wholeNumber = 9; double widened = wholeNumber; double preciseValue = 9.75; int narrowed = (int) preciseValue; System.out.println("Widened: " + widened); System.out.println("Narrowed: " + narrowed); }}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself β building beats watching.