Thursday , January 18 2018
Home / Java Programming / Enhanced for Statement

Enhanced for Statement

Enhanced for statement:

Enhanced for statement or enhanced for loop is a short form of a simple for loop (Counter Controlled Loop) used in Java Language.

We know that the simple for loop’s syntax is

for (var_initialization ; continuation_condition ; increment/decrement)

It has three parts initialization, condition and inc/dec operator.

e.g.

for (int counter=0 ; counter < 10 ; counter++)

If there is an integer array named arr with 5 elements

int[ ]  arr = {10,20,30,40,50} ; 

then by using simple for loop, we can iterate all the array elements like this

for(counter = 0 ; counter < arr.length ; counter++)
System.out.print(arr[counter]);

BUT

The enhanced for statement can iterate through the elements of an array without using a
counter. The syntax of enhanced for statement is:

for ( parameter : arrayName )
     statement

It has only two parts, parameter and an arrayName.

where parameter is just like the first part of simple for loop but without initialization. That is ‘parameter’ has a data type and an identifier  (e.g., int number), and arrayName is the array which we want to iterate through. The type of ‘parameter’ and type of array elements should consistent with each other.

Thus there are at least two advantages of using the enhanced for statement:

  • lesser syntax
  • avoiding the possibility of stepping outside the boundary of array indices.

Above example written using simple for statement can be expressed using enhanced for statement is:

for(int number : arr)
     System.out.println ( number ) ;

Hence the enhanced for statement gives us a simplified version of for loop to iterate through an array.

Disadvantages of Enhanced For Loop / Statement:

The enhanced for loop can be used only to obtain array elements. It cannot
be used to modify elements. If your program needs to modify the array elements, the you have to use the traditional counter-controlled for statement.

(Visited 38 times, 1 visits today)

Check Also

How to parse string in java?

How to parse string in java? Usually in natural language processing, a text is parsed. …

One comment

  1. Muhammad Arslan Anjum

    Thanks Sir for your Good/Hard working….. Dear sir your so hard worker……