使用三元运算符和最终变量时出现意外输出 [英] Unexpected output when using a ternary operator and final variable

查看:149
本文介绍了使用三元运算符和最终变量时出现意外输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

public static void main(String[] args) {
    int z1 = 0;
    final int z2 = 0;
    System.out.println(false ? z1 : 'X');
    System.out.println(false ? z2 : 'X');
}

运行此代码时,我希望看到两个 X 。但是,实际输出是:

When running this code, I would expect to see two X in your console. However, the real output is:


88

X

88
X

如果我们看一下关于三元运算符的Java规范,我们发现

If we take a look at the Java specifications regarding the ternary operator, we found that


如果其中一个操作数是T类型其中T是byte,short或char,另一个操作数是int类型的常量表达式,其值可以在类型T中表示,那么条件表达式的类型是T.

If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.

因此第一个输出将'X' char视为 int ,这就是它打印 88 的原因。

So the first output considers the 'X' char as an int, that's why it prints 88.

但是,我不确定为什么要使用 final 更改第二个输出的行为。

However, I am not sure to understand why the use of final changes the behavior for the second output.

推荐答案

在第二种情况下, z2 算作常量表达式,因为它是 int 类型的最终变量。

In the second case, z2 counts as a constant expression, because it's a final variable of type int.

来自 4.12.4节


我们调用一个原始类型或类型为String的变量,即final并使用编译时常量表达式(第15.28节)初始化一个常量变量。变量是否是常量变量可能对类初始化(第12.4.1节),二进制兼容性(第13.1节,第13.4.9节)和明确赋值(第16节)有影响。

We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

第15.28节在项目集中包含常量变量,可用于形成常量表达式。

Section 15.28 includes "constant variables" in the set of items which can be used to form a constant expression.

z1 不是一个最终变量(即使没有别的东西给它赋值)所以它不是一个常量变量,因此不是一个常量变量 - 所以你引用的段落来自规范不适用。

z1 is not a final variable (even though nothing else assigns a value to it) so it's not a constant variable, and thus not a constant expression - so the paragraph you quoted from the spec doesn't apply.

这篇关于使用三元运算符和最终变量时出现意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