From Java to Groovy in a Few Easy Steps
Groovy and Java are really close cousins, and their syntaxes are very similar, hence why Groovy is so easy to learn for Java developers.
Join the DZone community and get the full member experience.
Join For FreeGroovy 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!
Opinions expressed by DZone contributors are their own.
Comments