Type Casting in Java

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion.

There are two types of casting in Java as follows:

  • Widening Casting (automatically)
  • Narrowing Casting (manually)

1. Widening Casting (automatically)

This type of casting takes place when two data types are automatically converted. It is also known as Implicit Conversion. This involves the conversion of a smaller data type to the larger type size.

byte -> short -> char -> int -> long -> float -> double

Code Snippet

// Widening Casting (Implicit)

/*Also known as automatic type casting, this happens when you convert a smaller data type to a larger one. */

public class App {
    public static void main(String[] args) {
        int num = 100;
        long bigNum = num; // int to long
        float floatNum = bigNum; // long to float
        System.out.println(floatNum); // Output: 100.0

    }
}

2. Narrowing Casting (manually)

if you want to assign a value of larger data type to a smaller data type, you can perform Explicit type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be done.

double -> float -> long -> int -> char -> short -> byte

Code Snippet

// Narrowing Casting (Explicit)

/*Also called manual type casting, it is used to convert a larger data type into a smaller one. */

public class App {
    public static void main(String[] args) {
        double myDouble = 9.78;
        int myInt = (int) myDouble; // manual cast: double to int
        System.out.println(myInt); // Output: 9

        // Example: Type Casting in Expressions
        int a = 5;
        int b = 2;
        double result = (double) a / b;
        System.out.println(result); // Output: 2.5

    }
}

Note

Without casting, a / b would give 2, since both are integers.

Working Source code

Code Snippet

// Type Casting in Java
/*
	Widening Casting
		byte -> short -> char -> int -> long -> float -> double
	Narrowing Casting
		double -> float -> long -> int -> char -> short -> byte
*/

class App {
    public static void main(String args[]) {
        int a = 10;
        double b = a, d = 25.5385;
        int c = (int) d;
        System.out.println("Int : " + a);
        System.out.println("Double : " + b);
        System.out.println("Double : " + d);
        System.out.println("Int : " + c);
    }
}