6. Various of looping in Groovy

We can actually improvise our way in writing code to be more comfortable to be read, or simpler to code. By using several add from groovy we can improvise those traditional loops into modern one. We have 3 new ways to make it different from the traditional one. We can choose which one is the best for us. I think it depends on how the way we code and read it. Let’s learn it by the example

public class TraditionalLoop{
    public static void main(String[] args){
        for(int a=0 ; a<3; a++){
            System.out.println("Hello World");
        }
    }
}

Here is the result

Improvisation :
Type 1:

for ([VAR] in [STARTLOOP]..[ENDLOOP]){
     //statement
}

Type 2:

[STARTLOOP].upto([ENDLOOP]){
        //statement
}

Type 3:

[NLOOP].times{
     //statement
}

For the last one, if we want there is skip values while looping, we can use
[STARTLOOP].step( [NLOOP], [NSKIP] ) method. Here is the example :

Tagged: , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: