Java programming language provides the following types of loop to handle looping requirements.Click on the following links to check the detail.
While Loop:
Syntax for while loop:
while(Boolean_expression) { //Statements }
e.g:
public class While{ public static void main(String[] args) { int x=10; while(x<20) { System.out.print("value of x: "+x); x++; System.out.print("\n"); } } }
output:
value of x: 10 value of x: 11 value of x: 12 value of x: 13 value of x: 14 value of x: 15 value of x: 16 value of x: 17 value of x: 18 value of x: 19
For Loop:
Syntax for for loop is:
for(iitialization;Boolean_expression;update)
{
//statements
}
the update statement can be left blank with a semicolon at the end.
example :
public class For { public static void main(String[] args) { for(int x=10;x<20;x=x+1){ System.out.print("Value of x is: "+x); System.out.print("\n"); } } }
out:
Value of x is: 10 Value of x is: 11 Value of x is: 12 Value of x is: 13 Value of x is: 14 Value of x is: 15 Value of x is: 16 Value of x is: 17 Value of x is: 18 Value of x is: 19
do..while loop:
do{
//Statements
}while(boolean_expression)
e.g:
public class DoWhile { public static void main(String[] args) { int a=10; do{ System.out.print("Value of a :"+a); a++; System.out.print("\n"); }while(a<20); } }
output:
Value of a :10 Value of a :11 Value of a :12 Value of a :13 Value of a :14 Value of a :15 Value of a :16 Value of a :17 Value of a :18 Value of a :19
Loop Control Statements:
break statements:
example:
public class Break { public static void main(String[] args) { int[] numbers={10,20,30,40,50,60}; for(int x:numbers){ if(x==40){ break; } System.out.print(x); System.out.print("\n"); } } }
output:
10 20 30
continue statements:
– In a for loop, the continue keyword causes control to immediately jump to the update statement.
– In a while loop or do-while loop, control immediately jumps to the boolean expression.
public class Continue { public static void main(String[] args) { int[] numbers={10,20,30,40,50,60}; for(int x:numbers) { if(x==30) { continue; } System.out.print(x); System.out.print("\n"); } } }
output:
10 20 40 50 60
Enhanced for loop in Java:
it included from Java 5, the enhanced for loop was introduced.This is mainly used to traverse collection of elements including arrays.
Syntax:
for(declaration:expression) { //statements }
Declaration: The newly declared block variable, which is a type compatible with the elements of the array you are accessing.
Expression: This evaluates to the array you need to loop through.The expression can be an array variable or method call that returns an array.
e.g:
public class Enhanced { public static void main(String[] args) { int[] numbers={10,20,30,40,50}; for(int x:numbers) { System.out.println( x ); System.out.println(","); } System.out.println("\n"); String[] names={"James","Larry","Tom","Lacy"}; for(String nameu:names) { System.out.println(nameu); System.out.println(","); } } }
output:
10 , 20 , 30 , 40 , 50 , James , Larry , Tom , Lacy ,