Java Reference
In-Depth Information
keep track of the square of the
for
loop control variable. This code works fine, but
consider this variation:
for (int i = 1; i <= 5; i++) {
int squared = i * i;
System.out.println(i + " squared = " + squared);
}
System.out.println("Last square = " + squared); // illegal
This code generates a compiler error. The variable
squared
is declared inside the
for
loop. In other words, the curly braces that contain it are the curly braces for the
loop. It can't be used outside this scope, so when you attempt to refer to it outside the
loop, you'll get a compiler error.
If for some reason you need to write code like this that accesses the variable after
the loop, you have to declare the variable in the outer scope before the loop:
int squared = 0; // declaration is now in outer scope
for (int i = 1; i <= 5; i++) {
squared = i * i; // change this to an assignment statement
System.out.println(i + " squared = " + squared);
}
System.out.println("Last square = " + squared); // now legal
There are a few special cases for scope, and the
for
loop is one of them. When a
variable is declared in the initialization part of a
for
loop, its scope is just the
for
loop itself (the three parts in the
for
loop header and the statements controlled by the
for
loop). That means you can use the same variable name in multiple
for
loops:
for (int i = 1; i <= 10; i++) {
System.out.println(i + " squared = " + (i * i));
}
for (int i = 1; i <= 10; i++) {
System.out.println(i + " cubed = " + (i * i * i));
}
The variable
i
is declared twice in the preceding code, but because the scope of
each variable is just the
for
loop in which it is declared, this isn't a problem. (It's
like having two dorm rooms, each with its own refrigerator.) Of course, you can't do
this with nested
for
loops. The following code, for example, will not compile:
for (int i = 1; i <= 5; i++) {
for (int i = 1; i <= 10; i++) { // illegal
System.out.println("hi there.");
}
}
Search WWH ::
Custom Search