You are here

Java for loop

Java for loop is used to repeat execution of the statement(s) until a certain condition holds true. for is a keyword in Java programming language.

Java for loop syntax

  1. for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) {
  2.   // Statements to execute, i.e., Body of a for loop
  3. }

You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement. Please note that all three components of a for loop are optional. For example, following for loop prints "Java programming" indefinitely.

  1. // Infinite for loop
  2. for ( ; ; ) {
  3.   System.out.println("Java programming");
  4. }

You can terminate an infinite loop by pressing Ctrl+C.

Simple for loop example in Java

Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.

  1. //Java for loop program
  2. class ForLoop {
  3.   public static void main(String[] args) {
  4.     int c;
  5.    
  6.     for (c = 1; c <= 10; c++) {
  7.       System.out.println(c);
  8.     }
  9.   }
  10. }

Output of program:
Java for loop example program output

Java for loop example to print stars in console

Following star pattern is printed
*
**
***
****
*****

  1. class Stars {
  2.   public static void main(String[] args) {
  3.     int row, numberOfStars;
  4.    
  5.     for (row = 1; row <= 10; row++) {
  6.       for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {
  7.         System.out.print("*");
  8.       }
  9.       System.out.println(); // Go to next line
  10.     }
  11.   }
  12. }

This program uses nested for loops i.e. for loop inside a for loop to print the pattern of stars. You can also use spaces to create another pattern, it is left for you as an exercise.

Output of program:
Java for loop example program output