具有最终访问修饰符的char和byte-Java [英] char and byte with final access modifier - java
问题描述
请看下面的示例,我无法理解字符和字节之间的关系
Please take a look at below example i cant understand the relation between char and byte
byte b = 1;
char c = 2;
c = b; // line 1
给我编译错误,因为c为char
类型,b为byte
类型,因此强制转换必须处于这种状态
Give me compilation Error because c is type of char
and b is type of byte
so casting is must in such condition
但是现在这里的tweest是当我在代码下运行时
but now the tweest here is when i run below code
final byte b = 1;
char c = 2;
c = b; // line 2
第2行编译成功,根本不需要任何强制转换
所以我的问题是为什么当我在byte
line 2 compile successfully it doesn't need any casting at all
so my question is why char
c behave different when i use final access modifier with byte
推荐答案
由于使用final
对其进行了限定,因此使该变量成为常量变量,这是
Because qualifying it with final
makes the variable a constant variable, which is a constant expression. So
final byte b = 1;
char c = 2;
c = b; // line 2
实际上变成了
final byte b = 1;
char c = 2;
c = 1;
并且编译器保证值1
可以适合char
变量.
And the compiler has a guarantee that the value 1
can fit in a char
variable.
对于非常量byte
变量,没有这样的保证. 已签名byte
,未签名char
.
With a non constant byte
variable, there is no such guarantee. byte
is signed, char
is unsigned.
这篇关于具有最终访问修饰符的char和byte-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!