Naming two kinds of scope in Java

c++, java, scope

Solution

Once you left the while{} loop g went out of scope as soon as you left it. It was then valid to declare g again.

Local variables are only in scope for the duration of the block in which they are declared.

To go into more detail:

- The first `f` is object scope. Its accessible from the object at all times.

- The second `f` is local scope. You access it using `f`, you can still access the object scope `f` using `this.f`.

The third `f` is trying to create a second local scope `f`. That is invalid.

The first `g` is creating a local scope `g`.

- The second `g` is creating a second local scope `g` but the first one has already gone out of scope and disappeared.

So the only invalid declaration is the third f.

There is a third type of scope which is where static variables are declared - these are variables that are shared between every instance of a class.

There are a number of names for the types, some of the most common are Local Variables, Instance Variables (also known as Fields) and Class Variables (also known as Static Fields). You also have method parameters but that's just a different way of getting a Local Variable.

For further reading:

- http://www.java-made-easy.com/variable-scope.html

- http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

- http://www.cs.berkeley.edu/~jrs/4/lec/08

Problem

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!

Original source