Introduction to Groovy (Part 1)

Java developers are now being inundated with a number of scripting and dynamic languages that will run on top of the Java Virtual Machine. One of my favorites (and a big focus of this weblog) is Groovy, an agile dynamic language that looks a lot like Java, but is inspired by other languages like Python, Ruby, and Smalltalk. It introduces concepts that current versions of Java lack such as Closures, dynamic typing, operator overloading, and native lists, maps, hashes, and regular expressions (although Java provides classes for those).

Groovy is a dynamic language, not a scripting language. The code compiles down to Java bytecode instead of being interpreted like a lot of other languages. It is useful for writing web applications, shell scripts, and test cases. In fact, there is tight integration with JUnit for testing.

The code is quite easy. A basic “Hello, world” program in Groovy can look like this:

[groovy]println “Hello, world!”[/groovy]

Whereas in Java, the code looks like this:

[java]class HelloWorld {
public static void main(String[] args) {
System.out.println(”Hello, world!”);
}
}[/java]

So how does one get started with Groovy? In this tutorial we will cover installing Groovy and creating a basic Groovy script. First off, you need to have a Java Virtual Machine installed. If you are running an operating system such as Mac OS X or any variety of Linux or Unix, chances are that you already have a JVM installed. If you are running Windows or if you do not have it installed, you should visit http://java.sun.com/javase/downloads/index.jsp and download a JDK for your platform. Once installed, you will have to set up an environment variable called JAVA_HOME that points to the path of your JDK. (That is beyond the scope of this introduction, but if you need help, search Google or post it in the comments!)

Once Java is installed and the JAVA_HOME variable is set up, then you need to install Groovy. Follow the installation guide on the Groovy website to download and configure it.

Groovy can be run a couple of different ways. You can use an interactive shell (groovysh), where you can enter a number of statements line by line. When you are ready to execut the statements, use the “execute” command to run your code. There is also an interactive Swing console (groovyConsole) which gives you a window user interface to run your Groovy code. To run more like a scripting language, you can type “groovy scriptname.groovy” to run a script from the command line. Finally, you can use the “groovyc” command to compile your Groovy script to Java bytecode that can be executed via the “java” command.

For your first Groovy script, open a text editor and save this file as ExampleOne.groovy:

[groovy]colors = ["red", "orange", "yellow", "green", "blue"]
println “The color list is: ” + colors.join(” “)
sortedColors = colors.sort()
println “The Sorted color list is: ” + sortedColors.join(” “)
[/groovy]

Let’s take a look at what this script should do, line by line:

[groovy]colors = ["red", "orange", "yellow", "green", "blue"][/groovy]

This sets up a list named colors, much like defining a new List in Java. In fact, lists in Groovy are instances of java.util.ArrayList and you can use all the methods from that class (as well as some additional ones like we will see below).

[groovy]println “The color list is: ” + colors.join(” “)[/groovy]

This line does two things: First off it takes all the elements of the colors list and appends them into a single string seperated by a space. Then it concatenates it to our message and prints it out on the screen.

[groovy]sortedColors = colors.sort()[/groovy]

This line creates a new list named sortedColors and its values are the sorted elements of the colors list. The final line is just like the line above where it prints out the list for us. If you run the script by typing in “groovy ExampleOne.groovy” on the command line, your output should look like this:

tim@slaggle.com [~]# groovy FirstExample.groovy
The color list is: red orange yellow green blue
The Sorted color list is: blue green orange red yellow

That’s it for this brief introduction to the Groovy language. In Part 2 we will cover the basic data types and looping constructs of Groovy, and Part 3 will introduce you to closures.

3 Responses to “Introduction to Groovy (Part 1)”

  1. BJ Says:

    I like the updates. I also liked how clean k2 was though.

    You know me though, I’ve been in the flash and trash crowd since I started a blog heh.

    Nice write-up on Groovy, it could help with quick projects, I’ll check back for further updates.

  2. tim Says:

    Yeah, you know me. I have to change the look pretty drastically every once and a while or else I start to lose interest in keeping things up. If I had time I would create my own layout and design but I don’t have much free time between work, WoW, and my side development projects. I did update K2 when I upgraded Wordpress and I really like the additions they have made so far. I might go back to it if I ever get the inclination to update the old stylesheet.

    I also wanted a fresh start to make a shift in the focus of my weblog. Instead of random “hey I had a sammich for lunch” type blog I want to have real useful content.

    I’ll still have personal updates every once and a while, but the main page will only reflect articles and information concerning Java, Groovy, Grails, JSF/Spring/Hibernate, JBoss Seam, and other programming concepts.

  3. BJ Says:

    Well keep the framework/concept/architecture write-ups coming, I don’t get the chance to experiment as much as I’d like and I sometimes miss better ways to do things.

    So you think your site could survive a digging?

Leave a Reply

You must be logged in to post a comment.