BCA / B.Tech 12 min read

Type Casting in Java

What is Type Casting in Java?

Type casting is the process of converting a variable from one data type to another. Think of it like pouring a liquid from one container into another of a different size. This is necessary when you need to perform operations that require a specific data type.

There are two fundamental types of casting for primitive data types:
  • Widening Casting (Implicit/Automatic): This happens when you convert a value from a smaller data type to a larger data type. This is done automatically by Java because there is no risk of losing information. It's like pouring water from a small cup into a large bucket—everything fits easily.

    Hierarchy: byteshortcharintlongfloatdouble

    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double
    System.out.println(myDouble); // Outputs 9.0
  • Narrowing Casting (Explicit/Manual): This involves converting a larger data type to a smaller data type. You must do this manually by placing the target type in parentheses (). This is risky because you might lose data if the value is too large for the smaller type. It's like pouring a large bucket of water into a small cup—some water might spill.

    Hierarchy: doublefloatlongintcharshortbyte

    double myDouble = 9.78;
    int myInt = (int) myDouble; // Manual casting: double to int
    System.out.println(myInt); // Outputs 9 (fractional part is lost)

Object Type Casting:

Casting also applies to objects, specifically within an inheritance hierarchy.

  • Upcasting: This is casting an object of a subclass to its superclass type. It's always safe and done implicitly by Java. You are moving from a more specific type to a more general type.
    class Animal {}
    class Dog extends Animal {}
    
    Dog myDog = new Dog();
    Animal myAnimal = myDog; // Implicit upcasting
  • Downcasting: This is casting an object from a superclass type back to its original subclass type. This must be done explicitly and can cause a ClassCastException if the object is not a true instance of the target subclass. It's wise to check with the instanceof operator first.
    // Assuming myAnimal from above holds a Dog object
    if (myAnimal instanceof Dog) {
        Dog myDogAgain = (Dog) myAnimal; // Explicit downcasting
        System.out.println("Downcasting successful!");
    }