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:



OneTwoThree


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:



OneTwoThree


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

No Sleep

 This is the second day I've woken up early. Like way earlier than normal. Like four am early. I don't know what to do about it. I n...