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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Clean Unit Testing
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling

Trending

  • 5 Best Node.js Practices to Develop Scalable and Robust Applications
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • The Transformative Power of Artificial Intelligence in Cloud Security
  • On-Call That Doesn’t Suck: A Guide for Data Engineers
  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.

By 
Guillaume Laforge user avatar
Guillaume Laforge
·
Jan. 27, 08 · Opinion
Likes (3)
Comment
Save
Tweet
Share
121.3K 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.

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Clean Unit Testing
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!