on Leave a Comment

Java for-each Loop | Enhanced for Loop

Java for-each loop is also known as enhanced for loop. This feature introduced with the J2SE 5.0 release. Java for-each loop is used to retrieve elements of array efficiently. This loop iterates through each element of array, so it is called for-each loop. Java for-each loop is also starts with for keyword.

Syntax of Java for each Loop

for(type identifier : array | collection)
{
  //Statements
}

Here, type represents data type, identifier represents the variable name and array represents the array name. There is not need to declare and initialize a loop counter variable in for-each loop. In for-each loop, we declare a variable that is same as base type variable.

Example of Java for Loop

class JavaForLoop
{
 public static void main(String[] args) {
  char[] ch = {'J', 'A', 'V', 'A'};
  for(int i = 0; i<ch.length; i++)
  {
   System.out.println(ch[i]);
  }
 }
}

Output:

J
A
V
A

Same Task Using Java for-each Loop

class JavaForLoop
{
 public static void main(String[] args) {
  char[] ch = {'J', 'A', 'V', 'A'};
  for(char c : ch)
  {
   System.out.println(c);
  }
 }
}

Output:

J
A
V
A

Limitations of Java for-each loop

For compatible use of for-each loop, you have at least Java 5.

We can't sort an array using for-each loop because it has only single element access.

For-each loop only iterates forward over the array in single steps.

It can't compare two arrays. 



0 comments:

Post a Comment