java中的强制转换和转换
升级意味着将较小的类型文字升级或转换为较高的类型。此提升用于计算表达式。现在我对此有点怀疑。当我键入此语句时
byte var1 = 56 + 10;
答案是66。这怎么可能呢? 根据提升规则,每个字节、short和char都被提升为int。因此,56和10将被提升为int,因此答案66将是int。这66将存储在字节类型的变量中。然而,要存储从int到byte的内容,需要进行转换。但是这段代码在没有强制转换的情况下可以完美地工作
你可以在下面搜索框中键入要查询的问题!
升级意味着将较小的类型文字升级或转换为较高的类型。此提升用于计算表达式。现在我对此有点怀疑。当我键入此语句时
byte var1 = 56 + 10;
答案是66。这怎么可能呢? 根据提升规则,每个字节、short和char都被提升为int。因此,56和10将被提升为int,因此答案66将是int。这66将存储在字节类型的变量中。然而,要存储从int到byte的内容,需要进行转换。但是这段代码在没有强制转换的情况下可以完美地工作
# 1 楼答案
这没关系,因为你给的是常量值。见compile-time narrowing of constants
# 2 楼答案
与许多情况一样,在Java Language Specification § 5.2中可以找到这一点:
这意味着编译器首先扩展到
int
,然后缩小到目标类型,因为66确实可以在目标类型(即字节)中表示请注意,这仅适用于常量表达式。例如,以下代码产生编译时错误: