Looping is a control structure that has been around ever since we started programming. The good old syntax for looping that you would have used most often is: String[] messages = {"Hello", "Greetings", "Thanks"}; var length = messages.length; var int i = 0; for(i = 0; i System.out.println(messages[i]); } What if you want to iterate over a collection, like ArrayList? We will do something like: Iterator iter = lst.iterator(); for(;iter.hasNext();) { System.out.println(iter.next()); } The foreach was introduced to avoid introduction of any new keywords. The foreach introduced in Java 5 simplifies looping further. Let’s take a look at an example of how we can use the new way to loop: for (String msg : messages) { System.out.println(msg); } You would read for (String msg : messages) as "foreach String msg in messages". Within the loop of foreach, msg represents a String element within the array String[]. Instead of inventing another keywor...
Blog on things around me - Quality Management, Free & Open Source Software, Gadgets, Utilities...