A program statement in a sequential structure can only be executed once. If you want to perform the same operation multiple times, you need to use a loop structure.
There are three main looping constructs in Java:
- while loop
- do...while loop
- for loop
An enhanced for loop mainly for arrays was introduced in Java 5.
while loop
while is the most basic loop, its structure is:
while(boolean expression) { //loop content }
public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } }
do…while loop
For a while statement, if the condition is not met, the loop cannot be entered. But sometimes we need to execute at least once even if the condition is not met.
A do…while loop is similar to a while loop, except that the do…while loop executes at least once.
public class Test { public static void main(String args[]){ int x = 10; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } }
for loop
While all looping constructs can be represented as while or do...while, Java provides another statement, the for loop, that makes some looping constructs simpler.
public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } }