Java enhanced for loops for UTS peeps


A very good friend of mine at UTS and on The Twitters asked about enhanced for loops in Java. I think he understands what's going on now, but just in case I'm putting an example up here!


  • In the real world, we don’t really use primitive arrays in Java anymore, but given UTS still teaches them for some reason, they’ll do for our example here!

  • For some reason I got into the habit of including the above picture from Railgun into my programming posts. Presumably because there’s a laptop involved, and I can’t stand dry posts without pictures! But I digress.

Regular for loops

Say we wanted to create an application that stores a list of moeblob character names into an array, then print each name out to the screen.

public class EnhancedForLoop
  public static void main(String[] args)
    String[] keion = new String[3];
    keion[0] = "Mugi";
    keion[1] = "Yui";
    keion[2] = "Azusa";
    for (int count = 0; count < keion.length; count++)

As you can see, we created an array and populated it with character names. We then used a for loop and printed each character by referencing them one by one.

There's a simpler way!

There are circumstances where a traditional for loop would be preferred (and needed!), but if all you want to do is traverse an array one by one, there's a simpler way!

for (String name : keion)

In this loop, instead of referencing each array element by a number, it traverses the array one by one for us, and stores the current element in a temporary variable. In this case, each element in our "keion" array gets put into our temporary "String name" variable! :D

As you can probably tell, for going through an array one by one, an enhanced for loop is:

  • shorter and easier to write
  • the statements in the loop are easier to read, make more sense
  • you don't need to know how many elements there are
  • you don't need to do any maths!

These kinds of loops are common

I'm not sure if you've done any scripting, but enhanced for loops are huge in languages like Perl, Ruby and Python. My personal favourite is the former ^_^

#!/usr/bin/perl -w
use strict;
my @keion = qw/Mugi Yui Azusa/;
foreach my $name (@keion) {

Author bio and support


Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.