Articles → Java → Loops in Java

Loops in Java






What are loops?











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





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



Click to Enlarge


Do while loop





Syntax


do
{
	// Code block that will be executed atleast once
			
}while(condition);



Example


package com.TestProject;


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



Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, December 01, 2016
 
Updated On  -  Thursday, September 07, 2017

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250