Groovy vs. Java

Introduction

Groovy is a powerful, optionally typed and dynamic language to develop an application on Java Platform where its syntax is Java-like. The syntax of Groovy is similar to Java. By extending JDK, it can accept Java code. Groovy is not only used as a programming language but also as a scripting language. Java programs can run in the Groovy environment because Groovy is a superset of Java.

Groovy is not only based on Java, but it also combines the power of other languages such as Python, Ruby, and Smalltalk. With these powers, Groovy provides more opportunities than Java.

This section describes the most common differences between Groovy and Java.

Differences

Area

Groovy

Java

Area

Groovy

Java

Default imports

  • java.io.*

  • java.lang.*

  • java.math.BigDecimal

  • java.math.BigInteger

  • java.net.*

  • java.util.*

  • groovy.lang.*

  • groovy.util.*

  • java.lang.*

All other packages have to be mentioned clearly to import them into java class file

Extra keywords

  • as, define, trait are extra keywords

In Java we cannot use these keywords.

Default access modifier

Default access modifier is public i.e. if you don’t specify access modifier for fields, methods or classes, it becomes public.

Default access modifier is package.

Getters and setters

Getters and setters are automatically generated for class members.

You need to provide getters and setters methods for fields, especially if you follow Java Beans naming convention and use tools and libraries, which uses Reflection to dynamically access and mutate bean properties.

Semicolons

Semicolons (;) are optional, use them only if you like or if you want to write more than one statement in one line.

Semicolons are mandatory at the end of a line.

For loop

Groovy loop declaration is much easier, e.g.:

for(j in 0..4){ print j } 0.upto(3) { print "$it" } 4.times{ print "$it" }

There is only one way to declare a loop:

for(int i=0;i<=5;i++){ System.out.println(i); }

Safe navigation operator

Safe Navigation Operator (?.) is used to avoid a NullPointerException.

String str = null; println str?.reverse()

We have to perform some operation to check the null object, to avoid null pointer exception.

The main() method

Groovy is a scripting language, there’s automatically a wrapping class called Script for every program.

Main method is needed to make a class executable.

Array declaration

Square brackets can be used.

String[] testArray = ["A", "B", "C"]

Curly braces have to be used.

String[] testArray = {"A", "B", "C"};

Data types

Everything is an object and uses only object, hence no concept of autoboxing or unboxing.

Primitive data types and wrapper classes to perform boxing and unboxing implicitly or explicitly.

 

Found an issue in documentation? Write to us.