Loops Structure in Java

In loops, programs run a set of instructions or functions multiple times until some condition is met. The conditions in the loop control the execution of the statements. If the condition is not met, loops are likely to execute infinite times.



Important points to remember in loops

Initialization – loops executes initialization once prior to code execution. initialization sets the initial value for the loop.
Condition – The condition decides to execution of the code. If the condition returns true, the loop will continue the next iteration round.
Expression – expression changes the state of the execution after the code block is executed.



Loops in Java

Java provides three ways to execute loops.

  • for loop
  • while loop
  • do..while loop


For loop in Java

For Loop is a simple form of looping structure. It allows to prove initialization, condition and expression in a single line. For loop is commonly used to execute block of codes for finite number of times.

package com.yawintutor;

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

Output

0
1
2
3
4


While loop in Java

while loop is another form of loops supported in java. while loop checks conditions and decides whether or not to execute the code block.

package com.yawintutor;

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

Output

0
1
2
3
4


Do while loop in Java

Do while loop executes a block of statements once, then checks the condition. If the condition is not met, then, skips from next execution.

package com.yawintutor;

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

Output

0
1
2
3
4



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *