| Java, Eclipse and Web programming Tutorials |
Version 1.1
Copyright © 2008 - 2010 Lars Vogel
02.02.2010
| Revision History | ||
|---|---|---|
| Revision 0.1 | 12.11.2008 | Lars Vogel |
| Started writing this article | ||
| Revision 0.2 | 02.12.2008 | Lars Vogel |
| First published version | ||
| Revision 0.3 | 10.12.2008 | Lars Vogel |
| Described the Groovy datatypes | ||
| Revision 0.4 | 13.12.2008 | Lars Vogel |
| Added closures | ||
| Revision 0.5 | 26.01.2009 | Lars Vogel |
| Clean-up work | ||
| Revision 0.6 | 15.04.2009 | Lars Vogel |
| Update to Groovy 1.6, moved command line into appendix | ||
| Revision 0.7 | 31.05.2009 | Lars Vogel |
| Improved loop examples, update for Eclipse 3.5 | ||
| Revision 0.8 | 15.06.2009 | Lars Vogel |
| Simplified explanation | ||
| Revision 0.9 | 18.07.2009 | Lars Vogel |
| New reference | ||
| Revision 1.0 | 30.07.2009 | Lars Vogel |
| Update to Eclipse 3.5 and new plugin | ||
Groovy
This article gives a short overview of the Groovy language including collections, loops, gstrings, MOP, closures, operator overloading, XML handing and using Groovy together with Java class. It also describes how to use Eclipse for developing Groovy.
This article assumes that you have already Eclipse installed and that you have used Eclipse for Java development. This article was written using Groovy 1.7, Eclipse 3.5 (Galileo) and Java 1.6.
Table of Contents
Groovy is a dynamic language which is based on the Java Virtual machine. Groovy supports standard Java constructs including annotations, generics, static imports, enums, varargs and in addition advanced language features as
Groovy is a dynamic language that runs on the JVM and is tightly integrated with the Java language. Groovy provides lots of simplifications compared to standard Java language features and advanced language features as properties, closures, native support for lists, maps and regular expressions, duck typing and the elvis operator.
Groovy is almost compatible to Java, e.g. almost every Java construct is valid Groovy coding which makes the usage of Groovy for an experience Java programmer easy.
The following assumes that you have already Java programming experience and focus on Groovy specific features.
While the simplicity and ease of use is the leading principle of Groovy here are a few nice features of Groovy:
Groovy allows to change classes and methods at runtime. For example if a class does not have a certain method and this method is called by another class the called class can decided what to do with this call.
Groovy does not require semicolons to separate commands if they are in different lines (separated by new-lines).
Groovy has list processing and regular expressions directly build into the language.
Groovy implements also the Builder Pattern which allows to create easily GUI's, XML Documents or Ant Tasks.
Asserts in Groovy will always be executed.
Download the latest version from Groovy from Groovy Homepage .
You have then to set the GROOVY_HOME environment variable and add%GROOVY_HOME%/bin to your path.
Use the Eclipse Update manager to install the Groovy Eclipse plugin. The URL for the update manager is: http://dist.springsource.org/release/GRECLIPSE/e3.5/ for Eclipse 3.5. Select the feature "Groovy-Eclipse".
Create a new Groovy project "de.vogella.groovy.project" via File -> New -> Other -> Groovy

Create a new package "de.vogella.groovy.project".
Select File -> New -> Other -> Groovy -> Groovy Class

Create the class "GroovyTest"

Create the following code.
package de.vogella.groovy.first
class GroovyTest{
static void main(def args){
def mylist=[1,2,"Lars","4"]
mylist.each{ println it }
}
}
Select the class, right click and select "Run As" -> "Groovy Script"
This should run your Groovy class and give you output on the shell.
Congratulation! You created and run your first Groovy class.
A Groovy source files ends with the extension .groovy. All Groovy classes are per default public.
Create and run the following groovy class "SumItUp.groovy".
package de.vogella.groovy.first
class SumItUp {
static sum(a,b){
a+b;
}
static void main(args){
println sum(1,5)
println sum(1,2)
}
}
In Groovy all fields of a class have per default the access modifier "private" and Groovy provides automatically getter and setter methods for the fields. Therefore all Groovy classes are per default JavaBeans (Plain Old Java Objects).
You can use the getter and setter directly or use the name of the variable for access. Groovy will convert this to the getter and setter method.
Groovy will also directly create constructors in which you can specify the element you would like to set during construction. Groovy archives this by using the default constructor and then calling the setter methods for the attributes.
Have a look at the following example to see this in action.
package de.vogella.groovy.first
public class Person{
String firstName
String lastName
int age
def address
static void main(def args) {
Person p = new Person()
// Use the generated access methods
p.setFirstName("Lars")
// This will still use the generated access method, it is not a direct access!
p.lastName = "Vogel"
p.address = ("Homestreet 3");
println(p.firstName + " " + p.lastName);
// Use the generated constructor
p = new Person(firstName: "Peter", lastName:"Mueller");
println(p.firstName + " " + p.lastName);
}
}
One difference between Java and Groovy is that the == operator will check for equality and not for identity. Java checks if both variables points to the same object while Groovy checks if both variables are equals. To check for identify you can use in Groovy the is() method.
Create a new project "de.vogella.groovy.loops" with the package "de.vogella.groovy.loops" for this example.
Groovy supports the standard Java loops but also the the each() method on several objects. In this method you can directly write code which should get executed. You can either directly define the name of the variable which the value of each iteration should get assigned to or using the implicit available variable "it".
package de.vogella.groovy.loops
public class PrintLoop{
public static void main(def args){
def list = ["Lars", "Ben", "Jack"]
// using a variable assignment
list.each{firstName->
println firstName
}
// using the it variable
list.each{println it}
}
}
In additional your have the methods upto(), downto(), times() on number variables. Also you can use ranges (this is an additional datatype) to execute certain things from a number to another number. Please see the following example.
package de.vogella.groovy.loops
public class LoopTest{
public static void main(args){
5.times {println "Times + $it "}
1.upto(3) {println "Up + $it "}
4.downto(1) {print "Down + $it "}
def sum = 0
1.upto(100) {sum += 1}
print sum
(1..6).each {print "Range $it"}
}
}
Create a new Java project de.vogella.groovy.datatypes. Create the package "de.vogella.groovy.datatypes".
All variables in Groovy are reference variables (objects), Groovy does not use primitive variables. Groovy still allows to use the primitives types as a short form but always translates this into the object.
Groovy allow static and dynamic typed variables. If you want to use dynamic typed variables you can use the keyword def.
If you use numbers then Groovy will automatically assign a type to it and will also make down- and upcasting for you.
Create the class "TypesTest" to test this.
package de.vogella.groovy.datatypes
public class TypesTest{
public static void main(args){
int i = 1 // Short form for Integer i = new Integer(1)
int j = i +3
int k = i.plus(3); // Same as above
// Make sure this worked
assert(k==4);
println i.getClass().getName()
println j.getClass().getName()
println k.getClass().getName()
// Automatic type assignement
def value = 1.0F
println value.getClass().getName()
def value2 = 1;
println value2.getClass().getName()
value2 = value2 / 2;
println value2
println value2.getClass().getName()
}
}
Groovy allows to define Strings in '' and in "". Strings which are quoted in by "" are so-called GStrings (short for Groovy Strings). In GStrings you can directly use variables which will then be evaluated and included in the text.
package de.vogella.groovy.datatypes
public class StringTesting{
public static void main(String[] args) {
def name = "John"
def s1 = "Hello $name" // $name will be replaced
def s2 = 'Hello $name' // $name will not be replaced
println s1
println s2
println s1.getClass().getName();
println s2.getClass().getName();
}
}
Groovy treads lists and maps as first class constructs in the language. You define a list via List list = new List[]. You can also use generics. To access element i in a list you can either use list.get(i) or list[i].
package de.vogella.groovy.datatypes
public class Person{
String firstName;
String lastName;
Person(String firstName, String lastName){
this.firstName = firstName
this.lastName= lastName
}
}
package de.vogella.groovy.datatypes
public class ListMapTest{
public static void main(args){
List<Integer> list = [1,2,3,4]
println list[0]
println list[1]
println list[2]
List<Person> persons = list[]
Person p = new Person("Jim", "Knopf")
persons[0] = p
println persons.size()
println persons[0].firstName
println persons.get(0).firstName
}
}
You can define maps via Map [key1:value1, key2:value2,...]. An empty map can be created via [:]. The values of a mapped value can get accessed via map[key]. Assignment can be done via map[key]=value.
package de.vogella.groovy.datatypes
public class MapTest{
public static void main(args){
Map map = [:]
def map2 = ["Jim":"Knopf", "Thomas":"Edison"]
println map2["Jim"]
map2["Test"] = "Tester"
println map2["Test"]
}
}
Groovy supports ranges. Every object can be used as long as it implements previous() and next() (which are also represented by the ++ and -- operators).
package de.vogella.groovy.datatypes
public class RangesTest{
public static void main(args){
for (i in 0..9) {
println ("Hello $i" )
}
}
}
For an general overview of regular expression please check Regular Expressions in Java .
Groovy is based on Java regular expression support and add the following operators to make the usage of regular expressions easier:
Table 1.
| Construct | Description |
|---|---|
| =~ | Find: True if the pattern is contained in a text |
| ==~ | Match: True if the complete string matches the pattern |
| ~String | Turns a string into a regular expression |
package de.vogella.groovy.datatypes
public class RegularExpressionTest{
public static void main(String[] args) {
// Defines a string with special signs
def text = "John Jimbo jingeled happily ever after"
// Every word must be followed by a nonword character
// Match
if (text==~/(\w*\W+)*/){
println "Match was successful"
} else {
println "Match was not successful"
}
// Every word must be followed by a nonword character
// Find
if (text=~/(\w*\W+)*/){
println "Find was successful"
} else {
println "Find was not successful"
}
if (text==~/^J.*/ ){
println "There was a match"
} else {
println "No match found"
}
def newText = text.replaceAll(/\w+/, "hubba")
println newText
}
}
Closures are code fragments which can be used without being a method or a class.
A closure is defined via {para1, para2 -> code of the closure}. The values before the -> sign define the parameters of the closure. For the case that only one parameter is used you can use the implicit defined variable it.
The last statement of a closure is returned as return value.
The groovy collections have several methods which accept a closure as parameter, for example the each method.
package test
public class ClosureTest{
public static void main(args){
List<Integer> list = [5,6,7,8]
list.each({line -> println line})
list.each({println it})
}
}
The meta object protocol allows to add dynamically at runtime methods and properties.
If a method is called or a property is accessed in a class and this class does not define this method / property then pre-defined methods are called which can be used to handle this call.
def methodMissing (String name, args) - Called for missing method
void setProperty (String property, Object o ) - called for non existing setter of a property
Object getProperty (String property) - called for non existing getter of a property
package de.vogella.groovy.training
public class AnyMethodExecutor{
def map
Object getProperty (String property){
println "Setting this propery"
return 5;
}
void setProperty (String property, Object o ){
println "Hallo"
}
def methodMissing (String name, args){
def s = name.toUpperCase();
if (s.startsWith("HELLO"))
{
println "This method stats with Hello. Full name $name"
} else {
println "This method is missing"
}
}
public static void main (args){
def test = new AnyMethodExecutor ();
test.hall();
test.helloMethod();
test.Hallo();
test.test= 5;
println test.test;
}
}
Groovy supports that you can use the standard operations in your own classes. For example if you want to use the operation a+b where a and b are from class Z then you have to implement the method plus(Z name) in class Z.
Groovy will map the operations to the following classes.
Table 2.
| Operator | Name | Method |
|---|---|---|
| a+b | plus | a.plus(b) |
| a-b | minus | a.minus(b) |
| a*b | star | a.multiply(b) |
| a/b | divide | a.div(b) |
| a%b | modulo | a.mod(b) |
| a--, --a | decrement | a.previous() |
| a++, ++a | increment | a.next() |
| a**b | power | a.power(b) |
| a-b | minus | a.minus(b) |
| a-b | minus | a.minus(b) |
Processing files with groovy is simple. The following example will first print out every line to the console and then print again every line to the console with a leading line number.
package mypackage
/*
* Writes a files to the console
*/
public class MyFile{
public static void main(def args){
// Write just the content of the file to the console
File file = new File("c:/temp/groovy/content.txt")
file.eachLine{ line -> println line }
// Adds a line number in front of each line to the console
def lineNumber = 0;
file = new File("c:/temp/groovy/content.txt")
file.eachLine{ line ->
lineNumber++
println "$lineNumber: $line"
}
}
}
Groovy allows to process XML very easily.
package mypackage
public class XmlTest{
static void main(args){
def xmldocument = '''
<persons>
<person> <firstname age="3">Jim</firstname> <lastname>Knopf </lastname>
</person>
<person> <firstname age="4">Ernie</firstname> <lastname>Bernd</lastname>
</person>
</persons>
'''
def persons = new XmlParser().parseText(xmldocument);
def allRecords = persons.person.size()
println("Number of person is: $allRecords")
def person = persons.person[0]
// name is the name of the XML tag
println("Name of the person tag is:" + person.name())
// text gets the text of the node firstname
println(person.firstname.text())
// Lets print out all important information
for (p in persons.person){
println "${p.firstname.text()} ${p.lastname.text()}"
}
}
}
All fields of a class are per default created private with automatic getter and setter. You can use the getter and setter directly or use the name of the variable for access. Groovy will convert this to the getter and setter method.
Groovy will also directly create constructors in which you can specify the element you would like to set during construction.
package de.vogella.groovy.first
public class Person{
String firstName
String lastName
int age
def address
static void main(def args) {
Person p = new Person()
// Use the generated access methods
p.setFirstName("Lars")
// This will still use the generated access method, it is not a direct access!
p.lastName = "Vogel"
p.address = ("Homestreet 3");
println(p.firstName + " " + p.lastName);
// Use the generated constructor
p = new Person(firstName: "Peter", lastName:"Mueller");
println(p.firstName + " " + p.lastName);
}
}
Grails is a webframework based on Groovy which allows you to develop a webapplicaiton based on convensions rather then configuration. This idea is similar to the Ruby on Rails idea. See Grails Tutorial for details.
To use Groovy classes in Java classes you need to add the Groovy runtime to the Java classpath.
Create a new Java project "de.vogella.groovy.java". Create package "de.vogella.groovy.java"
Create the following Groovy class.
package de.vogella.groovy.java
public class Person{
String firstName
String lastName
int age
def address
}
Create the following Java class.
package de.vogella.groovy.java;
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setFirstName("Lars");
p.setLastName("Vogel");
System.out.println(p.getFirstName() + " " + p.getLastName());
}
}
You should be able to run this Java program.
Right-click your project, select "Properties" and check that the build path includes the Groovy libraries.

