2

This is the text I read in a computer science book from my college regarding scopes and variable declarations in Java:

The compiler will generate an error for this code:

int i=3;
        while (...) {
            int i=1;
... }

The first declaration of i is still in effect within the while loop, yielding overlapping scopes.

The clause that I am questioning is this "yielding overlapping scopes". The scopes are overlapping yes, but the problem is that there are overlapping variable declarations in overlapping scopes. The overlapping scopes isn't the problem per se right?

azurefrog
  • 10,785
  • 7
  • 42
  • 56
Jwan622
  • 11,015
  • 21
  • 88
  • 181
  • Correct, the problem is actually that the variable declarations overlap as a result of the overlapping scopes. – EkcenierK Dec 28 '15 at 22:23
  • It could be clearer as "...yielding overlapping scopes **of the variables**", but as there are no other "scopes", this should already be clear. – Marco13 Dec 28 '15 at 22:29

2 Answers2

1

It's a little bit more tricky than that because it depends on where the variable is declared. For example, if both is are declared inside of the same method, that should be an illegal operation. You can't shadow another variable declared in the same scope.

question about variable scope and shadowing in java

If the first i is declared as say a field on the class (which is a separate scope), then the internal declaration can shadow the external one. This isn't the best precedence because it can lead to developer error (where she thinks she is setting the field but is only setting the local variable) but it's not strictly illegal from a compiler perspective.

Community
  • 1
  • 1
dolan
  • 1,716
  • 11
  • 22
1

That this is wrong:

/* Here an earlier i is visible. */
int i; /* Compiler error, */

is a deliberate design decision to prevent declaration-hiding errors.

  1. You are allowed to hide a field declaration inside a method/constructor/initializer block. The original field is accessible through this.i.
  2. (Special case) for (int i; i < n; ++i) { ... } limits the scope of i to the for-statement only.
  3. (Special case) the same for parameter declarations, exception catches and lambdas.

The error occurs inside the same or nested scope { ... }.

"Overlapping" is an unfortunate term, as scopes can only nest/surround within each other. A declared variable name is visible in its entire scope, and a subsequent declaration of the same name where the old declaration's name is visible, is illegal, a conflict.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138