Iteration Statements

Java’s iteration statements are for, while, and do-while. These statements create what we commonly call loops.
Java iterative statements are of following types:

1. while loop

In The while loop condition is evaluated once at the beginning of the loop and again before each further iteration of the statement. Example :

public class WhileExample {
	public static void main(String[] args) {
		int counter = 1;
		while (counter < 4) {
			System.out.println("counter " + counter);
			counter++; // increnent counter 

2. do-while loop

In while loop, condition is checked at beginning, and if the condition turns out to be false, the further statements will not be executed. But in do-while the condition is executed at least once if the condition return out to be false.

public class doWhileExample {
	public static void main(String[] args) {
		int a = 20;

3. for loop

In for loop variable will be initialized, checked, and incremented or decremented in one single line. For loop comes with two flavours
1. basic For loop
2. foreach loop

1. basic for loop
Example :

public class BasicFor {
	public static void main(String[] args) {
		for (int a = 10; a < 10; a--)
			// initialization, checking, decrement in one statement
			System.out.println("a is " + a);

2. foreach
with for loop we have to initialize variable to a start index and check with that to end value and increment/decrement as well manually. To overcome this foreach loop may be used, which will handle all these issues by itself. Foreach is specially used in iterating arrays, Collection etc. Example as :

public class ForEach {
	public static void main(String[] args) {
		int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		for (int a : arr1)
			// a is initial element that is used to fetch values of arra one by
			// one, arr1 is enough for check purpose, the loop will
			// automatically check the ending value
			System.out.print(a); // a is used to print, because a fetch each
									// element from arr1

You may also like...