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 Groovy is a superset of Java.
Groovy is not only based on Java, but it also it combines the power of other languages such as Python, Ruby, and Smalltalk. With these powers, Groovy provides more opportunities than Java.
This handbook section describes the most common differences between groovy Groovy and javaJava.
Differences
...
Area | Groovy | Java |
---|---|---|
Default imports |
|
Java
All other packages have to be mentioned clearly to import them into java class file |
Extra |
...
keywords |
|
...
|
...
In Java we cannot use these keywords. | |
Default access modifier |
Groovy
Default access modifier is public i.e. if you don’t specify access modifier for fields, methods or |
...
classes, it becomes package-private. |
Java
Default access modifier is package. |
Getters and |
...
setters |
Groovy
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 |
Groovy
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.:
|
Java
There is only one way to declare |
...
a loop:
| ||
Safe |
...
Groovy
...
navigation operator | Safe Navigation Operator (?.) is used to avoid a NullPointerException.
|
Java
We have to perform some operation to check the null object, to avoid null pointer exception.
| ||
The |
...
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. |
...
...
|
...
|
...
|
...
|
...
|
...
|
...
Curly braces have to be used |
...
. |
...
|
...
|
...
|
...
|
...
|
...
|
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. |