In this tutorial we will see how to add bytes values in java . In java byte data type 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 in java. Now we will see different ways to add bytes in java .
Example 1 : Add bytes in java Using typecasting
In this example we are adding bytes using typecasting . Sum will be in byte .
Approach:
- We will create two byte and initialize with values .
- Add byte and store value in byte variable .
- Result will be typecast .
Now we will write java program to addition of calculating bytes . Let’s see code for adding bytes in java
public class AddBytes {
public static void main(String[] args) {
byte a = 100;
byte b = 100;
byte result;
result = (byte) (a + b); // addition typecasted
System.out.println(result);
}
}
Output :
-56
Example 2 : Add bytes in java without typecasting
Now we will write java program to add bytes without using typecasting .
Approach:
- We will create two byte and initialize with values .
- Add byte and store value in int variable .
- Result will be in int value.
Java program to addition calculating byes . Let,s see code for that .
public class AddBytesWithoutCasting {
public static void main(String[] args) {
byte a = 100;
byte b = 100;
int result;
result = a + b; // without typecasting
System.out.println(result);
}
}
Output:
200
In this tutorial we have learned how to add bytes In java . We done addition calculating bytes using typecasting and without typecasting . We have seen that how to sum of two bytes store in int . You can see more java program for practice .