In this section we will learn what the for loop is and how to use it in Java.
What is for loop in Java?
When we want to repeat the execution of a block of code for number of times like 10, 100 or 1000 etc. times we use the for loop.
The for loop statement is mostly used for repeating the execution of a block of codes for a number of times.
We say ‘mostly’, because it is possible to run a for loop for infinite times (as long as the OS doesn’t shut it down).
Java for Loop Syntax
Here’s the structure of the for loop:
for (initialization_statement ; condition_statement ; update_statement) {
// the instructions within the body of 'for' loop
}
for: A for loop starts with the keyword for.
( ): In for loops there are three statements which two of them are optional. These statements can be set in the parentheses that comes after the for keyword.
In short these statements are for:
- Declaring and initializing a variable (Optional).
- Set a condition.
- Update the variable that was created in the first statement (Optional).
initialization_statements: within a loop there’s a condition in which either a true or false will come out of that condition. For example let’s say we have a variable named counter and its value is 0. The condition in the loop could be to check and see if the value of the counter is equal to 10. Keeping aside the condition for now, the variable and its value is a necessary part for the loop to run properly.
We could either create this variable outside of the loop or we have this option of creating the variable right in the first statement initialization_statement which is actually the purpose of this statement.
Note: the first statement will only run once and that is the time when the loop starts.
condition_statemnet: This is where we set the condition statement and every time the loop is repeated, this condition is checked and if the result is true then the body of the loop will repeat itself otherwise the loop will break.
Note: in condition_statement we can use comparison and logical operators to create complex conditions.
update_statement: the last statement within the parentheses ( ) is used to update the variable that is used in the condition_statement.
For example if there’s a variable named counter and it is used in the condition statement like counter < 10; then we can use the third statement to increase the value of the counter variable by some.
Note: the last statement will run every time the for-loop is repeated.
;: the statements mentioned before are separated from each other via semicolon ;.
{ }: The body of the for loop is within the pair of braces that comes after the parentheses ( ).
Here’s the order of execution in a for loop:
- Initialization statement.
- Condition statement.
- The body of the for loop.
- Update statement.
After the first 4 steps, the steps from 2 to 4 will be repeated for as long as the condition –statement results true.
Example: using the for loop in Java
Example: using the for loop in Java
public class Simple { public static void main(String[] args) { for (int i = 0; i<10; i++){ System.out.print(i+", "); } } }
Output:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
How does for loop work?
In this example, the first step is to declare and initialize the variable i.
Then the condition which is i<10 will be checked and because the result of this condition is true, the next step is to run the body of the loop.
Within the body of the loop, the value assigned to the i variable is sent to the output.
The next step is the update-statement which for this example is to increase the value of the i variable by one.
This process is repeated for 10 times and after that the condition-statement (i<10) will result false and the loop breaks at this point so the instructions after the loop will be run then.
Java infinite for loop
As mentioned at the beginning of this section, we can run an infinite loop via for loop as well.
Here’s how to do so:
Example: infinite loop in Java
public class Simple { public static void main(String[] args) { int i = 0; for (; true; ) { i++; System.out.print(i+", "); if (i == 20) { break; } } } }
Output:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
As we know, the initialization-statement and update-statement are optional and they can be skipped. (Just like the way we did in this example).
Within the condition-statement of the loop, we used the value true which is used as the result of the condition and so because no-matter how many times we repeat this loop the value of the condition won’t change, we need to use either break or return statement to end the loop at some point in the future.
For this particular example, we used the if-statement to check the value of the i variable at each round and finally when the value reached to 20, break the loop via the break keyword.
Java Nested for Loop
Using a for loop within the body of another for loop is called nested for loop.
One reason that we might want to use nested for loop is when we’re working on multidimensional arrays and want iterate through the entire elements of the sub-arrays! Note: you’ll learn more about for loop and multidimensional arrays in later sections.
Example: creating nested for loop in Java
class Main{ public static void main(String[] args) { int multi[][] = { {1,2,3,4,5}, {6,7,8,9,10} }; for (int i = 0 ; i<multi.length; i++){ for (int b = 0; b<multi[i].length; b++){ System.out.print(multi[i][b]); } } } }
Output:
12345678910
Java for Loop vs While Loop
Both for loop and while loop are capable of running a block of code for x number of times, but the design of for loop is more focused towards creating loops that should run for a specific number of times. On the other hand, the while loop is designed to run a block of code as long as a condition is met! So the number is not of the focus when using the while loop.
Note: remember, both while and for loop still are capable of doing the same tasks, but their main difference is in the design purpose.