Solution
public class ClassName {
public static void main(String[] args) {
String cars[] = {"Audi", "BMW", "Renault", "Porsche", "Ferrari"};
for(String CarsNames : cars) {
System.out.println(CarsNames);
}
}
}
Output
Audi
BMW
Renault
Porsche
Ferrari
Explanation
- Initialize and declare an array of String with “cars”.
- Two ways to iterate an array – “for” loop and “for-each” loop.
- The “for-each” loop is used to iterate an array. It accesses each element in the array and prints using println(). Here, no need to initialize and increment the loop iterator as in the “for” loop. The loop directly traverses the elements of the array.