Type Casting in Java: Implicit vs Explicit with Examples
Type casting in Java is the process of converting a value from one data type to another. Since Java is strongly typed, understanding when conversions happen automatically and when you need to do them manually is essential.
Implicit Casting (Widening)
Implicit casting happens automatically when converting a smaller data type to a larger one, since no data is lost in the process — for example, converting an int to a double happens without any special syntax.
Explicit Casting (Narrowing)
Explicit casting is required when converting a larger data type to a smaller one, since this can lose precision or data — for example, converting a double to an int. Java requires you to write the target type in parentheses to confirm you intend this conversion.
- Implicit: byte → short → int → long → float → double
- Explicit: the reverse direction, always requires manual casting syntax
- Casting between incompatible types (like a String to an int directly) isn't allowed and needs a proper conversion method instead
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.