2.1 From Java to Groovy

Let’s start with a piece of Java code with a simple loop. We’ll first run it through Groovy. Then we’ll refactor it from Java style to Groovy style. As we evolve the code, each version will do the same thing, but the code will be more expressive and concise. It will feel like our refactoring is on steroids. Let’s begin.

Hello, Groovy

Let’s start with a Java code example that’s also Groovy code, saved in a file named ​Greetings.groovy​.

 
// Java code
 
public​ ​class​ Greetings {
 
public​ ​static​ ​void​ main(​String​​[]​ args) {
 
for​(​int​ i = 0; i < 3; i++) {
 
System​.out.print(​"ho "​);
 
}
 
 
System​.out.println(​"Merry Groovy!"​);
 
}
 
}

Let’s execute this code using the command ​groovy Greetings.groovy ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.