Sebastian Gruia Sebastian Gruia -3 years ago 29
Java Question

Scope of a variable declared inside a for- loop

In the example below, variable

count
is ignored by java if it's declared inside the
for
loop. If it is declared inside the method
isPrime()
instead, everything goes well.

I don't understand why?

Here is my code.

public class Interest {

public static void main(String[] args) {

isPrime();

}

static void isPrime() {

int count = 0;
for (int i = 1; i <= 50; i++) {

if (i % 2 != 0) {
count++;
System.out.println("The number is: " + i);
System.out.println("We have: " + count + " prime numbers");
if (count == 10) {
System.out.println("The loop is ending");
break;
}

}

}

}
}

Answer Source

It is how java works. If you declare a variable in a block then that block is the scope of the variable.

Quoting from Java docs

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

A for implies a scope, so the scope of count is restricted to that block (it means it is a local block variable).

Moreover, you see it as java looks like it is ignoring any update on count because at each iteration the variable gets re-initialized. You can see it a little better printing count at the start and at the end of each iteration.

for (int i = 1; i <= 50; i++) {
     int count = 0;
      System.out.println("Begin " + count );
      if (i % 2 != 0) 
         count++;
     System.out.println("End " + count );
}

Produces:

Begin 0
End   1
Begin 0
End   0
Begin 0
End   1
Begin 0
End   0
Begin 0
End   1
Begin 0
End   0
Begin 0
End   1
Begin 0
End   0
Begin 0
End   1
....

This tells you that whatever update on count is lost as soon the control of the function reaches the end of the for block. That is why if you want to keep information across iterations you have to use a variable declared in some outer scope (in this case the scope of the function isPrime() works just fine).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download