Friday, January 6, 2012

The For Loop

There are two types of for loops in Java. Your traditional loop:




for (int i = 0; i < 10; i++) {

}


Or the advanced loop that will loop through items in say an array:




for (String s : stringArray) {

}


Let's go through both of these examples and see what comes of it.



First, let's create a String Array for the loops to process.




String[] strArray = {"one", "two", "three"};


Simple enough. Just an array containing three values of one, two and three.



With the traditional for loop, you would loop through the array like this:




for (int i = 0; i < strArray.length; i++) {
System.out.println(strArray[i]);
}


As you might have guessed, it outputs the three values:




One
Two
Three


Now, let's do the same thing, but using the other for loop. Sometimes this loop is called a For Each loop.




for (String s : strArray) {
System.out.println(s);
}


Again we get the three values:




One
Two
Three


I prefer the new method myself. It comes in handy. But there are times that you'll want to use the traditional for loop, (for example if you want to run through a Multidensional Array).



Happy Coding!

No comments:

Post a Comment

Ever feel like no one is listening?

 Ever have that feeling that no one is listening to you? Yeah, that feeling. It can be a strong feeling to have, a hurtful feeling also. The...