Cool New Loop in Java 5

Most of us grew up with “Learn How To Program in C“. Then some of us shifted to JAVA due to the phrase, “Write Once, Run Everywhere“. Now back then, learning to write a loop in those days are considered good programming practice during the C Programming era. TechieDan even has his experiences on C Program and even wrote his own source using the goto method. (goto method is definitely not a good programming practice)

For reference sake, this is how a for loop is written in Java.

Rope Loop
No! Not a Rope Loop. A Java Loop

int[] total = {1,2,3,4,5};
int node = 0;

for (int i=0; i<5; i++) {
node = total[i];
System.out.println(node);
}

The above would then display the result as shown below.

1
2
3
4
5

For the non-programmies, these seem like Greek to them. For programmies, these are just simple FOR LOOP methods. The above was written in reference before Java 5 has broke into this era. Now what if the start of Java 5 has brought upon a new era just like how Autoboxing was introduced in Java 5. Here's the newly enhanced loop which would also display the same result as above where we call it the FOR EACH LOOP.

int[] total = {1,2,3,4,5};
for (int i : total) {
System.out.println(i);
}

Oh my what happened to the code? Why is Java 5 that simple? Not only does this help one to code easier, the length to type out a FOR LOOP has now been cut short with this new method of writing one. What it does is pretty simple. In lame man's term, it's For each value in total I will pass them to variable 'i' to print.

Conclusion

Java 5 really does wonders to programmers of the technology in this new era. Of course SCJP exam takers should now know about this.

5 Comments

  1. Kennee October 28, 2009
    • techieDan October 29, 2009
  2. acai berry November 10, 2009
  3. danielctw March 8, 2011

Leave a Reply to techieDan Cancel reply