Articles → Java → Loops In Java

Loops In Java






What Are Loops?




  1. A structure, series, or process, the end of which is connected to the beginning.
  2. A shape produced by a curve that bends round and crosses itself.



For Loop





Syntax


for (initialize counter; test counter; increment counter) {
  code to be executed;
}



Example


class MainClass {
  public static void main(String args[]) {
    for (int i = 0; i < 10; i++) {
      System.out.println(i);
    }
  }
}



Output




Picture showing the output of the for loop in Java
Click to Enlarge


While Loop





Syntax


while (condition) {
  // code block
}



Example


package com.TestProject;

public class TestClass {
  public static void main(String[] args) {
    int i = 0;
    while (i != 5) {
      System.out.println(i);
      i++;
    }
  }
}



Output


Picture showing the output of the while loop in Java
Click to Enlarge


Do While Loop





Syntax


do {
  // Code block that will be executed atleast once

} while (condition);



Example



public class TestClass {

  public static void main(String[] args) {

    int i = 0;
    do {
      // Code block that will be executed atleast once
      System.out.println(i);

    } while (i != 0);
  }
}



Output


Picture showing the output of the do while loop in Java
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, December 1, 2016
 
Updated On  -  Thursday, September 7, 2017

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250