Pageviews

Friday 7 June 2013

Type conversion in Java

by Unknown  |  in Beginners at  Friday, June 07, 2013

Type Conversion is the process of converting one data type to another data type.Type conversion is useful in programs when we need to change the data type later on in the programs.Type conversion is of following types:

1.Implicit Type Conversion: In this type conversion,a data type of lower size is assigned to a data type of higher size.For example,Byte takes 1 byte space in memory and Short takes 2 bytes in memory,so this conversion can be done from Byte to Short.This rule applies for all implicit conversions.


2.Explicit Type Conversion:Since a data type of higher size cannot be assigned to a lower size,so explicit casting is performed by the user.The rule for explicit conversion is that the source type must be greater than the destination data type.


3.Boolean Type Conversion:This type conversion is not basically implemented anywhere,this type cannot be assigned to any data type,it is called as non-compatible data type.Boolean data type can assigned only to the Boolean.

To illustrate the above types,here are simple program blocks which performs the type conversion of all three types:

Implicit Type conversion:



1.    Byte to Short
public class ByteToShort
{
     public static void main(String args[])
     {
          byte b1 = 10;                // 1 byte 
          short s1 = b1;               //  one byte to 2 bytes
          System.out.println(s1);     // prints 10
     }
}
Explicit Type conversion:


2.        Float to Byte
public class FloatToByte
{
     public static void main(String args[])
     {
          float f1 = 10.5f;            // 4 bytes
       // byte b1 = f1;                // error as 4 bytes to 1 byte

          byte b1 = (byte) f1;        // 4 bytes type casted to 1 byte
          System.out.println(b1);     // prints 10
     }
}
Boolean Type conversion:


public class BooleanToString
{
    public static void main(String args[])
    {
            boolean b1 = true;
            String str = String.valueOf(b1);
            System.out.println("boolean b1 in string form is " + str);
   }
}


   

0 comments:

Proudly Powered by Blogger.