The TechGuy

September 6, 2012

Java to Groovy by Example – Part 2

Filed under: Framework/APIs,Groovy,Java,Scripting — Zeeshan Bilal @ 10:32 PM


In the last post we lean very basic concepts from groovy. We also map an example from java to groovy code and then a very simple script. We have also learned that classes are defined in Groovy similarly to Java. Each class in Groovy is a Java class at the bytecode / JVM level. Any methods declared will be available to Java and vice versa. We also learned some of the basic rules/features of groovy;

  • Class and all its methods are by default public.
  • Semicolons are optional.
  • Dynamic and static typing is supported
  • Default return type is void
  • Omit parentheses
  • Groovy is a scripting language

Java Sample Code

In this part we look at some advance HelloWorld java program,

  1. public class GreetWorld {
  2. private String salutation;
  3. public void setSalutation(String salutation) {
  4. this.salutation = salutation;
  5. }
  6. public String getSalutation() {
  7. return salutation;
  8. }
  9. public String greet(String name) {
  10. return salutation + " " + name + "!";
  11. }
  12. public static void main(String[] args) {
  13. GreetWorld hello = new GreetWorld();
  14. hello.setSalutation("Hello");
  15. System.out.println(hello.greet("Java"));
  16. }
  17. }

It’s a simple class GreetingWorld, designed to generate greeting message. There is a private field to preserve salutation with associated setter and getter. You can find a method greet that used to generate the greeting message, it receives a parameter to associate name with the message. Now let’s see how groovy code looks like for this program.

Groovy version

If we look at line 2 to 10, there is a private field with associated setter and getter.

Groovy support properties – fields and properties have been merged in groovy so that they act and look the same.

Rather than creating a private field for salutation and writing a getter and setter, we can simply declare it as a property without any explicit access modifier. When groovy is compiles to byte code, following rules will apply;

  • If the data member is declared with an access modifier (public, private or protected) then a field is generated.
  • A data member declared with no access modifier generates a private field with public getter and setter (i.e. a property).
  • If a property is declared final the private field is created final and no setter is generated.
  • You can declare a property and also declare your own getter or setter.
  • You can declare a property and a field of the same name, the property will use that field then.
  • If you want a private or protected property you have to provide your own getter and setter which must be declared private or protected.

Note that properties need some kind of identifier: e.g. a variable type (String)

Based on these rules, our salutation property will be just String salutation, nothing more. A private field and associated getter and setter will be provided by Groovy automatically. For calling setSalutaion("Hello"), you need to write hello.salutation = "Hello", and for getSalutaion(), simply hello.salutaion. This also means that you can call getSalutaion() and setSalutaion("Hello") from a Java program(invoking our Groovy class) too.

As we move further in our java code, we have a public method greet ahead which receives a String parameter and returns a String as well. In java, there has to be a return statement if your method has the return type.

The return statement is optional in Groovy, it return the last statement of the method as return type.

But you can put it if you like to put. In our code, we can remove return keyword from the greet method. As you remember we already remove public modifier from each of our methods earlier, now code looks simpler and easy to read and understand.

There is another very nice feature that we can apply on this method and that is Groovy’s special string.

The GString, you can embed expressions inside strings.

Inside a normal string, you can put some place holders delimited with curly-brasses like ${someVariable} or just a dollar sign ahead like $someVariable, that will be replaced automatically by the value of the variable or expression when the string will be used. So you don’t need to bother about manually concatenating strings.

Java is a strongly typed language; whereas groovy,

Dynamic and static typing is supported – so you can omit the type declarations on methods, fields and variables.

Thus we can get rid of all the types if we wish so, and even don’t mention types with arguments of methods. For dynamic type variables there is a def keyword that we can use to define different properties/variables. Here we can change all String declarations to def and also can omit argument type in our greet method.

At this level we are almost done with the greet method. As we learned in the last post, groovy is a scripting language as it allows you to write some free form programs that don’t require you to define a class structure. So we don’t need main method and use just the code as script in groovy outside class.

  1. class GreetWorld {
  2. def salutation
  3. def greet(name) { "$salutation ${name}!" }
  4. }
  5. def hello = new GreetWorld()
  6. hello.salutation = "Hello"
  7. println hello.greet("Groovy")

Voila! It’s really neat and handsome piece of code that is very easy to understand.

Last but not Least

At the end we recap all in few points to summarize as a feature list that we learned in this post.

  • Support properties – fields and properties have been merged in groovy so that they act and look the same.
  • The return statement is optional in Groovy, it returns the last statement of the method as return type.
  • The GString, you can embed expressions inside strings.
  • Dynamic and static typing is supported

Where to go next

You can get more familiar with groovy, some advance concepts in the next part.

« Previous PageNext Page »

Blog at