In this tutorial, we will learn how to use for loop in Java with the help of examples and we will also learn about the working of Loop in computer programming.
The Java for loop is a control flow statement that iterates a part of the programs multiple times.
If the number of iteration is fixed, it is recommended to use for loop.
for( init ; condition ; incr/decr )
{
// code to be executed
}
//for loop
for(int i=1 ; i<=5 ; i++)
{
System.out.println("Thanks for using CODEMISTIC!");
}
Output :
Thanks for using CODEMISTIC!
Thanks for using CODEMISTIC!
Thanks for using CODEMISTIC!
Thanks for using CODEMISTIC!
Thanks for using CODEMISTIC!
Explanation :
In the above example, we have :
int i = 1
Here, initially, the value of i is 1. So the test expression evaluates to true
for the first time. Hence, the print statement is executed. Now the update expression is evaluated.
Each time the update expression is evaluated, the value of i is increased by 1. Again, the test expression is evaluated. And, the same process is repeated.
This process goes on until i is 6. When i is 6, the test expression (i <= 5
) is false and the for loop terminates.
One of the most common mistakes while implementing any sort of looping is that that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason.
for( ; ; )
{
// code to be executed
}
//Java program to illustrate various pitfalls.
public class LooppitfallsDemo
{
public static void main(String[] args)
{
// infinite loop because condition is not apt
// condition should have been i>0.
for (int i = 5; i != 0; i -= 2)
{
System.out.println(i);
}
}
}