+ 1
Why this code shows Error?
byte a=5; byte b=10; byte c=a+b; System.out.print(c); Can u explain? https://code.sololearn.com/cQvwUbbmuQFu/?ref=app
2 Antworten
+ 4
well, in Java, bytes get converted to ints during arithmetic operation.
“The Java virtual machine provides the most direct support for data of type int. This is partly in anticipation of efficient implementations of the Java virtual machine's operand stacks and local variable arrays. It is also motivated by the frequency of int data in typical programs. Other integral types have less direct support. There are no byte, char, or short versions of the store, load, or add instructions, for instance.”
Edit: right, I forgot you can also cast a+b as byte in most cases, or change c to type int:
byte c = (byte)(a+b)
int c = a+b