Guillaume has posted 10 posts at DZone. You can read more from them at their website. View Full User Profile

From Java to Groovy in a few easy steps

01.27.2008
| 63366 views |
  • submit to reddit

Groovy and Java are really close cousins, and their syntaxes are very similar, hence why Groovy is so easy to learn for Java developers. The similarities are such that most of your Java programs are even valid Groovy programs! However, as you learn Groovy, you'll get used to its neat shortcut notations, its sensible defaults, its GStrings, and more.

In this first article, we are going to take a Java program and turn it into a Groovy program. We'll start with a dumb but convoluted Hello World program, and in later articles, we may see some more advanced examples. For this one, I've taken my inspiration from some slides that are presented at conferences to show how Groovy and Java syntaxes are close -- thanks to Andres and Paul for this idea.

So what does our initial Java program looks like?

public class HelloWorld {
private String name;

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public String greet() {
return "Hello " + name;
}

public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setName("Groovy");
System.out.println( helloWorld.greet() );
}
}

Well, this HelloWorld class has got a private field representing a name with its associated getter and setter. There's also a greet() method which will return the infamous Hello World string we've all come to love and hate at the same time. Then there's a main() method that will instantiate our class, set the name, and print the greeting message on the output.

What will the Groovy program look like?

 

public class HelloWorld {
private String name;

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public String greet() {
return "Hello " + name;
}

public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setName("Groovy");
System.out.println( helloWorld.greet() );
}
}

Yes, that's exactly the same program! No, I'm not kidding, that's really the same program in Java and in Groovy! I wouldn't really call it a Groovy program though, as we can definitely improve it to make it more concise and readable. We'll do so by following some simple steps to "groovyfy" the program. The first step will be to remove the semi-colons:and at the same time, I will also remove the public keyword as by default classes and methods are public in Groovy, unless stated otherwise explicitely. Our Groovy program now becomes:

class HelloWorld {
private String name

void setName(String name) {
this.name = name
}

String getName() {
return name
}

String greet() {
return "Hello " + name
}

static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld()
helloWorld.setName("Groovy")
System.out.println( helloWorld.greet() )
}
}

What else can we do? We can use Groovy's special strings: the GString. Isn't that a sexy feature? But what is a GString? In some other languages, it is also called an "interpolated string". Inside a normal string delimited by double quotes, you can put some place holders, delimited with ${someVariable}, that will be replaced by the value of the variable or expression when the string will be printed. So you don't need to bother about manually concatenating strings. So what will our greet() method look like?

    String greet() {
return "Hello ${name}"
}

One more baby-step further: you can omit the return keyword and the last evaluated expression of your method will be the return value. So greet() is now even slighlty shorter. Let's recap to see the current state of our program:

class HelloWorld {
private String name

void setName(String name) {
this.name = name
}

String getName() { name }

String greet() { "Hello ${name}" }

static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld()
helloWorld.setName("Groovy")
System.out.println( helloWorld.greet() )
}
}

I've even taken the liberty to turn the getName() and greet() methods into one-liners. But then, what's next? Groovy supports properties -- a future version of Java may also support them. So, instead of creating a private field and writing a getter and setter, you can simply declare a property. In Groovy, properties are very simple since they are just mere field declaration without any particular visibility. Our name property will be just String name, nothing more. A private field and associated getter and setter will be provided for free by Groovy. For calling setName(), you'll be able to write helloWorld.name = "Groovy", and for getName(), simply helloWorld.name. This also means that you will also be able to call getName() and setName() from a Java program invoking our Groovy class. Let's see our new iteration:

class HelloWorld {
String name

String greet() { "Hello ${name}" }

static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld()
helloWorld.name = "Groovy"
System.out.println( helloWorld.greet() )
}
}

Groovy gives you some handy methods and shortcuts for some mundane tasks such as printing. You can replace System.out.println() with println(). Groovy even decorates the JDK classes by providing additional utility methods. And for top-level statements (a statement which is just a method call with some parameters), you can omit parentheses.

class HelloWorld {
String name

String greet() { "Hello ${name}" }

static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld()
helloWorld.name = "Groovy"
println helloWorld.greet()
}
}

So far, you've certainly noticed that we used strong typing all over the place by defining the type of every method, variable or field. By Groovy also supports dynamic typing. Thus we can get rid of all the types if we wish so:

class HelloWorld {
def name

def greet() { "Hello ${name}" }

static main(args) {
def helloWorld = new HelloWorld()
helloWorld.name = "Groovy"
println helloWorld.greet()
}
}

We transformed the strings into the def keyword, we were able to remove the void return type of the main method, as well as the array of string type of its parameter.

Groovy is an Object-Oriented language (a real one where numbers are also objects), and it supports the same programming model as Java. However, it's also a scripting language as it allows you to write some free form programs that don't require you to define a class structure. So in the last step of this tutorial, we're going to get rid of the main method altogether:

class HelloWorld {
def name
def greet() { "Hello ${name}" }
}

def helloWorld = new HelloWorld()
helloWorld.name = "Groovy"
println helloWorld.greet()

A script is really just a bunch of statements thrown freely into your program. You can even define several classes inside a script if you will, just like our HelloWorld class.

Voila! Our boring Java program became much more Groovy, by following some simple baby-steps as we learned how to leverage some of the numerous handy features that the Groovy language provides. The program became much more concise, and at the same time more readable than its Java counterpart. Readability is so important when you have to maintain code, especially if it's not yours, as we usually spend much more time reading and understanding code than actually writing it.

In forthcoming installments, we will learn more about the language, its syntax and its APIs which simplify the life of the Java developer. We will learn about its native syntax for lists, maps, ranges and regular expressions, and much more. Stay tuned!

Published at DZone with permission of its author, Guillaume Laforge.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Fred Barney replied on Mon, 2008/01/28 - 8:25am in response to: Andres Almiray

Sort of.  Since it can't know if classes have been modified at runtime, it won't do a huge part of what most people would consider compile-time type checking. 

Andres Almiray replied on Mon, 2008/01/28 - 2:32pm in response to: Robert Hicks

The answer lies in how groovy handles scripts. Every script is compiled to byte code, meaning it should have an enclosing class, the name of the class will be the name of the file minus .groovy

But in this case you already have a HelloWorld class defined inside the script, that is why you get a compile error stating that class HelloWorld has been defined twice. Just change the name of the script an everything should run fine =-) 

Mihai Campean replied on Wed, 2008/01/30 - 2:56am

Looks like Groovy is a versatile language :). Very nice article, I like the approach very much and I am looking forward to new articles in this series.

replied on Sun, 2008/02/03 - 9:22pm

Good post. I would've liked to see a litte some more about properties, since the properties, as you described them look just like normal java fields. Let's say I wanted to create a property, but I wanted to override the default behaviour of the setter, to say, also outputting to a log or whatever, would calling the setter via

helloWorld.name = "Groovy"

automatically call my overridden setter method such as:

void setName(String name) {
  this.name = name
  println "name has been set"
}

(Ps. sorry, I don't know how to include code properly in dzone).

Kookee Gacho replied on Mon, 2012/05/28 - 7:56am

Once you decide to use an EJB application the first thing that you have to decide is choosing between local/remote EJB.-Arthur van der Vant

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.