Menu
Topics Index
...
`

Int to Byte Conversion - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App