Java enhanced for-loop FTW

I’ve got to do a whole slab of Java/J2EE coding soon so I’m in the process of skimming/re-acquainting myself with the Java language as a whole, when I just came across the new way to iterate over collections in a for-loop (available from Java 5 onwards) – and it’s genius!

public class ForLoopTest
	public static void main(String[] args)
		String[] carMakes = { "Ford", "Kia", "Vauxhall", "Ferrari" };
		// Old-school for-loop
		System.out.println("----- Old-School For-Loop -----");
		for (int loop = 0; loop < carMakes.length; loop++)
		// New enhanced style for-loop
		System.out.println("----- New Enhanced For-Loop -----");
		for (String current : carMakes)
	} // End of main

How much easier to both read and write is that? Clever clever clever…

P.S. I just looked it up and Java 5 was released in 2004, and it’s only now I’m finding out about this?! Hahaha! Besides a socket client I knocked together a couple of months back I haven’t coded anything in Java since 2001!

Update 2014: Whilst very useful in general, avoid the enhanced for-loop in game development; it creates temporary objects which the garbage collector must then clean up. Any time the GC runs, you’ll take a performance hit. For example, if you’re writing a game and you use a lot of these, your game’s frame rate may stutter as and when the GC reclaims memory (which is as and when it feels like running – you may ask it to run, but whether it does or not is outside of your control).

6 thoughts on “Java enhanced for-loop FTW”

  1. Loads of new goodies were introduced with Java5

    If you think the new for statement is useful then Generics will blow your mind!

    Best resource for going from Java 1.4 thinking to Java5+ thinking is the book…
    Java 1.5 Tiger – A Developer’s Notebook
    Brett McLaughlin / David Flanagan
    O Reilly (O RLY!)
    ISBN 0-596-00738-8
    See Amazon page for this book

    It’s one of those books that you keep on your desk rather than on the shelf.

    And you don’t need to worry about the book being outdated because of Java6 / Java7 releases because the language changes are not too dramatic in comparison.

    1. Cheers for the heads-up – will def check it out. I’m currently using the Head First Java book, and it’s chock full o’ Java-y goodness!

      Could you recommend a Spring Framework book for object persistence or would you advise just going with MySQL Connector/J as I’ve got (looks at watch) – 5 days to build a receipt system that prints to an Epson POS printer =D

      1. Holy heck man, that’s a tough call wrt time.

        I’d recommend using Maven2 to handle your jar dependencies as it’ll also automate the war building process. That’s just developer stuff, nothing to do with the app. Saves massive chunks of time through development though.

        Spring is hard to describe. In a nutshell it does dependency injection, so you configure how your objects are built. It’s like a team co-ordinator, with the team members being the technologies you use in your system. You don’t HAVE to use it, but it makes life simpler in the long run.

        Spring is agnostic when it comes to the persistence layer. It can use any of them just as easily. You could use the new JPA 2.0 (which is where this tech is headed), but I’d recommend Hibernate as there is a lot of help out there for it and JPA2 may be a little too new. That means you don’t have to write a single SQL statement (even to create your db), but it takes longer than 5 days to learn and be useful with it.

        Don’t think of java persistence as using sql tables, think in terms of you saving your java objects to disk. All that oracle/mysql/postgres you learned? Yea, fuggeduboutit. You come from the java viewpoint, which is symantically the proper way.

        I’ll get you some ISBN numbers for Spring and Hibernate when I get to work.

        I’ll also give you a copy of one of my in-progress proof-of-concept projects. It can query a database through hibernate using spring mvc. And uses maven for the build process. We can chat through it sometime over the weekend if you want.

        Do yourself a favour and setup m2eclipse within your eclipse ide when you have a spare moment. And also install maven2 or maven3 command line. (m2eclipse uses an embedded maven rather than what’s installed on your system, which is a bit rubbish. But m2eclipse is also REALLY useful)

        1. Okey-doke. Cheers, fella! =D

          Hmm, thinking that’s a lot for 5 days, too – so might just Connector/J it for now (which I can have up + running + forms & shiz in just a few hours).

          Have a great Friday and will chat on teh Sabbath!

        2. Beginning Hibernate (2nd Ed) – Jeff Linwood / Dave Minter [Apress]
          ISBN 978-1-4302-2850-9

          Spring In Action (3rd Ed) – Craig Walls [Manning]
          ISBN 978-1-935182-35-8

          This one is more for ensuring your app / website / etc is only giving authorised content to your users
          Spring Security 3 – Peter Mularien [Packt]
          ISBN 978-1-847199-74-4

          Personally I just wished I knew about and purchased these books MONTHS before I actually did. The info just isn’t available anywhere on the web in such a useful format.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.