java - 下面两行java代码有什么区别?

标签 java switch-statement

<分区>

请原谅我的无知。我无法理解以下看似相似的代码行之间的区别。

  1. final int num1 = 1;
  2. final int num2; num2 = 2;

是什么让 num2 不符合 switch case 常量的条件?

    switch (expression) {
        case num1:
            System.out.println("Case A");
        case num2:
            System.out.println("Case B");
    }

最佳答案

我们开始学习 Java 语言规范。 switch语句的 case 标签定义为

SwitchLabel:
    case ConstantExpression :
    case EnumConstantName :
    default :

您的 num 变量没有引用 enum 常量名称,所以让我们忽略它。什么是 ConstantExpressions ? JLS再次定义它

A compile-time 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:

  • Literals of primitive type and literals of type String
  • [...]
  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).

因此原始 int2 是一个常量表达式。你可以做

switch {
    case 2:
}

现在我们想知道使用final的关系和常量变量

A blank final is a final variable whose declaration lacks an initializer. [...]

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.

所以最后一个引用是指一个非空白 final 变量,即。一个有初始化器的。

所以

final int num1 = 1;

是常量变量。

final int num2; 
num2 = 2;

不是,因此不能在 case 标签中使用。

关于java - 下面两行java代码有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22737176/

相关文章:

c - 在 switch 语句中从一个 case 跳转到 default case

javascript - 将 html 添加到 switch 语句中

c# - 不同版本解析文件不同

java - 使用 apache -common-validator 时出错 --java.lang.NoClassDefFoundError : org/apache/commons/digester/Rule

java - 使用Spring Integration下的Paho接收二进制MQTT消息

java - 从 arraylist 元素调用方法

c++ - 在 C++ 中,他们为什么要将 break 语句放在 switch 语句中?

java - Spring Boot 作为 war 与 jar

java - 通用 JUnit 测试

C++ char类型输入,int类型输出