Can a for statement loop infinitely in java?

Java 8Object Oriented ProgrammingProgramming

Using loops in programming languages we can execute a set of statements repeatedly. Java provides various loops namely while loop, for loop and the do while loop.

The for statement contains an initialization statement, a condition and, an increment or decrement operation.

  • Initializing statement − The initialization determines the starting value of the loop.
  • Condition − The condition in for loop is a statement returning a boolean value. This condition determines the exit value of the loop. It is executed before the statements of the loop.
  • Increment and decrement − Using this the loop will be incremented or decremented to the next value.

After initializing the value of the loop the condition of the loop is verified if it results true the statements in the loop are executed and then the loop is incremented or decremented to the next value according to the statement.

Example

 Live Demo

public class ForLoopExample {
   public static void main(String args[]) {
      //Printing the numbers 1 to 50
      for(int i = 1; i<=50; i++) {
         System.out.print(" "+i);
      }
      System.out.println(" ");
      //Printing the numbers 100 to 50
      for(int i = 100; i>50; i--) {
         System.out.print(" "+i);
      }
   }
}

Output

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51

infinite for loop

Example

You can run a for loop infinitely by writing it without any exit condition.

public class ForLoopExample {
   public static void main(String args[]) {
      //Printing the numbers 1 to
      for(int i = 1; ; i++) {
         System.out.print(" "+i);
      }
   }
}

Output

On executing, this program prints the values infinitely starting from 1.

You can also print infinite numbers starting from 1 by defining the for loop without initializing statement, condition or increment/decrement operation as −

public class ForLoopExample {
   public static void main(String args[]) {
      for(; ;) {
         System.out.print(" "+i);
      }
   }
}
raja
Published on 08-Jul-2019 13:16:31
Advertisements