Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the sum of bytes integer? [duplicate]

I have tyo byte variable

byte a = 3;
byte b = 4;

If I sum them, the value of sum is integer.

byte z = a+b  //error, left side is byte, right side is integer

Why a+b is int?

like image 327
user2693979 Avatar asked Feb 19 '14 23:02

user2693979


1 Answers

Because the Java Language Specification says so

Binary numeric promotion is performed on the operands (§5.6.2).

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

The type of an additive expression on numeric operands is the promoted type of its operands.

and, regarding numeric promotion,

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • [...]
  • Otherwise, both operands are converted to type int.

So the byte values are promoted to int values and added up. The result of the expression is the promoted type, therefore an int.

You can simply cast the result

byte z = (byte) (b + a);

but careful with overflow/underflow.

like image 75
Sotirios Delimanolis Avatar answered Oct 24 '22 13:10

Sotirios Delimanolis