Groovy For Java Geeks

Groovy For Java Geeks :

No semi colons required.
Generally methods do not require braces.

By Default Imports classes / packages :

    As groovy is based on java. Groovy automatically imports the following Java packages:    

    1) java.lang
    2) java.util
    3) java.io
    4) java.net

It also imports the classes
    1) java.math.BigDecimal
    2) java.math.BigInteger.

In addition, by default groovy.lang and groovy.util are imported.

Loops 

Java Loop Example

public class TestLoop {
public static void main(String[] args) {
  for(int i = 0; i < 3; i++) { 
       System.out.print(“in loop");
   }
}

Loop in Groovy

// inside .groovy file. 

for(i in 0..2) { print ‘in loop ' } // that's it

There are other ways also ...

0.upto(2)  { print ‘in loop ' }

OR

3.times  { print ‘in loop ' }

Iterations can be specified in loops. Standard way to define it is $it.

upto is an example of closure. Please closure section for closure details.

defining steps for loop

Syntax
      <startingNumber>.step(lastNumber,step) {...}
Example
       0.step(20,4) {print "$it "}
will print 0 4 8 12 16 20


 


No comments:

Post a Comment