Loops in Groovy

  The Groovy loops are very powerful and easy to use compared to Java. Here I printed 0 to10 integer values using both Java and Groovy language.

The java code.
public class LoopsInJava {
    public static void main(String[] args) {
        for(int i=0;i<10;i++) {
            System.out.println(i);
        }
    }
}

The Groovy code.
class LoopsInGroovy {
    public static void main(String[] args) {
        10.times {
            println it
        }
    }
}
Just notify the real power of Groovy now.
If suppose you want to print some even numbers that are in between 2 to 20 then, you can able do like this.

2.step(20,2) {
    println it
}

It is equivalent to
for(int i=2;i<20;i+=2) {
  System.out.println(i);
}

The output is.
2,4,6,8,10,12,14,16,18

Comments