DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Languages
  4. From Java to Groovy in a Few Easy Steps

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.

Guillaume Laforge user avatar by
Guillaume Laforge
·
Jan. 27, 08 · Opinion
Like (3)
Save
Tweet
Share
119.88K Views

Join the DZone community and get the full member experience.

Join For Free

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!

Groovy (programming language) Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is API-First?
  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • Introduction to Automation Testing Strategies for Microservices
  • Key Elements of Site Reliability Engineering (SRE)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: