Block scope variables

后端 未结 5 1687
时光说笑
时光说笑 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

    public static void main(String args[])
    {
        int a = 2; // I know a
        // I know a
        {
            // I know a
            int a = 3; // There can be only one a!
        }       
    }
    

    In the example above you declared a in you method main(). From the declaration till the end of the method, a is declared. In this case you cannout redeclare a in you codeblock.

    Below, you declare a in a block. It is only known insside.

    public static void main(String args[])
    {
        { 
            int a = 2; // I know a
            // I know a
        }
        // Who is a?
        {
    
            int a = 3; // I know a!
        }       
    }
    

提交回复
热议问题