Menu
Topics Index
...
`


Variables >
Siva Nookala - 23 Feb 2017
Type conversion is automatically done if the types are compatible and source type is smaller than destination type. But when destination type is smaller than source type, then we need to explicitly cast it. This is called as 'Type Casting'. This is also called narrowing conversion and truncation.

A cast is an explicit type conversion.
(target-type) value
Int to Byte Conversion
class IntToByteConversion
{
    public static void main(String arg[])
    {
        int a = 350;
        byte b;
        
        b = (byte) a;
        
        System.out.println("b = " + b );
    
    }
}
OUTPUT

b = 94

DESCRIPTION

When a value of larger size in the 350 is casted into a byte whose range is -128 to 127, it is narrowed down to fit into that range. So the value becomes 94 from 350.
We need to be careful with this kind of conversion, since if the destination type range can not store the source value it is shortened and possibly loses the data.

THINGS TO TRY
  • Assign to the variable a values like 30, -25 (which are in the byte range) and values like 7000, -1500 (which are outside the byte range) and see what will be output.
This casting can be done between various types in integer group, floating group and to char group.
Data type casting
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; // LINE A
        System.out.println("d = " + d + " i = " + i); // LINE B
        
        i = (int) f; // LINE C
        System.out.println("f = " + f + " i = " + i); // LINE D
        
        b = (byte) d;
        System.out.println("d = " + d + " b = " + b);
    
    }
}
OUTPUT

i = 81 c = Q
d = 323.142 i = 323
f = 72.38 i = 72
d = 323.142 b = 67

DESCRIPTION

When i is casted to c the value corresponding to the ascii code of 81 which is 'Q' is assigned.
When d is casted to i the decimal part .142 is truncated and only 323 is assigned to i.
Similarly when f is casted to i, the decimal part .38 is truncated and only 72 is assigned to i.
When d is casted to b whose range is -128 to 127, not only the decimal part .142 is truncated but it is also shortened from 323 to 67 so as to fit in byte range.

THINGS TO TRY
  • Change initialization value of d from 323.142 to 2.75E+19 which is much higher than integer range and see what value will be printed in LINE B.
  • Change initialization of f from 72.38f to 72 and see what gets printed in LINE D.
  • Remove the type cast from d to i in LINE A, i.e. change i = (int) d; to i = d; and see that you get 'possible loss of precision' compilation error.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.