Java Type Casting



In this tutorial, we will learn about Java type casting with the help of examples.


Java Type Casting

Type casting is the mechanism when we assign a value of one primitive data type to another one.

Java offers two types of casting:

  • Widening Casting: It automatically converts a smaller type to a larger type size byte -> short -> char -> long -> float -> double
  • Narrowing Casting: It manually converts a larger type to a smaller size type double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting consists of automatically passing a smaller size type to a larger size type.

Example:

public class Main {
    public static void main(String[] args) {
        int myInt = 45;
        double myDouble = myInt;     // Automatic casting : int to double

        System.out.println(myInt);        // Outputs 45
        System.out.println(myDouble);    // Outputs 45.0
    }
}

Output:

45
45.0

Narrowing Casting

Narrowing casting consists of manually converting larger size type to smaller size type, and it is done by placing the type in parentheses in front of the value.

Example:

public class Main {
    public static void main(String[] args) {
        double myDouble = 7.35;
        int myInt = (int) myDouble;     // Manual casting : double to int

        System.out.println(myDouble);        // Outputs 7.35
        System.out.println(myInt);            // Outputs 7
    }
}

Output:

7.35
7


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.