+ 14
Doubt Regarding Operation
public class Program { public static void main(String[] args) { byte b=20; // Line 1 b=b+1; //Line 2 } } In this code the literal '20' by default is of type int and in the next line the expression b+1 after addition operation also of type int as byte+integer=integer. My question is why we get error in the statement b=b+1 and not in byte b=20.
2 Answers
+ 6
Java automatically promotes the type of each part of the expression to int.
Automatic type conversion can sometimes cause unexpected translator error messages.
For example, the code shown below, although it looks quite correct, results in an error message during the translation phase. In it, we are trying to write the value 20 + 1, which should fit perfectly into the byte type, into a byte variable. But due to the automatic conversion of the result type to int, we receive an error message from the translator - after all, when int is entered into byte, a loss of precision may occur.
byte b = 20;
b = b + 1;
(Incompatible type for =.
Explicit conversion of int to byte is required).
Corrected text:
b = (byte) (b + 1);
or
b += 1;