Java 5: Enhanced for loops

Java 5 features
 Enhanced for Loop |   Varargs |   Static import |   Autoboxing and unboxing |   Enum types |   Generics |   Annotations |   By date 

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.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.




Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017