Your code is
class Example{
public static void main(String args[]){
byte b1=10,b2=20,b3; //line 1
b3=b1+b2; //line 2
}
}
The cause of error at line 2 because JLS 5.6.2 makes it clear.
When an operator applies binary numeric promotion to a pair of
operands, each of which must denote a value that is convertible to a
numeric type, the following rules apply, in order, using widening
conversion (§5.1.2) to convert operands as necessary: If any of the
operands is of a reference type, unboxing conversion (§5.1.8) is
performed. Then: If either operand is of type double, the other is
converted to double. Otherwise, if either operand is of type float,
the other is converted to float. Otherwise, if either operand is of
type long, the other is converted to long. Otherwise, both operands
are converted to type int.
It means that Java prefers to treat smaller data types as ints, since any modern processor has at least 32-bit words anyway. A byte + a byte gets converted to an int + and int, and the result is an int. It's easy to add bits here - the new bits are all 0.
So you can solve this problem in two way -
1. Explicit Type Casting
class Example{
public static void main(String args[]){
byte b1=10,b2=20,b3; //line 1
b3= (byte)b1+b2; //line 2
}
}
- By declaring final
class Example{
public static void main(String args[]){
final byte x = 1;
final byte y = 2;
byte z = x + y;
}
}