Primitive type casting in Java

In Java, primitive type casting is converting one primitive data type into another.
It’s split into two categories: widening (implicit) and narrowing (explicit) casting.


1. Widening Casting (Implicit)

Also called type promotion — smaller types automatically convert to larger types without data loss.

Order of promotion:
byte → short → int → long → float → double

Example:

int num = 100;
double bigNum = num; // int to double automatically
System.out.println(bigNum); // 100.0

Safe — no explicit cast required.


2. Narrowing Casting (Explicit)

Also called type demotion — larger types convert to smaller types.
You must use a cast because it may cause data loss.

Example:

double decimal = 9.78;
int whole = (int) decimal; // double to int explicitly
System.out.println(whole); // 9 (fractional part lost)

Risky — may lose precision or cause overflow.


Primitive Casting Table

From / Tobyteshortcharintlongfloatdouble
byteYesYesYesYesYesYes
short(Yes)YesYesYesYesYes
char(Yes)(Yes)YesYesYesYes
int(Yes)(Yes)(Yes)YesYesYes
long(Yes)(Yes)(Yes)(Yes)YesYes
float(Yes)(Yes)(Yes)(Yes)(Yes)Yes
double(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)

Note: “Yes” = implicit widening; “(Yes)” = explicit narrowing.


Example Demonstrating Both

public class CastingExample {
    public static void main(String[] args) {
        // Widening (automatic)
        int i = 42;
        double d = i; 
        System.out.println("Widening: " + d);

        // Narrowing (manual)
        double x = 42.99;
        int y = (int) x; 
        System.out.println("Narrowing: " + y);
    }
}

If you want, I can also give you a diagram of Java primitive type casting that visually shows which conversions are automatic and which require explicit casting. That tends to make it much easier to memorize.

Leave a Reply