Saturday, September 9, 2023

10 Differences between Java and Groovy Programming - Examples

If you are working in Java, you might have heard about Scala, Groovy, and Closure. Out of these three Groovy seems to be gaining a place in Java projects more rapidly than others. Groovy is a Scripting language but runs on Java virtual machine. Every Java program can run on the Groovy platform. As per the official Groovy website, "Apache Groovy is a powerful, optionally typed and dynamic language, with static typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax". I think they have highlighted the key capabilities of Groovy very well in that sentence.

It basically further reduce the burden from Java developer with respect to coding. Now, you can put more focus on business logic and get your work done quickly without wasting time on writing more code.

In this article, I'll introduce some of the most fundamental differences between Java and Groovy. For some of you, these differences might be trivial but a Java programmer starting with Groovy will give him a good idea about what to expect in Groovy.

The general feedback I have received from Java developers who also use Groovy is quite positive, especially for small tasks e.g. dynamically generating config files, template-based programming, testing using Spock framework, and so on.

This list is by no means complete, in fact, it's the most basic list of differences between Groovy and Java you will ever find. If you want to contribute or highlight some other differences, please, feel free to leave comments, those will be very useful to a Java developer learning Groovy.

And, If you are new to Groovy world then I also recommend you go through The Complete Apache Groovy Developer Course on Udemy to learn Groovy in a better and more structured way. This is one of the best and up-to-date courses to learn Groovy online.  It's also very affordable and you can buy this course for just $10 on Udemy sales which happen every now and then.





Groovy vs Java - Difference between Java and Groovy

Even though Groovy generates bytecodes similar to Java and runs on JVM, can use the existing Java library, the programming style and capabilities are very different than Java programming language. Once you start writing code in Groovy, you will notice how easy it is to do something in Groovy than Java. Anyway, here is my list of 10 basic differences between Groovy and Java programming languages.


1. Access Modifiers

In Java by default access modifier is package i.e. if you don't specify access modifier for fields, methods, or class it becomes package-private, on Groovy things are by default public. It means a method without any access modifier is public and accessible outside of class and package boundaries.


2. Getters and Setters

In Java, you need to provide getters and setters method for fields, especially if you are following Java Beans naming convention and use tools and libraries, which uses Reflection to dynamically access and mutate bean properties. In Groovy, getters and setters are automatically generated for class members.


3. Super Set

Groovy is a superset of Java, which means a Java program will run fine in the Groovy environment, but vice-versa may or may not run, depending upon whether it’s written in groovy or Java.

Btw, here is a nice image that perfectly highlights the productivity difference between Java and Groovy:

Difference between Groovy and Java



4. Utility methods

In order to make things concise, Groovy has provided several utility methods e.g. to print something on the console, instead of using System.out.println, you can simply use println(). See Groovy in Action to learn more about optional things in Groovy which are mandatory in Java.


5. Variable Substitution

Another key difference between Groovy and Java is that groovy supports variable substitution using double quotation marks with strings i.e. you can print dynamic content without using string concatenation e.g.

println("Good morning $name !");

will include the value of the name variable, which can be either local or a member of the class. This is quite useful for writing scripts where you can use environment variables.


6. Dot Operator

There is a difference between Java and Groovy on handling dot (.) operator. Java uses the dot operator to access properties and groovy also support dot operator but unlike Java calls actually go through getters and setters, which are automatically generated in groovy. For example

   Greetings greet = new Greetings();
 greet.message = 'Good Morning';

will call mutator setMessage(String message) from the Greetings class.


7. Type information

One more key difference between Java and groovy is specifying type information. Typing information is mandatory in Java but optional in Groovy. In Groovy language instead of specifying a type, you can just use the keyword def as shown below.

The use of def is mandatory for methods, but it is optional for method arguments. You can also use def with class and method variables to avoid specifying the exact type. In this example, we have used def in place of the type for the method return type, specifying the type for variable and we have not specified any type for method argument as well, this program will not compile in Java but runs fine in Groovy.

class Greetings {
    def greet(name) {
        println("Good morning $name!");
    }

    static def main(args) {
        Greetings morning = new Greetings();
        def name = 'James';
        morning.greet(name);
    }
}

See Programming Groovy 2: Dynamic Productivity for the Java Developer for many such tips, which can drastically improve your productivity.

differences between Java and Groovy Programmming


8.  Semicolons

The next difference between Java and Groovy is related to semicolons. In Java, every statement ends with a semicolon but in Groovy it's not required. The use of semicolons is totally optional in Groovy though I prefer to use semicolon because of programming in Java for so long, I used to treat semicolons as the end of the statement. If you are in a hurry and want to save a few keystrokes, you are free to avoid semicolons.


9. Execution Path

In Java, you need the main method to make a class executable, in Groovy you don't need that. Since Groovy is a Scripting language, there's automatically a wrapping class called Script for every program. This means you can get rid of your own wrapping class, as well as the main method, like so:

def greet(name) {
        println("Good morning $name!");
}
def name = 'Steve'
greet(name)

This code will be wrapped by Script class so that it can be executed inside a Java virtual machine.


10. Syntax difference

There is some syntax difference between Java and Groovy as well, for example In order to create and initialize a String array in Java, you can curly braces e.g. {"ABC"} but in Groovy, you need to use square bracket e.g. ["ABC"]. Here is how to create a static array in Java and Groovy:

