Block scope variables

后端 未结 5 1709
时光说笑
时光说笑 2020-12-09 17:38

This will compile

class X
{  
    public static void main(String args[])
    {
        {
            int a = 2;
        }
        {
            int a = 3;
          


        
5条回答
  •  盖世英雄少女心
    2020-12-09 18:25

    Java doesn't allow you to have two variables with the same name within scope of one another.

    In your second case:

    int a = 2;
    
    {
      // the outer 'a' is still in scope
      int a = 3; // so this is a redeclare <-- nooo!
    } 
    

    However, in your first case, each a is contained within its own scope, so all is well.

提交回复
热议问题