Addition of byte values in Java

The byte data type in Java is a signed integer based on the two’s complement 8-bit mechanism. It is different from the int data type that uses 4 bytes (i.e., 32-bit to store a number). The values that can be stored in a single byte are -128 to 127. byte data types are primitive.

svg viewer

How it works

  1. Two variables of type byte are created and their values are declared.

  2. Both variables are then added and stored in another byte type variable.

  3. Additions are always typecasted​.

The following code explains this process better:

class example {
public static void main(String[] argv){
byte a = 3;
byte b = 8;
byte result;
result = (byte) (a + b); //addition typecasted
System.out.println(result);
}
}

Byte overflow

Byte overflow is a problem that needs to be understood when dealing with bytes. If the result is greater than 127 or less than -128, then the byte variable overflows (i.e., it cannot contain the resulting value in a single byte). The remainder result is then displayed instead of the original result.

For example, 124 + 76 = 200. As we know, 200 cannot be stored in a single byte, so the resulting variable will now store -56 instead of 200. This happens because 200 - 256 (capacity of two bytes) is equal to ​- 56. Try this in the code ​above!

Copyright ©2024 Educative, Inc. All rights reserved