如果声明"不是声明"?

guo*_*guo 2 java intellij-idea

示例代码:

public class SalCal {
    public static void main(String[] args) {
        int a=0;
        if (a > 1)
            String string = "fds";//hint:not a statement
    }
}
Run Code Online (Sandbox Code Playgroud)

Intellij IDEA提示 String string = "fds";

不是声明

但是,如果我在任何一方面添加括号 String string = "fds";,它就不会像以前那样提示了.为什么?

Ste*_*n C 6

Intellij IDEA表示,因为它不是声明.这是一份声明1.

添加大括号时,您将其转换为块语句...这是一个语句.

但这就是问题所在.如果这段代码合法,那将毫无用处.

  if (a> 1)
        String string = "fds";
Run Code Online (Sandbox Code Playgroud)

为什么?因为声明的范围必须在声明结束时if结束.您将声明一个无法使用的变量.


这里有几个选择:

1)此版本声明if块中的变量

  if (a> 1) {
        String string = "fds";
        // you can use 'string' here
  }
  // ... but not here, because it is now out-of-scope.
Run Code Online (Sandbox Code Playgroud)

2)此版本在if语句之前声明并初始化变量,并在if中为其分配新值:

  String string = "asdf";
  if (a> 1) {
        string = "qwerty";  // assignment, not declaration
  }
  // OK to use 'string' here.
Run Code Online (Sandbox Code Playgroud)

@ Maroun的回答给出了为什么你写的不是有效的Java代码的技术原因.


1 - 实际上,Intellij IDEA编译器正在"松散于事实".实际上,JLS称之为"局部变量声明语句".所以它在技术上是一个"声明"......但它是一种特殊的类型,不能在所有可以使用普通的环境中使用.