Concept
How are for loops structured and scoped in Java?
ComputerScienceOne / Do-While Loops
"For loops in Java use the familiar syntax of placing the initialization, continuation condition, and iteration on the same line as the keyword for. An example can be found in Code Sample 28.3.\n\nfor(int i=1; i<=10; i++) {\n\n//perform some action\n\n}\n\nCode Sample 28.3.: For Loop in Java\n\nSemicolons are placed at the end of the initialization and continuation condition, but not the iteration statement. Just as with while loops, the opening curly bracket is placed on the same line as the for keyword. Code within the loop body is indented, all at the same indentation level. Another observation: the declaration of the counter variable i was done in the initialization statement. This scopes the variable to the loop itself. The variable i is valid inside the loop body, but will be out-of-scope after the loop body. It is possible to declare the variable prior to the loop, but the variable i would have a much larger scope. It is best practice to limit the scope of variables only to where they are needed. Thus, we will write our loops as above."
Related Ideas
- How does Java use variables and collections in enhanced for loops?ComputerScienceOne · Enhanced For Loops
- How are for loops structured in PHP?ComputerScienceOne · For Loops
- How is a basic while loop structured in Java?ComputerScienceOne · While Loops
- How can you iterate over Java arrays?ComputerScienceOne · Basic Usage
- What are enhanced for loops in Java?ComputerScienceOne · Enhanced For Loops
- How can a for loop calculate the sum of numbers from 1 to 10?ComputerScienceOne · Nested Loops
- How do nested loops execute in Java?ComputerScienceOne · Nested Loops
- How do do-while loops differ from while loops in Java?ComputerScienceOne · For Loops