Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variable scope and for loop

Tags:

java

I just have started to learn Java. I have some dummy question. I don't really get why in this situation:

int j = 5;
for (int j = 0; j < 10; j++) {
   // do sth
}

my compiler says : the variable j is already defined in the scope.
Why this second j is a problem ? I thought that it should simply shadow the first one.

like image 318
Adrian Baran Avatar asked Dec 07 '22 06:12

Adrian Baran


2 Answers

The problem is that you're declaring the variable j twice: One out of the for loop and one inside. Just delete the line above the for and you'll be good to go.

Local variables aren't shadowed - perhaps you had fields in mind (but that's something different from what you have here).

like image 109
Theodoros Chatzigiannakis Avatar answered Dec 14 '22 23:12

Theodoros Chatzigiannakis


A simpler yet similar scenario is:

int i = 0;
{
   int i = 2;
}

So you have two i variables. Which one do you mean when you reference i ?

The Java compiler doesn't allow 'shadowing' here. The definitions are ambiguous, and the compiler is working to warn you of this.

like image 27
Brian Agnew Avatar answered Dec 14 '22 23:12

Brian Agnew