Search code examples
javavariablesscope

What is the scope of a Java variable in a block?


I know in C++ variables have block scope, for example, the following code works in C++:

void foo(){
    int a = 0;
    for (int i = 0; i < 10; ++i){
        int a = 1; // Redefine a here.
    }
}

But this snippet doesn't work in Java, it reports "duplicate local variable a", does it mean Java variables don't have BLOCK scope?


Solution

  • java variables do have a block scope but if you notice int a is already defined in scope

      { 
         int a = 0;
          {
           {
            } 
          }
    
    
    
    
       }

    all subscopes are in scope of the uppermost curly braces. Hence you get a duplicate variable error.