This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Debug Note < Raw Conversion and Assignment in Java >
Ask questions
I understand the reasons for the following errors:
byte a = 3;
byte b = 8;
byte c = a + b; // compile error
Copy the code
It doesn’t compile. The expression always results in an int. Therefore, we should do an explicit conversion:
byte c = (byte) (a + b); // valid code
Copy the code
But I don’t see why the following is true:
byte d = 3 + 8; // it's valid! why?
Copy the code
Because literal integers (such as 3 or 8) are always implicitly int.
And int-or-smaller always causes int. Can anyone explain what’s going on here?
The only thing I can guess is that the compiler equates this expression to the following:
byte d = 11;
And I don’t think it’s an expression.
Answer a
Yes, it does.
As long as the right-hand side of the expression is made up of constants (suitable for the desired basic type, see @Jason’s answer for exactly what JLS says about this),
You can do that. Since 128 is out of range,
Therefore cannot compile:
byte a = 128;
Copy the code
Note that if you convert the first code snippet like this:
final byte a = 3;
final byte b = 8;
byte c = a + b;
Copy the code
It compiles! Because these two bytes are their expressions, final, and their expressions are constant, this time the compiler can be sure that the result will fit a byte when first initialized.
However, this will not compile:
final byte a = 127; // Byte.MAX_VALUE
final byte b = 1;
byte c = a + b // Nope...
Copy the code
The compiler will error with “possible loss of precision”.
Answer two
This is because 3 and 8 are compile time constants.
Thus, at compile time, the compiler can recognize variables that 3 + 8 can fit into byte variables.
If you set the final variable (constant) of your variables A and B to constant. A + b will become a compile time constant.
Therefore, it will compile without problem.
final byte a = 3;
final byte b = 8;
byte c = a + b;
Copy the code
The article translated from Stack Overflow: stackoverflow.com/questions/1…