Saturday, 25 April 2020

SE - 73 - Difference between : Type casting and type conversion

Type Conversion : This is done implicitly by JAVA for those conversions which are allowed to be done automatically.


Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens when:
-> The two data types are compatible.
-> When we assign value of a smaller data type to a bigger data type.

In java the numeric data types are compatible with each other but no automatic conversion is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other. If the conversion is done in the following sequence it will be Widening/Automatic conversion

Byte -> Short -> Int -> Long -> Float -> Double
int i = 10
          
        // automatic type conversion
        long l = i; 
          
        // automatic type conversion
        float f = l; 


Type Casting :  This is same as Type conversion but here we need to explicitly type cast the conversion. It is not done automatically by JAVA.

Narrowing or Explicit Conversion

If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or narrowing.

-> This is useful for incompatible data types where automatic conversion cannot be done.
-> Here, target-type specifies the desired type to convert the specified value to.

 Explicit Typecasting is done if the conversion is required in reverse order of implicit conversion :
Byte <- Short <- Int <- Long <- Float <- Double

  double d = 100.04
          
        //explicit type casting
        long l = (long)d;
          
        //explicit type casting 
        int i = (int)l; 





No comments:

Post a Comment