Open In App

Typecasting in Java

Last Updated : 28 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, typecasting is the process of converting one data type to another data type using the casting operator. When you assign a value from one primitive data type to another type, this is known as type casting. To enable the use of a variable in a specific manner, this method requires explicitly instructing the Java compiler to treat a variable of one data type as a variable of another data type.

Syntax:

<datatype> variableName = (<datatype>) value;

Types of Type Casting

There are two types of Type Casting in Java:

  • Widening Type Casting
  • Narrow Type Casting

1. Widening Type CastingĀ (Implicit Casting)

A lower data type is transformed into a higher one by a process known as widening type casting. Implicit type casting and casting down are some names for it. It occurs naturally. Since there is no chance of data loss, it is secure. Widening Type casting occurs when:

  • The target type must be larger than the source type.
  • Both data types must be compatible with each other.

Note: Widening type casting is also sometimes called upcasting for primitives, but it is not correct to call it casting down.

Syntax:

larger_data_type variable_name = smaller_data_type_variable;

Widening-Type-Casting


Example:

Java
// Java program to demonstrate Widening TypeCasting
import java.io.*;

class Geeks {
    public static void main(String[] args)
    {
        int i = 10;

        // Wideing TypeCasting (Automatic Casting)
        // from int to long
        long l = i;

        // Wideing TypeCasting (Automatic Casting)
        // from int to double
        double d = i;

        System.out.println("Integer: " + i);
        System.out.println("Long: " + l);
        System.out.println("Double: " + d);
    }
}

Output
Integer: 10
Long: 10
Double: 10.0


2. Narrow Type Casting (Explicit Casting)

The process of downsizing a bigger data type into a smaller one is known as narrowing type casting. Casting up or explicit type casting are other names for it. It doesn't just happen by itself. If we don't explicitly do that, a compile-time error will occur. Narrowing type casting is unsafe because data loss might happen due to the lower data type's smaller range of permitted values. A cast operator assists in the process of explicit casting.

Syntax:

smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;

Narrow Type Casting


Example:

Java
// Java Program to demonstrate Narrow type casting
import java.io.*;

class Geeks {
    public static void main(String[] args)
    {
        double i = 100.245;

        // Narrowing Type Casting
        short j = (short)i;
        int k = (int)i;

        System.out.println("Original Value before Casting"
                           + i);
        System.out.println("After Type Casting to short "
                           + j);
        System.out.println("After Type Casting to int "
                           + k);
    }
}

Output
Original Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100


Types of Explicit Casting

Mainly there are two types of Explicit Casting:

  • Explicit Upcasting
  • Explicit Downcasting

1. Explicit UpcastingĀ 

Upcasting is the process of casting a subtype to a supertype in the inheritance tree's upward direction. When a sub-class object is referenced by a superclass reference variable, an automatic process is triggered without any further effort.Ā 

Example:

Java
// Java Program to demonstrate Explicit Upcasting
import java.io.*;

class Animal {
    public void makeSound()
    {
        System.out.println("The animal makes a sound");
    }
}

class Dog extends Animal {
    public void makeSound()
    {
        System.out.println("The dog barks");
    }

    public void fetch()
    {
        System.out.println("The dog fetches a ball");
    }
}
class Geeks {
    public static void main(String[] args)
    { // Upcasting
        Animal animal = new Dog();
        // Calls the overridden method in Dog class
        animal.makeSound();
        // This would give a compile error as fetch() is not
        // a method in Animal class
        // animal.fetch();
    }
}

Output
The dog barks


2. Explicit Downcasting

When a subclass type refers to an object of the parent class, the process is referred to as downcasting. If it is done manually, the compiler issues a runtime ClassCastException error. It can only be done by using the instanceof operator. Only the downcast of an object that has already been upcast is possible.

Example:

Java
// Java Program to demonstrate Explicit downcasting
import java.io.*;
class Animal {
    public void eat()
    {
        System.out.println("The animal is eating.");
    }
}

class Cat extends Animal {
    public void meow()
    {
        System.out.println("The cat is meowing.");
    }
}

class Geeks {
    public static void main(String[] args)
    {
        Animal animal = new Cat();
        animal.eat();

        // Explicit downcasting
        Cat cat = (Cat)animal;
        cat.meow();
    }
}

Output
The animal is eating.
The cat is meowing.


Typecasting is also applicable to reference types, but must be done carefully. Casting an object to an incompatible type will result in a ClassCastException at runtime.

Object obj = "hello"; // A String stored in an Object

String s = (String) obj; // Valid cast, no error

Integer i = (Integer) obj; // Runtime error: ClassCastException

To avoid such issues, it's good practice to use the instanceof operator before downcasting:

if (obj instanceof String) {

String s = (String) obj;

System.out.println("String value: " + s);

}


Next Article
Article Tags :
Practice Tags :

Similar Reads