Janki Shah wrote:
In this code, since a and b are final it works fine and prints -1. but, if I remove modifier final then, i get compiler error asking for casting to byte [(byte)a - b] or declaring c of type int.
I don't understand the difference between this to situations and also the reason.
Please help.
First, to understand the explanation, you need to understand what is a compile time constant... see one of my previous topics for a full explanation....
https://coderanch.com/t/454384/java/java/compile-time-constant
Second,
Java has an interesting special rule regarding compile time constants, and assignments (specifically related to section 5.2, under assignment conversions). Here is an excerpt from the JLS...
In addition, if the expression is a constant expression (ยง15.28) of type byte, short, char or int :
--> A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
--> A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is :
------> Byte and the value of the constant expression is representable in the type byte.
------> Short and the value of the constant expression is representable in the type short.
------> Character and the value of the constant expression is representable in the type char.
If the type of the expression cannot be converted to the type of the variable by a conversion permitted in an assignment context, then a compile-time error occurs.
Basically, with assignments, implicit casting is done (from int to byte) provided that the value is a compile time constant -- and that the value fits into the range of a byte. Given this, then line 5 and line 6 definitely compiles, as int literals are definitely compile time constants -- and the example has values which fits into a range of a byte.
As for line 7, it will only compile if the expression on the right is a compile time constant expression. And interestingly, if line 5 and line 6 are declared as final, then it is... as explained in the other topic.
Henry