Last editor: Dave Cherry, last modified: Aug 3, 2008
In the previous groovy article I gave you a feel for the groovy language, showing you how to deal with strings, objects and do basic iteration. In this article I go into a little more detail about looping and how the type system works.
A range is a sequence of numbers either inclusive or exclusive. Ranges are used in many places in the groovy language, so getting an understanding of them is important. A range is a sequence of numbers, either inclusive or exclusive. Please see the example below.
0..10 range of 0 to 10 inclusive.1..9 range of 1 to 9 inclusive1..<9 range of 1 to 8 (exclusive of 9)[0..10] range of numbers 0 to 10 inclusive as a ListIn comparison with java, groovy if statements allow a wider range of conditions. For example references are considered false when null, integers are considered false when 0.
def ref = null
def val = 10;
if( ! ref)
{
println "null"
}
if( val )
{
println "not zero"
}
While is pretty much the same as the java equivalent, except that the condition does not have to be boolean as per the if statement.
def val = 10;
while( val )
{
println val;
val--;
}
For statements are quite different from Java, but I think for the better as they are much more readable. In essence a for statement is an iteration over a range or iterable (such as list). See the examples below.
// notice this is a range - ie no []
for (i in 1..5)
{
println "for loop ${i}"
}
for(i in [1,4,6,8,9])
{
println i;
}