• Post Reply Bookmark Topic Watch Topic
  • New Topic

Redeclaration  RSS feed

 
Mandy Singh
Greenhorn
Posts: 23
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey folks,

Why is this not a redeclaration:


As far as I know, Integer "i" shall be available till we don't exit the for loop. This line shall be executed again and again in the loop:

So, isint this a re-declaration ?

 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The declaration has a scope restricted to the loop. So when you go back to the beginning of the loop, the variable goes out of scope. Which means it doesn't exist by the time the declaration is reached again, so there's no conflict.

In a similar way, if you've got a variable declared in a method you don't get a redeclaration error every time the method is called.

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the i your using for the loop is a local variable, that will not compile. If it does compile that means that i is not a local variable but a field instead. In that case, you're hiding / shadowing the field inside the loop.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!