September 09, 2015

Type conversion in Java

Type conversion is very much necessary in the world of programming. We all know when it is needed. There are three types of type conversion in Java.

  1. Widening 
  2. Narrowing
  3. Mixed

  • Widening Conversion
The conversion from Sub to super data type is called the Widening Conversion. This conversion is also known as Implicit type conversion. This type conversion is automatically done by jvm.

The following type conversion is possible from one datatype to another datatype.
  1. byte to short, int, long, float, double
  2. short to int, long, float, double
  3. int to long, float, double
  4. long to float, double
  5. float to double

  int i = 123456789;
  float f = i;          // Widening conversion
  int j = (int) f;      // Narrowing conversion
  • Narrowing Conversion
The conversion from super to it's sub data type is called the Narrowing Conversion. This conversion is also known as Explicit type conversion. This conversion we need to do by our own. In this type conversion we need to do type casting otherwise compiler will give an error "Possible lose of Precision".

The following type conversion is possible from one datatype to another datatype.
  1. double to float, long, int, short, byte
  2. float to long, int, short, byte
  3. long to int, short, byte
  4. int to short, byte
  5. short to byte

   int i = 12345;
   short s = (short) i;

  • Mixed Conversion
The conversion from char to it's sub type and conversion from sub type of int to char is called mixed conversion. It is mixed type conversion because it contains narrowing and widening conversion.
The following type conversion is possible from one datatype to another datatype.
  1. byte to char
  2. short to char
  3. char to short, byte
    char c= 88;     //X
    System.out.println( c = (char)(c+2));  // will print Z

No comments:

Post a Comment