for, while, do while and for each loops in Java

In a programming language we have to repeat set of instruction many time as per programmer’s requirements.

To repeat instructions java provides looping statements. Looping is also known as Iterative statement
Following are types of loop in java.
1. For loop statement
2. While loop statement
3. Do while loop statement
4. For each loop (enhanced for loop)

Work of above statement are same but the have syntax difference. Let us see all of them one by one

1 For Loop in Java

for loop syntax in java

Example: Print 1 to 10 numbers using for loop in java

In for statement first loop variable is initialized then condition is checked if condition is true body of loop is executed after that variable is updated.   

Again condition is cheeked condition satisfied body of loop is executed and variable updated this process is continue until condition is false.

Variable initialization is done only once.

Output

2 While Loop in Java

while loop syntax in java

In while statement only condition is checked if condition is true then the body of loop is executed loop variable initialization should be before the while statement.

Variable updating is part of body of loop.

Example: Print 1 to 10 numbers using for loop in java

Output

3 do while in Java

do while loop syntax in java

In do loop condition is cheeked at last. First time body of loop is excuted without checking the condition after that if condition specified in while is true then body of loop is executed until condition is false.


Example: Print 1 to 10 numbers using for loop in java

Result

If condition is false then also do while statement is executed once.
Example: Executing do while loop once in false condition.

Result

Here condition in do while is false then also body of loop is executed once.

4 for each loop in java

For each loop is more readable and easier then for loop.

It is used to iterate over array and collection.

Syntax of for each loop in java

Difference between for and for each loop is that in for loop we can access index value but not in for each.

Example: Print all array elements using for each loop

Output

Example: Iterating a student object using for each loop.

Created a class student it contains a method getStudents() to get student list.

Class forEach1 call getStudents() and store its data in studentList.

then for each loop is used to iterate the student object.

Output

5 Examples on Loops

Example: Multiplication table program in java using while loop in Java

Output

Example: Sum of n natural numbers in java using for loop in java

Output

Example Java program to check whether a given number is prime or not

Output

Read more about prime numbers

Program: Program to find sum of digits in java