Same Name used in Several Loops
Other for statements might use the same identifier (the same name)
in declaring
their loop control variable,
but each of these is a different variable which can be seen only by
its own loop.
Here is an example:
class sameName
{
public static void main ( String[] args )
{
int sumEven = 0;
int sumOdd = 0;
for ( int j = 0; j < 8; j=j+2 )
sumEven = sumEven + j;
System.out.println( "The sum of evens is: " + sumEven );
for ( int j = 1; j < 8; j=j+2 ) // a completely different variable,
sumOdd = sumOdd + j; // also named "j"
System.out.println( "The sum of odds is: " + sumOdd );
}
}
|
The two loops work correctly, and don't interfere with each other,
even though each one has its own variable named "j".
(It would be a good idea to copy-paste-compile-and-run this code.)
|