java - 为什么 Java 语言规范说表达式 (n > 2) 不是常量表达式?

标签 java

Definite Assignment 上的 Java 语言规范一章中, Example 16-2说是

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 */ 
}

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,它是这样说的

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

可以贡献常量表达式。

表达式 n > 2 是否是常量表达式?我们如何确定这一点?

最佳答案

之所以这么说是因为n不是 constant expression .

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:

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不是常量表达式。

关于java - 为什么 Java 语言规范说表达式 (n > 2) 不是常量表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34660442/

相关文章:

java - 为什么这个 GUI 应用程序不向我显示图像?

java - log4j2 触发 System.exit

Java并发&分布式场景

java - Spring Batch Json 自定义 ItemWriter

java - 找不到 RMI 注册表

java - 如何在 Swing GUI 中使用 JDialog?

java - TCP 套接字上的 Ascii

java - Android Spinner 在 OnCreate 中执行 ItemSelectedListener

java - 在jsp页面中读取java类函数变量

java - 从外部网站执行java GUI程序