Java 5: Enhanced for loops

  Java Features     Java 5     Java 7     Java 8  
Java 5 features

Enhanced for loops is introduced in Java 5. This feature allows you to handle loops in a simple. In the example below we compare the new for loop with the older one! For more info click here to read Oracle’s explanation.

Example 1: Enhanced for loops code

What is the output of the following code?

public class EnhancedForLoop
  public static void main(String[] args)
    String brands[] = {"Dell", "HP", "IBM"};
    // enhanced for loop
    for(String element: brands)
      System.out.print(element + " ");
    // older Java versions
    for(int i = 0; i < brands.length; i++)
      System.out.print(brands[i] + " ");
Author: Sar Maroof

Answer explanation

The answer is simple. both loops write the same elements of the array brands to the standard output.

The correct answer is: Dell HP IBM Dell HP IBM.


 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply
