400 APPENDIX B: Introduction to Groovy
Note Groovy requires Java, so you need to have a version available (while Groovy 1.6 supported JDK 1.4 or
greater, for Groovy 1.7 onward, at a minimum JDK 1.5 is needed).
To validate your installation, open a console and type the following:
groovy -v
You should see something like this:
Groovy Version: 2.0.0 JVM: 1.6.0_31 Vendor: Sun Microsystems Inc. OS: Windows 7
Now you can write your first “Hello World” program (see Listing B-1).
Listing B-1. “Hello World” in Java
- public class HelloWorld {
- public static void main( String[] args )
- System.out.println("Hello World!");
- }
- }
Lines 1 to 2: The default visibility of methods and fields is public, so you can
drop the public modifier.
Line 2: Groovy supports dynamic typing, so you can drop type information and
the return type void on the main().
Line 3: Every Groovy object has at its disposure println, which can be seen as
a shortcut for System.out.println.
Line 3: The semicolon at the end of line is optional, so you can drop that too.
In light of these rules, you can transform Listing B-1 to Listing B-2.
Listing B-2. Transforming “Hello World” Applying Groovy Rules
- class HelloWorld {
- static main( args ){
- println "Hello World!"
- }
- }
As you can see, Listing B-2 is much more compact. You can write and execute Groovy code in the
form of scripts that are also compiled to bytecode. So, you can write the Groovy code illustrated in
Listing B-3 for the “Hello World” program.
Note Any Java class/object is also a Groovy class/object.