Enhanced for Loop for Arrays

Overview of Enhanced For Loop for Arrays

  • The enhanced for loop, also known as the for-each loop, is used to traverse array or collections in Java.
  • It is simpler and more readable compared to the classic for loop.
  • The enhanced for loop automatically iterates over each element of an array/collection without using an index.

Syntax and Usage

  • The syntax for enhanced for loop is: for (dataType item : arrayName) { // code block to be executed }.
  • In the syntax dataType is the type of elements in the array, item is a variable that takes each value from the array during each iteration and arrayName is the array to be traversed.
  • The { // code block to be executed } is where you put the code that should be executed for each element in the array.

Working with Enhanced For Loop

  • The enhanced for loop is best used when you want to go through all the elements in an array, but not necessarily need to know the index of the element.
  • The enhanced for loop does not support operations like modifying array elements, or getting the current index of the array.
  • Be aware that changing the value of the iteration variable (item in the example) doesn’t actually modify the array elements.

Example using Enhanced For Loop

  • Sample usage of enhanced for loop is given below:
      int[] arr = {1, 2, 3, 4, 5};
      for(int i : arr) {
          System.out.println(i);
      }
    
  • In this example, the enhanced for loop iterates over each element in the arr array, with the variable i taking on each value in turn. The value is then printed to the console.

By using these revision notes, you can increase your understanding of enhanced for loops and how to use them with arrays in Java.