Open In App

Java Program to Calculate Sum of Two Byte Values Using Type Casting

Last Updated : 11 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The Sum of two-byte values might cross the given limit of byte, this condition can be handled using storing the sum of two-byte numbers in an integer variable.

Example:

Input:  firstByte = 10, secondByte = 23
Output: Sum = 33

Input:  firstByte = 10, secondByte = 23
Output: Sum = 33

Type Casting: Typecasting is simply known as cast one data type, into another data type. For example, in this program, Byte values are cast into an integer.

Approach:

  • Declare and initialize the two-byte variable.
  • Declare one int variable.
  • Store the sum of the two-byte numbers into an int variable.

Below is the implementation of the above approach

Java




// Java Program to Calculate Sum of
// Two Byte Values Using Type Casting
  
public class GFG {
    public static void main(String[] args)
    {
        // create two variable of byte type
        byte firstByte = 113;
        byte secondByte = 123;
  
        // create int variable to store result
        int sum;
  
        sum = firstByte + secondByte;
        System.out.println("sum = " + sum);
    }
}


Output

sum = 236


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads