Java: Type Conversion

Type Conversion

Conversion of one data type by deducing the structure of the expression and the types of literals, variables and methods mentioned in the expression, to another data type is known as Type Conversion or Type Casting.

We have two types of Type conversion namely-

  • Widening Conversion.
  • Narrowing conversion. 

Widening Conversion

  • Converting a data type of smaller size to a data type of larger size is known as Widening conversion.
  • This type of casting/conversion is done automatically hence, it is also known as implicit type casting.
  • The condition for this case of conversion is that the data types should be compatible with each other.
  • In this type of data conversion we neither have any error nor any loss of data whatsoever.

Let us understand through an example-

Widening Conversion
Run
public class Main 
{ 
    public static void main(String[] args) 
    { 
        int num = 500;
        
        long l = num;  

        float f = l;  

        System.out.println("Int type value "+num); 
        System.out.println("Long type value "+l); 
        System.out.println("Float type value "+f); 
    } 
}
Output :

Int type value 500

Long type value 500

Float type value 500.0

Narrowing Conversion

  • Converting a data type of larger size to a data type of smaller size is known as Narrowing conversion.
  • This type of conversion does not occur automatically,  hence we need to convert explicitly using the cast operator “( )” explicitly. Thus, it is also known as explicit type casting.
  • This is useful for incompatible data types where automatic conversion cannot be done.
  • One of the drawbacks of narrowing conversion is the loss of data.

Let us understand through an example-

Narrowing Conversion
Run
class Main
{ 
    public static void main(String[] args) 
    { 
        double d = 560.025;

        long l = (long)d; 

        int num = (int)l;  

        System.out.println("Double type value "+d); 
        System.out.println("Long type value "+l);  
        System.out.println("Int type value "+num);  
    }  
}
Output :

Double type value 560.025

Long type value 560

Int type value 560

Permitted Conversions

  • Widening conversion

byte short, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double
  • Narrowing Conversion

short byte, char
char byte, short
int byte, short, char
long byte, short, char, int
float byte, short, char, int, long
double float, byte, short, char, int, long