You can run Groovy code via:
the Groovy shell: groovysh
the Groovy interpreter: groovy
the Groovy Console : groovyConsole
complile Groovy code to classfiles and run it via the Java Virtual machine
The Groovy shell is the simplest way to run Groovy program. The groovy shell allow you to type in groovy commands and let them evaluate.
Open a command shell (Start-> Run -> cmd under Windows) and start the groovy shell via "groovysh". Type in the following code:
println("Hello Groovy")
Press enter-> the system will execute your code.
Start the interactive Groovy Shell with the command groovyConsole. This console allows you to test Groovy code.

Thank you for practicing with this tutorial.
Please note that I maintain this website in my private time. If you like the information I'm providing please help me by donating.For questions and discussion around this article please use the www.vogella.de Google Group. Also if you note an error in this article please post the error and if possible the correction to the Group.
I believe the following is a very good guideline for asking questions in general and also for the Google group How To Ask Questions The Smart Way.
http://groovy.codehaus.org/ Groovy Homepage
http://groovy.codehaus.org/Documentation Groovy documentation
http://grails.codehaus.org Grails Homepage
http://www.ibm.com/developerworks/java/library/j-grails01158/index.html Scott Davis introduction article to Grails
http://www.ibm.com/developerworks/java/library/j-pg04149.html Scott Davis article about loops in Groovy
http://www.ibm.com/developerworks/opensource/library/j-pg05199/index.html Scott Davis about XML processing with Groovy
http://www.ibm.com/developerworks/opensource/library/j-pg06239.html Scott Davis about Metaprogramming