如果你给
public class test { public static void main(String ar[]) { if (true) int i=0; } }
它没有编译,但是带有花括号的相同代码是:
public class test { public static void main(String ar[]) { if (true) {int i=0;} } }
有什么解释?
基本上,变量声明只能在块中声明。
查看 Java语言规范中“语句”的语法 -它包括Block,但不包括LocalVariableDeclarationStatement- 后者是block语法的一部分。
这实际上是实用主义的问题:如果没有括号,则只能使用一个语句。如果没有后续语句,则声明变量是没有意义的,因为您不能 使用 该变量。您也可以只具有一个不带变量声明的表达式语句,这 是 允许的。
这样可以防止出现以下错误:
if (someCondition) int x = 0; System.out.println(x);
乍一看可能还不错,但实际上等效于:
if (someCondition) { int x = 0; } System.out.println(x);
就我个人而言,无论如何我总是使用花括号,因为它使这种错误更难以创建。(我曾经被它咬过,发现有问题的代码令人惊讶地棘手。)