Ranges in Groovy represent a collection of hip sequential values; as such, they facilitate looping in a concise manner. In truth, they function exactly like a for loop; however, they are significantly more terse. For example, the typical for loop in Java looks like this:<pre class="prettyprint"><code>for(int x=1; x<=term; x++){ System.out.println(x); }Of course, I could leverage Java’s succinct for loop syntax using the venerable colon (:) if I am able to capture a list of values (i.e. 1 to term) like so:<pre class="prettyprint"><code>for(int x : values){ System.out.println(x); }Thus, in both cases, if my term value is, say, 3, the numbers 1, 2, and 3 will be printed. Interestingly, if it’s my bag and I want the exclusive range– that is, I don’t want 3 in my series, I can finagle my first for loop’s second expression to x < term (reminds you of working with normal array’s eh?). The same desired behavior, however, isn’t so easy when it comes to using the newer for loop syntax– I suppose I could remove the last item in the values collection (which presumably is 3, right?). Groovy has the notion of ranges, which, as mentioned earlier, essentially represent a collection of sequential values. In my case, if term is equal to 3, then I can represent a an inclusive range of 1, 2, 3 as 1..termand an exclusive range — that is, 1 and 2 only as 1..<termRanges facilitate looping rather efficiently. Because they are a list of values, you can leverage the each method call, which is available to any collection in Groovy (remember, objects other than normal Collections can be collections of values — a String is a collection of characters, for instance). For example, I can achieve the same result as my first copasetic Java example, like so:<pre class="prettyprint"><code>(1..term).each{ println it }and if I want to capture the exclusive range (that is, I don’t want term’s value), I can simply write:<pre class="prettyprint"><code>(1..<term).each{ println it }Note how the range effectively lessens the amount of code one has to write to achieve iteration; that is, a range’s sequential-ness enables me to drop having to specify loop conditions (i.e. x < term). And because ranges in Groovy are, in fact, java.util.Lists they can also be leveraged properly in new-style for loop. If you still find yourself looking for some familiarity with Java and miss the for loop, you can also leverage ranges in Groovy’s for loop using in rather than a colon like so:<pre class="prettyprint"><code>for(x in (1..term)){ println x }And don’t forget, you can easily substitute that inclusive range for an exclusive one, baby! Iteration and looping are an everyday occurrence in development land (just like disco music is an everyday occurrence in la-la land) and on more than one occasion, ranges have materially reduced ceremonial for loops that I would have otherwise had to write. So what are you waiting for? Give them a try, man! You can follow thediscoblog on Twitter now! Java