Naming two kinds of scope in Java

Viewed 199

I have difficulties in naming the two kinds of scopes that I see in Java:

class Fun {
    int f = 1;
    void fun() {
        int f = 2;
        while(true){
            int f = 3;
            int g = 1;
        }
        int g = 2;
    }
}

The case is mostly with f = 3 and g = 2;

A while statement doesn't introduce a new scope, so I can't create a while-local variable named f. But if I create a local variable named g then I can "re-create" it after the loop. Why? I know it's no longer accessible, but if the compiler checks accessibility then it almost checks scopes..

So I was wondering what is the deal here, what are these concepts called? Is it the same as in C++?


I just managed to install g++ and tried it out myself:

#include <iostream>
using namespace std;

int main(){
    int f = 0;
    for(int i=0; i<1; i++){
        int f = 1;
        cout << f << endl;
        {
            int f = 2;
            cout << f << endl;
        }
    }
    cout << f << endl;
}

So apparently C++ treats all scopes equally!

4 Answers
Related