为什么Java语言规范说表达式(n> 2)不是常量表达式? [英] Why does Java Language Specification say that the expression (n > 2) is not a constant expression?

查看:129
本文介绍了为什么Java语言规范说表达式(n> 2)不是常量表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Definite Assignment <的Java语言规范章节中/ a>,示例16-2


Java编译器必须为代码产生编译时错误:

A Java compiler must produce a compile-time error for the code:

{
    int k;
    int n = 5;
    if (n > 2)
        k = 3;
    System.out.println(k);  /* k is not "definitely assigned"
                               before this statement */ 
}

即使n的值在编译时是已知的,并且原则上在$ ​​b $ b中,可以在编译时知道对k的赋值总是会执行
(更恰当地,评估)。 Java编译器必须根据本节中规定的规则运行
。规则只识别
常量表达式;在这个例子中,表达式n> 2是
而不是§15.28中定义的常量表达式。

even though the value of n is known at compile time, and in principle it can be known at compile time that the assignment to k will always be executed (more properly, evaluated). A Java compiler must operate according to the rules laid out in this section. The rules recognize only constant expressions; in this example, the expression n > 2 is not a constant expression as defined in §15.28.

但是,如果我们看§15.28,它说

But, if we look at §15.28, it says that


关系运算符<,< =,>,和> =

the relational operators <, <=, >, and >=

可以对常量表达式做出贡献。

can contribute to a constant expression.

是表达式 n> 2 是否表达常量?我们怎样才能确定这个?

Is the expression n > 2 a constant expression or not? How can we determine this?

推荐答案

它是这样说的,因为 n 是不是常量表达式

It says so because n is not a constant expression.


常量表达式是表示原始
类型或 String 不会突然完成,仅使用
组成以下内容:

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • [...]
  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).


常量变量是原始类型或类型的 final 变量
字符串用常量表达式初始化(​​§15.28)。

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).

n 不是 final ,因此不是常量变量。因此,它不是一个恒定的表达。因此 n< 2 不是常量表达式。

n is not final and therefore isn't a constant variable. It therefore isn't a constant expression. And therefore n < 2 is not a constant expression.

这篇关于为什么Java语言规范说表达式(n> 2)不是常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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