Tuesday, February 9, 2010

Java Programmer's first look on Groovy

Like many Java programmers i started learning Groovy for some fascinated stuffs like Dynamic Typing, Closures, functional programming, etc. Overall the first experience with the Groovy was mind blowing. It has many new things to learn. To start with i am using Groovy in Action, its an excellent book for Groovy beginners.

My first encounter with Groovy started with the conventional "Hello World" program. The Hello World example finished and as such i didn't learn anything.

println "Hello, World"

But meanwhile i found that there are various ways to execute the above groovy code snippet:

1. From command prompt

>groovy -e "println 'Hello, World'"

2. From .groovy file

// HelloWorld.groovy

println "Hello, World"

// on prompt
// .groovy extension is optional
>groovy HelloWorld.groovy

3. From Groovy Interactive Console

// on prompt

A GUI application will open where in the upper half part developer can write the Groovy script and on lower half can see the script result.

4. From Groovy Shell

Though i haven't explored the Shell much but i could execute one line at a time and "Hello World" needs one line only. Following is the command to open the Groovy Shell:

// on prompt

Seemingly it would look quite simple to a new learner, but the real magic starts when the above code is either executed by Java interpreter or used by a Java program.

Convert Groovy files to .class files

// on prompt
// .groovy extension is NOT OPTIONAL this time
>groovyc HelloWorld.groovy

And the above command will create a .class file which can be executed with:

// on prompt
>java -classpath .;{groovy home}\embeddable\groovy-all-1.6.7.all.jar HelloWorld

And it works correctly. The same way this class file can be access by any Java program, it can create an instance or call the main() method directly.

So overall my first experience with Groovy was really good and i am quite sure to spend some time with this emerging language.


1. Groovy Home
3. Lots of links at Groovy DZone

No comments:

Post a Comment