Block scope variables

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

    In Java all local variables will be stored on Stack. So if u write

    class X
    {  
    public static void main(String args[])
    {
       int a = 2;    // At this point var 'a' is stored on Stack
       {
           /*
           Now as the prev. 'main method is not yet complete so var 'a' is still present on the Stack. So at this point compiler will give error "a is already defined in main(java.lang.String[])" 
            */
           int a = 3;   
    
       }
     }
    }
    

    Hope this help you out

    Thanks

提交回复
热议问题