Iterable interface in Java

The Iterable Interface is defined in java.lang package. The Iterable interface is the super interface in collection framework. It is the root interface for all the collection classes. The Collection interface extends the Iterable interfaceSo,all the subclasses that implementing the Collection interface also implement the Iterable interface.
Implementing this interface allows an object to be the target of the enhanced “for each” statement. The for-each loop is used for iterating the collections. The Iterable Interface is implemented in collections classes where iterations comes in handy.
It contains only one abstract method that returns the iterator.

Iterator <T> iterator();

where T represents the type of elements returned by the iterator.

The iterator can be used to iterate the elements of the object implementing the Iterable interface.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IterableEample {
  public static void main(String[] args) {
    List<String> objectNames = new ArrayList<>();
    objectNames.add("alpha");
    objectNames.add("beta");
    objectNames.add("delta");
    
    System.out.println("Using for loop");
    for (int i = 0; i < objectNames.size(); i++) 
    {
        System.out.println("Name = " +objectNames.get(i));
    }
    
    System.out.println("Using for Iterator");
    // Second approch
    Iterator<String> iterator = objectNames.iterator();
    while (iterator.hasNext()) {
        System.out.println("Object Name = "+iterator.next());
    }
  }
}

Output:

Object Name = alpha
Object Name = beta
Object Name = delta