I'm trying to figure out why some castings work and why others do not. Can you explain to me why some of these examples work and others don't?
Setup:
I'm using jshell.
byte one = 1;
one ==> 1
Example 1:
jshell> byte val = 200 - 200;
val ==> 0
According to my knowledge these literals are of type int, but code compiles because the result fits in the byte.
Example 2
jshell> byte val = 1 - one;
| Error:
| incompatible types: possible lossy conversion from int to byte
| byte val = 1 - one;
| ^-----^
When I'm switching one literal to a variable, code suddenly does not compile. Casting any or all of components of the espression doesn't fix the problem.
Example 3
jshell> byte val = (byte)(1) - one;
| Error:
| incompatible types: possible lossy conversion from int to byte
| byte val = (byte)(1) - one;
|
I expected this to work. After all I did convert the integer in this expression to byte, so there shouldn't be 'incompatible types' error.
Example 4
jshell> byte val = 1 - (byte)(one);
| Error:
| incompatible types: possible lossy conversion from int to byte
| byte val = 1 - (byte)(one);
| ^-------------^
This was more an experiment to see if this would fix the problem. I didn't expect this to work.
Example 5
jshell> byte val = (byte)(1) - (byte)(one);
| Error:
| incompatible types: possible lossy conversion from int to byte
| byte val = (byte)(1) - (byte)(one);
| ^---------------------^
This one confuses me so much. I'm casting both components to byte, so why would there be an error? After all in Example 1 there was a similar operation and Java didn't complain at all.
Example 6
jshell> byte val = (byte)(1 - one);
val ==> 0
In the end only casting result of the expression doesn't produce an error. Why?
Java automatically promotes each
byte,short, orcharoperand tointwhen evaluating an expression. Because the operands are automatically promoted tointwhen the expression is evaluated, the result also gets promoted toint. Thus, the result of the expression is now of typeint, which cannot be assigned to abytewithout the use of a cast.