+ 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.

21st Jul 2021, 6:31 AM
💖Cavalry💕
💖Cavalry💕 - avatar
3 ответов
+ 7
Thank you Jazz and Vasiliy for all of your hard work .I am starting to get the concept now
21st Jul 2021, 8:50 AM
💖Cavalry💕
💖Cavalry💕 - avatar
+ 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;
21st Jul 2021, 8:27 AM
Solo
Solo - avatar