Java char to byte casting

时间秒杀一切 提交于 2019-11-29 09:06:11

When the variable is final, the compiler automatically inlines its value which is 1. This value is representable as a char, i.e.:

c = b1;

is equivalent to

c = 1;

In fact, according to this section on final variables, b1 is treated as a constant:

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

The conversion from byte to char is a widening and narrowing primitive conversion, as described in paragraph 5.1.4 of the Java Language Specification.

As the JLS describes, this is done via an intermediate step; the byte is converted to int via a widening primitive conversion and then the int is converted to char via a narrowing primitive conversion (see 5.1.3).

Paragraph 5.2 explains when a cast is necessary when you do an assignment:

... 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.

Your variable b1 is indeed a constant, but your variable b2 is not, so this rule applies for b1 but not for b2.

So: you can assign b1 to c because b1 is a constant and the value of the constant, 1, fits in a char, but you cannot assign b2 to c without a cast because b2 is not a constant.

Well , its because byte is a signed type while char is not, so u need to apply explicit type conversion for (2)

c = (char)b2;

also the final statement worked for 1 because prior to compilation , the compiler is able to confirm that there is no loss due to conversion since '1' is in the range of char , try putting '-1' with the same final statement in (1) you will again get a compilation error.

All this boils down to the type compatibility between signed and unsigned types..which needs to be done explicitly in java.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!