For Loop
The for loop looks like this:
Example:
for (init expression; condition expression; increment expression)
{
// statements here
}
The init condition marking the start of a for loop will run only once. Conditional expression will be checked each time before entering the loop. It is used for testing the exit condition for a loop and must return a boolean value. Once the condition is true, the statements in the loop are executed; thereafter the increment expression will be executed to modify the values of counter or other variables for next iteration.
Example:
Write the following code in the /home/labex/project/forTest.java file:
public class forTest
{
public static void main(String[] args)
{
// for loop begins when x=1 till x<=3
for (int x = 1; x <= 3; x++) {
System.out.println("x = " + x);
}
}
}
Output:
Run the forTest.java file using the following commands:
javac /home/labex/project/forTest.java
java forTest
See the output:
x = 1
x = 2
x = 3
You can exit the loop whenever you want in the loop body by using code like continue or break in an if block of statements. break will exit the whole loop while continue will only quit the current iteration and perform the next iteration (if the condition is true).
Example:
Write the following code in the /home/labex/project/loopTest.java file:
public class loopTest
{
public static void main(String[] args)
{
// for loop begins when x=1 till x<=3
for (int x = 1; x <= 3; x++) {
if(x==2){
// exit the whole loop
break;
// continue will only quit the current iteration, and do next iteration
// you can delete the break expression and use continue. See the output.
// continue;
}
System.out.println("x = " + x);
}
}
}
Output:
Run the loopTest.java file using the following commands:
javac /home/labex/project/loopTest.java
java loopTest
See the output:
x = 1