In Java:
String[] currencies = {"GBP", "USD", "JPY", "EUR", "INR} ;

In Groovy
String[] currencies = ["GBP", "USD", "JPY", "EUR", "INR] ;

Note the difference, in Java, array elements are enclosed with braces e.g. "{ }" but in Groovy we have used brackets "[ ]". Also worth noting that under the hood, this code is no longer creating an array; rather, Groovy is (invisibly) creating an ArrayList. This gives us a number of new options e.g. names.sort(), very useful.


That's all about the basic differences between Java and Groovy.  Java and Groovy are both popular programming languages, but they differ in several significant ways. Firstly, Java is statically typed, requiring explicit type declarations, while Groovy is dynamically typed, allowing flexible type inference. 

Groovy boasts a more concise and expressive syntax, with optional semicolon usage for enhanced readability. It excels in meta-programming, enabling runtime code generation and modification, a feature Java lacks. Groovy supports scripting, simplifying task automation, whereas Java doesn't have built-in scripting support. 

While Java is statically compiled, Groovy offers optional static compilation for improved performance. Groovy provides graceful null handling, and its closures and lambda expressions are more concise. Lastly, Groovy integrates seamlessly with Java, allowing coexistence and incremental migration of codebases.

The best part is that both can live together on the same project. I have seen projects where Groovy is used to automate build systems, providing dynamic configuration and testing.


Further Learning
The Complete Apache Groovy Developer Course
Groovy Fundamentals
Introduction to Grails

Other Java articles you may like
  • Differences and similarities between Scala and Java (see here)
  • 5 Free Scala Programming books for Java developers (see here)
  • Java vs Python - which language is better to start with? (read more)
  • 10 Articles Every Programmer should read (see here)
  • 10 tips to become a better software developer (see here)
  • Difference between Java and JavaScript (see here)
  • Difference between an average and good programmer (read more)
  • 5 books to improve your coding skill (see here)
P. S. - The popular, Spock testing framework is also built on Groovy and it's slowly getting adopted by Java developers too. If you are interested in learning Groovy I suggest reading Groovy in Action, the most comprehensive book on Groovy for Java developers.

11 comments:

  1. I donj't think we can use groovy to do complete project

    ReplyDelete
    Replies
    1. You'll obviously need to decide for yourself but I haven't found many projects in the last 5 years that I couldn't convert completely to Groovy.

      Delete
  2. A friendly note: you have missed the last quotation mark in:
    String[] currencies = {"GBP", "USD", "JPY", "EUR", "INR} ;
    String[] currencies = ["GBP", "USD", "JPY", "EUR", "INR] ;

    ReplyDelete
  3. One of Groovys main selling points is that you don't have to convert everything to Groovy. You can use just about any JVM(java,scala, clojure) library from Groovy. If you have some Java that you don't want to mess with leave it in java can call it from Groovy.

    Also Groovy is optionally, but strong typed. While writing Groovy, if I have some variable that I know is going to be a string, I mark it as a string, but I still have the flexibility to take advantage of dynamic features. There are also annotations that can be set at the class/method level to do static vs dynamic compilation. This gives you the ability to optimise in the places that you need it. While in practice you should use these annotation when you need it, i.e. don't prematurely optimise.

    One particular Groovy project Grails, specifically in version 3, is just Spring Boot with some conventions, a plugin system, some config DSLs, and Gradle for building, to make development easier/faster.

    Another project Ratpack(for micro services), is a Java project, but is often used from Groovy, because there is a nice DSL that makes it easier to use.

    Now while I would strongly suggest you really learn what Groovy has to offer before starting to use it, you can do an iterative approach where you convert parts of a project to Groovy, and make you code Grovier over time. You can take a .java file rename it to a .groovy file, and it will probably just run out of the box. There are a few corner cases like where == in Groovy is .equals() from Java, polymorphism is slightly different(see multi methods), and Groovy has its own version of the truth(0 == false, "" == false, [] == false, [:] == false, null == false, 1 == true, "non empty string" == true, [1,2,3] == true, [key1 : "value1", key2:"value2" == true)

    ReplyDelete
  4. @Aulo, you are right, there should be a double quotes to cover String "INR".

    ReplyDelete
  5. @virtual Dogbert, that's they many organization is using Groovy e.g. for tooling, creating dynamic build and testing.

    ReplyDelete
  6. You missed everything about closures...you haven't specified that curly brackets in groovy are used for closures

    ReplyDelete
  7. @Anonymous, yes, covering everything in 10 points is difficult, will write about that in another article. Thanks anyway.

    ReplyDelete
  8. Thanks that's just a great concise read for me who needs/wants to use groovy being a java dev for the last 15 years

    ReplyDelete
  9. Thanks for writing this. My personal take is that groovy will save you a lot of time up front and then hurt you down the line. All of the things that are important about good object class development are just thrown out the window with groovy. Some of the features would be great with java such as better containers and iterators... but honestly not worth it unless you are throwing together a short program. Not sure I would want to go through the effort to formally create a class and then access all the variables as though they weren't even in the class, and then have the potential to break any contract the class writer intended... and break compatibility with that class down the line.

    I will endeavor to understand groovy as an important tool for using things like gradle, but it's nowhere near as strong a language as Java.

    ReplyDelete