Java 字符到字节的转换

Java char to byte casting

我一直在测试字符转换,我经历了这个:

public class Test {
    public static void main(String a[]) {
        final byte b1 = 1;
        byte b2 = 1;
        char c = 2;

        c = b1; // 1- Working fine
        c = b2; // 2 -Compilation error
    }
}

任何人都可以解释为什么当我向字节添加一个 final 时它在 1 中工作正常吗?

当变量为final时,编译器自动内联它的值为1。这个值可以表示为char,即:

c = b1;

等同于

c = 1;

其实根据this section on final variablesb1被当成常量处理:

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.

嗯,因为 byte 是有符号类型而 char 不是,所以你需要为 (2) 应用显式类型转换

c = (char)b2;

最终语句也适用于 1,因为在编译之前,编译器能够确认没有因转换而造成的损失,因为“1”在 char 的范围内,请尝试将“-1”与(1) 中相同的最终语句,您将再次遇到编译错误。

所有这些归结为有符号和无符号类型之间的类型兼容性..这需要在 java 中明确完成。

bytechar 的转换是扩大和缩小原始转换,如 Java 语言规范的 paragraph 5.1.4 中所述。

正如 JLS 所描述的,这是通过一个中间步骤完成的; byte 通过扩大原始转换转换为 int,然后 int 通过缩小原始转换转换为 char(参见 5.1.3)。

Paragraph 5.2 说明在您执行作业时何时需要强制转换:

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

你的变量 b1 确实是一个常量,但是你的变量 b2 不是,所以这个规则适用于 b1 但不适用于 b2.

因此:您可以将 b1 分配给 c,因为 b1 是一个常量,而常量的值 1 适合 char,但你不能在没有转换的情况下将 b2 分配给 c,因为 b2 不是常量。