·  JAVA – Syntax – Conditional Statements – for

 

- Info:

  - This tutorial shows how to use conditional statement "for" which has following structure:

    for (initialize parameters;execute body if these conditions are true;execute after each iteration)

    { body with statements }

  - Use break statement to exit "for loop".

  - Use continue statement to skip te rest of the body and continue from the begining of "for loop".

 

- Procedure:

  - Create JAVA Console Application Test.java

 

    Test.java

    public class Test {

      

      public static void main (String arg[]) throws Exception {

   

        //SIMPLE.   Output is "1 2 3 4".

        for(int i=1;i<=4;i++){

          System.out.println(i);

        }

   

        //COMPLEX.  Output is "1 2 3".

        for(int i=1, j=5 ; i<=4 && j>2 ; i++,j--){

          System.out.println(i);

        }

      

        //BREAK.    Output is "1 2 3" since we break out of for loop before condition i<4 is reached.

        for(int i=1;i<=4;i++) {  

          System.out.println(i);

          if(i==3) { break; }

        }

   

        //CONTINUE. Output is "1 2 4" since display of number 3 is skipped.

        for(int i=1;i<=4;i++) {

          if(i==3) { continue; };

          System.out.println(i);

        }

 

      }

      

    }