Foreach Loop In JAVA
Java For-each or Enhanced For Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for a loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns elements one by one in the defined variable.
Syntax :
for(Type var:array){
//code to be executed
//syntax for foreach loop
}
Example Foreach Loop 1:
public class ForEachDemo
{
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4 };
for (int i : arr)
{
System.out.println(i);
}
}
}
OutPut
1
2
3
4
Example Foreach : (PROGRAM TO PRINT ARRAY VALUES WITH USER INPUT)
//PROGRAM TO PRINT ARRAY VALUES WITH SCANNER
import java.util.Scanner;
public class ForEachDemo
{
public static void main(String arng[]) {
int value[] = new int[5];
Scanner data = new Scanner(System.in);
float sum = 0;
System.out.println("Enter 5 element of array");
// Enhanced for loop
for (int i : value) {
i = data.nextInt();
sum = sum + i;
}
System.out.println("Sum is " +sum);
}
}
Output :
Enter 5 element of array
5
5
5
5
5
Sum is 25.0
Series:
Java Tutorials Hub
