Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top