Friday, August 4, 2017

Type Conversion and Casting


Assigning value of one type to variable of another type is known as conversion.

In java we have two types of conversions.

  1. Implicit type conversion.
  2. Explicit type conversion.



1. implicit type conversion
Java automatically converts from one type to another  if it satisfy the following conditions.
1 Both types are compatible with each other.
2 The size of destination type is more than the source type.
This is also known as “Widening Conversion”.
Example
int i = 3;                                   int i=5;//size of int is 32
double f;                                  long d;//size of long is 64
f = i;                                        d=I;    
Example program
class TypeConversion
{
    public static void main(String arg[])
    {
        byte b = 50;
        short s = 4125;
        int i = 800000;
        long l = 107343L;       
        s = b;    
        i = s;   
        l = i;   
        float f = 25.0f;
        double d = 327.98;
        f = i;
        d = f;
        System.out.println("b = " + b );   
        System.out.println("s = " + s );   
        System.out.println("i = " + i );   
        System.out.println("l = " + l );   
        System.out.println("d = " + d );   
        System.out.println("f = " + f );  
    }
}

2. Explicit type conversion
If we want to convert two types which are incompatible or if the size of destination type is less than the size of source type, then we must do the conversion explicitly.
This process is also called as “type casting”. This is also called as Narrowing conversion .
Explicit type cast is requires to Narrowing conversion to inform the compiler that you are aware of the possible loss of precision.
Syntax
newValue = (typecast)value;
Example
double f = 3.5;
int i;
 i = (int)f; // it cast double value 3.5 to int 3.

Example program
class DatatypeCasting
{
    public static void main(String arg[])
    {
        byte b;
        int i = 81;
        double d = 323.142;
        float f = 72.38f;
        char c = 'A';
       
        c = (char) i;
        System.out.println("i = " + i + " c = " + c);
       
        i = (int) d; 
        System.out.println("d = " + d + " i = " + i); 
       
        i = (int) f; 
        System.out.println("f = " + f + " i = " + i); 
       
        b = (byte) d;
        System.out.println("d = " + d + " b = " + b);
   
    }
}

No comments:

Post a Comment