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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With