I am trying to add two values in a byte array. This is my code:
byte[] ars = {3,6,9,2,4};
ars[0] = (byte)ars[0] + (byte)ars[4];
System.out.println( ars[0] );
public static void main(String args[]){
byte[] ars = {3,6,9,2,4};
ars[0] = (byte)(ars[0] + ars[4]);
System.out.println( ars[0] );
}
this happens for the reason that java automatically converts expressions which use byte and short variables to int... this is to avoid potential risk of overflow.... as a result even if result may be in the range of byte java promotes type of expression to int