Java Reference
In-Depth Information
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
1. public class HelloWorld {
2. public static void main( String[] args )
3. System.out.println("Hello World!");
4. }
5. }
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
1. class HelloWorld {
2. static main( args ){
3. println "Hello World!"
4. }
5. }
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.
 
 
Search WWH ::




Custom Search