Why this is not compiling in Java?

前端 未结 3 1283
耶瑟儿~
耶瑟儿~ 2021-01-02 06:15

If you give

    public class test
    {
        public static void main(String ar[])
        {
            if (true)
                int i=0;
        }
    }         


        
相关标签:
3条回答
  • 2021-01-02 06:44

    Since you are defining a variable inside if block you need to have brackets.

    But below code will compile with a compiler warning.

    int i;
    if(true)
      i = 0;
    
    0 讨论(0)
  • 2021-01-02 06:55

    Variable declarations can only be declared in blocks, basically.

    Looks at the grammar for "statement" in the Java Language Specification - it includes Block, but not LocalVariableDeclarationStatement - the latter is part of the grammar for a block.

    This is effectively a matter of pragmatism: you can only use a single statement if you don't have a brace. There's no point in declaring a variable if you have no subsequent statements, because you can't use that variable. You might as well just have an expression statement without the variable declaration - and that is allowed.

    This prevents errors such as:

    if (someCondition)
        int x = 0;
        System.out.println(x);
    

    which might look okay at first glance, but is actually equivalent to:

    if (someCondition)
    {
        int x = 0;
    }
    System.out.println(x);
    

    Personally I always use braces anyway, as it makes that sort of bug harder to create. (I've been bitten by it once, and it was surprisingly tricky to spot the problematic code.)

    0 讨论(0)
  • 2021-01-02 07:01

    This is because a variable declaration needs a block context (a scope for it's lifetime), and hence you need the brackets (which define a block).

    0 讨论(0)
提交回复
热议问题