What are loops in Java

A loop is required to run set of statement(s) repeatedly, for certain number of times.

There are three loops in Java. They are
1. for loop
2. while loop
3. do while loop

How to use for loop in Java

Below is syntax of for loop

	//program statements

In initialization single or multiple variables(separated by comma) can be declared or initialized.
Initialization part gets executed only once when execution of for loop starts.
Condition can be simple condition(using relational operators) or complex condition(having relational and logical operators),
Condition part executes once, before starting execution of each iteration.Iteration is continued only if the condition part evaluates to true, else execution comes out of the for loop.
Expression part executes once, after each iteration. Expression part can have multiple statements separated by comma.

Below are few valid for statements

for(int i=0;i<10;i++)

for(int i=0,j=10;(i<10)&&(j>0);i++,j--)

//infinite for loop

There may be other logic problems which may end up with infinite for loop, as shown below
for(int i=0;i>0;i++)//infinite for loop

Below for loop is syntactically right, but logically may not produce expected output

int i;
for(i=0;i<20;i++);//here ; does not give compile error

Nested for loops Examples

Program to print Fibonacci numbers
sorting example
How to calculate factorial in Java?
print a pattern using for loop

what is for-each loop in Java

for-each has been added in Java version 5. It provides better readable syntax to iterate through individual elements in Array or in any Collection. Below is an example of for-each

class TestForEach{
  public static void main(String args[]){
   float arr[] = {14.5f,61.23f,43.5f,34.4f,12.23f};

   for(int item:arr){

Difference between while and for loop

Both for and while loops are used to run set of statements repeatedly.
But they are different, in syntax.

for loop syntax is much cleaner, compared to while loop. initialization, condition and change of values in expression, appear at one place, hence code using for loop is better readable and maintainable.

Another difference is for loop lets to declare variables, which can be used only within for block. But its not possible to declare variables in while statement.

Difference between while and do while loops

Basic difference between while and do while is
1.while loop iterates zero or more times, based on the condition
2.But do while loop iterates one or more times, based on the condition

You may also like to read:
How many keywords in Java?
Basic data types in Java