Home >>Java Tutorial >Java Type Casting

Java Type Casting

Java Type Casting

Java Type Casting is basically the process of assigning a value of another type to a variable of another type. In simple words, it can be understood in such a way that whenever a value of one primitive data type is assigned to another type.

Types of Typecasting

There are generally two types of typecasting available in Java:

  • Widening Casting : It is the casting that involves conversion of a smaller type in to a larger type. Here is the sequence of widening casting: byte -> short -> char -> int -> long -> float -> double
  • Narrowing Casting : It is the casting that involves conversion of a larger type in to a smaller type. Here is the sequence of narrowing casting: double -> float -> long -> int -> char -> short -> byte

1. Widening Casting in Java

Widening casting is known as the automatically happening typecasting that is done when a small size type is passed to a larger size type.

Here is an example of the widening casting in Java language that will definitely help you in understanding the topic:

public class Demo 
{
  public static void main(String[] args) 
  {
    int num = 5;
    double num1 = num; //it will  Automatic cast int to double
    System.out.println(num);     // Output is  5
    System.out.println(num1);   // Output is  5.0
  }
}
Output :
5
5.0

2. Narrowing Casting

Narrowing Casting is generally needed to be done manually just by placing the type in parentheses in front of the value.

Here is an example of the Narrowing casting in Java language that will definitely help you in understanding the topic:

public class Demo 
{
  public static void main(String[] args) 
  {
    double num = 5.75;
    int num_int = (num) myDouble;
    System.out.println(num);   // Output 5.75
    System.out.println(num_int);// Outputs 5
  }
}
Output :
5.75
5