A loop is a control flow structure in Java that enables code to be iterated over and over with until a specific condition is met. There are three types of loops in Java; For loop, while loo, and do-while loop. This discussion focusses on the for loop.
In Java, the for loop comprises two types, that is, the regular for loop and the enhanced for loop. The regular for loop can iterate over anything including arrays, collections, and figures. The values of the iterated arrays and collections can be altered as a for loop provides and index value. The for loop takes in three parameters namely; the initialization variable, the testing condition, and the increment/decrement.
The initialization condition initializes the variable to be tested. This can either be an already initialized variable, or a locally initialized variable inside the for loop. It determines the index from which the for loop will start when initiating the loop.
The testing condition checks if the loop requirements have been met and returns true or false. If the condition is false, then the loop continues iterating. If it results to true, then the loop breaks and the next statement after the loop is executed.
The increment/decrement section increments or decrements after each iteration. It will do so until it matches the testing condition upon which the loop breaks. Below is an example of a regular for-loop.
for (int i=0; i <5;i++)
System.out.println (i);
}
Output:
1
2
3
4
The second type of for loop is the enhanced for-loop, which was introduced in Java 5. The enhanced for loop is specially formulated to iterate over collections and arrays, and does not provide and index, hence values can only be read sequentially. However, the enhanced for loop is simpler to implement than the regular for loop as it only takes two parameters i.e. the variable that will hold the element picked from the iteration and the collection/array. Below is an enhanced loop in action:
String [] words = {"Me","You","Them"};
for(String i: words){
System.out.println (i);
}
Output:
Me
You
Them
One thing to note about the enhanced for loop is that the values of the collection/array are immutable since no index is provided.
An enum in Java is a special data type that contains a fixed number of constants. It can contain either constants, or methods, or both. Once an enum has been initiated, it cannot be modified during runtime. An enum can be iteratedin several ways; using an enhanced for loop, using a forEach loop, and using java.util.stream. The code below showcases iteration using the for loop and the forEach loop method (introduced in Java 8).
public enum names {Edgar, Peter, Thomas};
//using for loop
for (names n: names.values()){
System.out.println (n);
}
Output:
Edgar
Peter
Thomas
//Using forEach
//First convert the array to a list and then apply foreach
Arrays.asList(names.values()).forEach(name->System.out.println (name));
Output:
Edgar
Peter
Thomas
Comments
Leave a comment