+ 2
What is enhanced for loop?
2 Antworten
+ 2
It is used to traverse an array like-
for (declaration : expression){
// statement
}
As it is very useful to do the same thing without calling the count variable.
For example
public class Program {
public static void main(String[] args) {
int[ ] primes = {2, 3, 5, 7};
for (int t: primes) {
System.out.println(t);
}
}
}
+ 2
This means you have to use a regular For loop for getting each object in the array so it takes time to give an index and get each object one by one.
But with enhanced type it will use each object in array by itself and you don't need to define it.
e.g.
int[] arr={1,2,3};
for (x=0;x <arr.length;x++) {
System.out.println(arr[x]); }
instead
int[] arr={1,2,3};
for (int t: arr) {
System.out.println(t); }