Java Type Casting

What Is Type Casting?

Type casting means converting a variable from one data type to another. Java supports both implicit (widening) and explicit (narrowing) conversions.

int x = 5;
double y = x;       // Implicit
int z = (int) y;     // Explicit

Widening Casting (Implicit)

Widening happens automatically when converting from a smaller to a larger data type. No data is lost.

Loading...
Output:

Narrowing Casting (Explicit)

Narrowing must be done manually and may cause data loss.

Loading...
Output:

Primitive Type Casting Notes

  • boolean cannot be cast to/from other types
  • char can be cast to/from int using ASCII codes
Loading...
Output:

Object Casting in Java

Object casting allows you to convert one object type into another, either from a subclass to a superclass or vice versa. There are two types:

  • Upcasting: Casting a subclass object to a superclass reference — done implicitly.
  • Downcasting: Casting a superclass reference back to a subclass — requires explicit casting.

Upcasting Example:

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Bark");
    }
}

Animal a = new Dog();  // Upcasting (implicit)
a.sound();

Downcasting Example:

Animal a = new Dog();
Dog d = (Dog) a;  // Downcasting (explicit)
d.bark();

⚠️ Downcasting must be used with caution. If the actual object is not of the subclass type, a ClassCastException will be thrown.

Practice Question

What will this output?

Loading...
Output:

Hint: Narrowing truncates, it doesn't round.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic