gpt4 book ai didi

Java 字符到字节转换

转载 作者:IT老高 更新时间:2023-10-28 20:28:37 25 4
gpt4 key购买 nike

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

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 variables , b1 被视为常量:

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.

关于Java 字符到字节转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30346587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com