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

I know that in C ++ variables there is a block area, for example, the following code works in C ++

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

}

but this fragment does not work in java, it says "duplicate local variable a", does this mean that java variables do not have a BLOCK scope?

+3
source share
5 answers

java variables have a block scope, but if you notice that int a is already defined in scope

  { 
     int a = 0;
      {
       {
        } 
      }




   }

all undermining are in the area of ​​the topmost braces. Therefore, you get a duplicate variable error.

+3
source

. , . Java .

+9

Section §14.4.2 :

(§14.2) , , (§14.4) .

v , v .

+4

The previous answers already indicated the reason, but I just want to show that this is still allowed:

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

In this case, the ainside does not hide the external a, therefore it is valid.

And IMHO should also be like this in C ++, this is less confusing and prevents accidental declaration of a variable with the same name.

+3
source

It does, but it is nested, so the "a" you defined in foo () is available in all blocks inside foo.

Here is an example of what you are looking for:

void foo(){
    {
        int a = 0;
        // Do something with a
    }
    for(int i = 0; i < 10; ++i){
        int a = 1; //define a here.
    }
}
+2
source

Source: https://habr.com/ru/post/1768029/


All Articles