You are here

Java for loop

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

Java for loop syntax

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

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, the following for loop prints "Java programming" indefinitely.

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

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.

//Java for loop program
class ForLoop {
  public static void main(String[] args) {
    int c;
   
    for (c = 1; c <= 10; c++) {
      System.out.println(c);
    }
  }
}

Output of program:
Java for loop example program output

Java for loop example to print stars in console

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

class Stars {
  public static void main(String[] args) {
    int row, star;
   
    for (row = 1; row <= 10; row++) {
      for (star = 1; star <= row; star++) {
        System.out.print("*");
      }
      System.out.println(); // Go to next line
    }
  }
}

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

Output of program:
Java for loop example program output

Share this