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.

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

byteshort, int, long, float, double
shortint, long, float, double
charint, long, float, double
intlong, float, double
longfloat, double
floatdouble
  • Narrowing Conversion

shortbyte, char
charbyte, short
intbyte, short, char
longbyte, short, char, int
floatbyte, short, char, int, long
doublefloat, byte, short, char, int, long

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription