Have a look at the following code :
Case 1 :
char a = 'x' ^ 'y';
It is working fine. But when I use variable instead of constants as here :
Case 2:
char x = 'x';
char y = 'y';
char a = x ^ y; // Error!
In java language : case 1 is working and value of a comes out to be 1 but case 2 is not working.
In C and C++ : both cases are working, and the value of a comes out to be 1
In C# : both the cases are not working.
In javascript : both cases are working, which is not a HLL, and value of a comes out to be 0.
I understand that java is converting variables to integer to do binary operation, but why it is working in case 1 and not in case 2, Why same is not working in C# And why the values are different in the case of javascript.
Updated When I made the variables final than it is working in java, but still not in C#
final char x = 'x';
final char y = 'y';
char a = x ^ y;
But still I cannot understand why constants are working but when using variable they are not. And why same is not happening with other high level programming language.
I think it is a basic operation and should be working in all programming languages with same behaviour.
Note To test all above cases in javascript I am replacing 'char' with 'var' in all cases and they are working.
Answering for Java only.
The expression 'x' ^ 'y'
is a constant expression; x ^ y
is not, unless both variables are declared final
. Furthermore, the result is an int
; ^
is an integral bitwise operator, meaning that both operands have to be promoted to an integral type before being evaluated. char
promotes to int
.
So you have this int
expression, and you try to narrow it to a char
. In the general case, this could lead to a loss of precision (ints are 4 bytes, chars are 2), so the compiler doesn't let you do that without you explicitly stating it's what you want to do (via a cast to char
). However, you can implicitly narrow constant expressions, if their value would fit into the new type. From JLS 5.2:
- A narrowing primitive conversion may be used if the type of the variable is
byte
,short
, orchar
, and the value of the constant expression is representable in the type of the variable.
(Emphasis added)
Intuitively, this makes total sense: the error is there to tell you that you may lose precision, and so it wants you to confirm that you know that; in a sense, it's a loud warning. But if the compiler can know absolutely that this won't happen, as it can for a constant expression, then it makes things a bit easier for you and "hides" that warning.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句