Table of content

Type Casting in java

The process of converting the value of one data type into another is called Type Casting. An example of typecasting is converting an integer to a string.

Similarly, you can convert double to int and vice versa. The automatic conversion is done by the compiler and manual conversion is done by the programmer.

There are mainly two types of type casting-

  1. Widening Type Casting
  2. Narrowing Type Casting

Widening Type Casting-

In Widening Type Casting, one data type is converted into another automatically. In Widening Type Casting, the lower data type (having smaller size) is converted into the higher data type (having larger size).

Hence there is no loss in data. This is why this type of conversion happens automatically. This is also known as Implicit Type Casting.
picture1

Example of Implicit/Widening type casting -

Here we have assigned the int type variable 'num' to a double type variable 'val'. Java automatically converts the int type data into the double type and then assigns it the double variable.

 public static void main(String[] args) {
    // create int type variable
    int num = 5;
    System.out.println("The integer value is " + num);
    // convert into double type
    double val = num;
    System.out.println("The double value is " + val);
  }

Output-

The integer value is 5
The double value is 5.0

When you are assigning a larger type value to a variable of a smaller type, then you need to perform explicit type casting. If you don't perform casting then the compiler reports compile-time error.

So In Narrowing Type Casting or explicit type casting, we manually convert one data type into another using the parenthesis.

In case of Narrowing Type Casting, the higher data types (having larger size) are converted into lower data types (having smaller size). Hence there is the loss of data. This is why this type of conversion does not happen automatically.

picture2

The below example will make it clear to you what an explicit type casting is and how it is done. Here, double type is stored into long, and long type value is stored into int.

public static void main(String[] args) 
    { 
      double d = 14.05;  
      //converting double type value to a long type value
      long l = (long)d;   
      //converting a long type value into int 
      //int keyword inside the parenthesis indicates that the 'l' variable
     //is converted from long into an integer type
      int i = (int)l;  
      System.out.println("Double value is"+d); 
      System.out.println("Long value is"+l);  
      System.out.println("Int value is"+i);  
    }  

Output-

Double value is 14.05
Long value is 14
Int value is 14
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions