For Loop in Java
The for
loop in Java is the loop that is typically most used in programming. For loops are great when we know how many times we want the loop to execute. For example when looping through an entire array, we can use the array's size to tell us how many times to loop.
For Loop Concepts
As with the while and do-while loops, for
loops consist of the same structure, just written in a different syntax. In a for
loop, we write the initialization, terminating condition, and update all on one line. Here's an example of printing the word "Hello" 3 times.
for (int i = 0; i < 3; i++) {System.out.println("Hello");}
We can see that the variable i
is initialized with a value of 0. Then i
is evaluated by the terminating condition to see whether we should execute the loop body. After the loop body runs, then the update where we increase the value of i
by 1 is executed.
Array Example
Consider this example of printing all the items in an array:
int[] items = new int[]{ 1, 2, 3, 4, 5 };for (int i = 0; i < items.length; i++) {System.out.println(items[i]);}
Since we know that the number of times the loop should execute is the amount of items in the array, the for
loop is useful.
Why Use a For Loop Over a While or Do-While Loop?
In the while
and do-while
loop, we have to create an initialization variable before the loop block. This means if we have multiple while
or do-while
loops, we may end up reusing the initialization variable, which could make the code harder to read. With for
loops, once the loop is done executing we no longer have access to the initialization variable. This means we can redeclare an initialization variable with the same name if we were to have multiple for
loops in a function.
In a while
loop, we can access the counter
variable still when the loop is done executing:
int counter = 0;while (counter < 3) {System.out.println("Hello");counter++;}System.out.println(counter);
Same for a do-while
loop:
int counter = 0;do {System.out.println("Hello");counter++;} while (counter < 3);System.out.println(counter);
However, outside a for
loop, we do not have access to the variable outside the loop block:
for (int counter = 0; counter < 3; counter++) {System.out.println("Hello");}// Will cause an error!System.out.println(counter);
The advantage of this is that the initialization variable is only accessible within the for
loop body and cannot be called outside it. This makes the code easier to read and prevent bugs that can happen when we try to reuse initialization variables as with the while
and do-while
loops.
Conclusion
The for
loop is very handy and an important concept to learn in programming languages as they are probably the most common loop you will write.