Menu
Topics Index
...
`


Variables >
Siva Nookala - 12 Apr 2016
Sometimes it is necessary to convert variables of one type to another type. e.g., convert values present in an int to byte or from short to long.

Type conversion happens between two variables when the following 2 rules are met.
  • The two types are compatible. i.e. They are of integer type or floating point type.
  • The destination type is larger than source type. e.g., Source is short which is of size 2-bytes where as the destination is of type int which is 4-bytes.
This automatic conversion is also called as widening conversion.
Type Conversion
class TypeConversion
{
    public static void main(String arg[])
    {
        byte b = 50;
        short s = 4125;
        int i = 800000;
        long l = 107343L;
        
        s = b;    // LINE A
        i = s;    // LINE B
        l = i;    // LINE C
        
        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 );    
    
    }
}
OUTPUT

b = 50
s = 50
i = 50
l = 50
d = 50.0
f = 50.0

DESCRIPTION

Initially we declared all integer type variables and converted from lower size to higher size. The conversion is automatic since every assignment follows the two rules mentioned above.
The reason why i prints 50 instead of 4125 is, when s = b; is executed the value of s is over written with 50 and the later when i = s; is executed, i will become 50. That is the reason why all other values are also 50.
Also note that floating point variables d and f print 50.0 instead of 50.

THINGS TO TRY
  • Rearrange LINE A, LINE B and LINE C in the order LINE C, LINE B and LINE A and see the output.
  • Change 107343L to 107343 and see if type conversion happens automatically for literals as well. Note that 107343 is an int literal where as 107343L is a long literal.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.