Posts Tagged tutorial 9
Java Tutorial 10 – Enhanced For Loops
enhanced for loops are very useful for arrays.
to loop through array what we generally do is we take one int as index and use this index inside loop to point to array location and then we increment it.
But there is one more easiest way to loop through array which is called Enhanced For Loop. it automatically increments index and stops at the end of the array. let me show you one example:
For loop:
public class fruit {
public static void main(String[] args) {
String fruift[] = {“apple”, “banana”, “grapes”};
int i;
for (i = 0; i < 3; i++) {
System.out.println(fruift[i]);
}
}
}
Enhanced For Loop:
public class fruit {
public static void main(String[] args) {
String fruift[] = {“apple”, “banana”, “grapes”};
for (String i : fruift) {
System.out.println(i);
}
}
}
You can see the difference between lines of code.
it is pretty much easy to use each element of array and loop through it.
Syntax:
for( <type of array> <variable> : <array name> )
for example u have array of int and you want to loop through each 1 then u have to write.
for( int x : numbers ){
….things to do….
}
here “numbers” is array of ints. int x holds the value of array elements.
Example.
int num[] = { 4, 34, 12, 7, 56, 89}
for( int x : num){
}
when first time it loops x holds value “4”.
then in second loop value of x will be “34” and so on…
It’s very useful to loop through all elements of array.
So, it’s all about enhanced for loop.
Have a nice day, Peace.