Java Reference
In-Depth Information
The Scope of for Loop Variables
Any variables declared in the initialization step are local variables in the for loop and go
out of scope when the loop fi nishes. For example, the following code attempts to display
k after it goes out of scope:
for(int k = 10; k >= 1; k--) {
System.out.print(k);
}
System.out.print(k);
The following compiler error occurs:
For.java:19: cannot find symbol
symbol : variable k
location: class For
System.out.println(k);
^
Watch for a question that tests your knowledge of this subject. By the way, if you need
to use k outside the loop, declare it outside the loop. For example, the following code is
valid:
int k = 10;
for(k = 10; k >= 1; k--) {
System.out.print(k);
}
System.out.print(k);
The output of this code is
109876543210
There will be questions on the SCJP exam that test your knowledge of the syntax
and behavior of basic for statements. The exam seems to favor nested for statements,
something along the lines of the following example:
4. for(char one = 'a'; one <= 'f'; one++) {
5. for(int i = 1; i <= 3; i++) {
6. System.out.print(“ “ + one + i);
7. }
8. System.out.println();
9. }
Search WWH ::




Custom Search