Prelude to Groovy
"Software is eating the world" a famous quote declared by Marc Andreessen and now we are in the
digital era where everything gets simpler. People love handy things which would serve their purpose
in quick turn around time.
Groovy is one such object-oriented programming language on Java platform which improves the
performance thereby reducing time.
Groovy has adopted many dynamic features inspired from different programming languages.
Groovy : An Overview
Let us see what Groovy is?
In General, Groovy means Exciting. So, it is.
Let us first know few definitions and its usage.
Groovy achieves its agility and dynamicity by performing a lot of work in background.
Groovy harnesses the power of the Java platform by utilizing the extensive list of libraries Java has.
Groovy being OOPs language for the Java platform, is compiled to byte code which is executed by the
Java Virtual Machine (JVM).
Cool features of Groovy:
Simplicity
Dynamicity
Flexibility
Performance
Stability of the JVM
Let's understand how Groovy carries these cool features in-detail.
Why Groovy...
Here are some of the features of Groovy which a JAVA developer can consider adapting to it.<br>
Blocks and Closures: Groovy provides "Blocks and Closure", a powerful feature which JAVA lacks.
Sugar Syntax: Groovy is less verbose than Java.
Ex: To get a file contents, single line of groovy is sufficient as against multiple lines of code in Java
new File('C:\Temp\sample.txt').getText()
Wrappers: Groovy has basic java functionalities with excellent wrappers around it.
For example, in Groovy, with SwingBuilder class only a few liner script is required whereas, Java
requires several lines of code to initialize, build UIs, write an actionListener etc.
Groovy Basics - First Groovy Programming
Let's get started with first groovy program “Hello World”.
It is as simple as given below.
println (“Hello World”)
You will learn about the
data type
operators
language elements in the next section.
Benefits of Groovy
Groovy requires only one-third of code written when compared to lines of code in Java.
Let's check some more benefits of Groovy
No need to remember many syntaxes as Groovy take care of this.
Reduced manual-effort of writing code.
Time-saving.
Increased productivity.
More on Java vs Groovy
Groovy has General purpose packages and classes imported by default, whereas Java has Java.lang
package that exists by default.
Groovy uses '==' to compare both primitive type and object type, whereas Java uses '==' to compare
only primitive type.
In Groovy, 'in' is a keyword and it cannot be used as a variable name, whereas Java doesn't have a
keyword 'in'
In Groovy Arrays are created using [], whereas in Java Arrays are created using {} block.
';' (Semicolon) usage is not mandatory in Groovy, whereas it is mandatory in Java.
Java program will run fine in Groovy, whereas Groovy program will not run in Java
All methods and classes are public by default in Groovy, whereas 'public' key word has to be added in
Java to make them public.
Below are some of the application areas where Groovy is being used heavily.
Spring Framework
Database Access
RESTful Webservices
Building and Testing Web Applications
Build Automation tools (Gradle)
Installing Groovy
Let us try installing groovy on an Ubuntu environment. You will be using Katacoda Ubuntu
playground for the same.
Let us execute the following 2 steps
sudo apt-get update
sudo apt-get install groovy
Once the setup is done successfully, try checking the version to confirm on groovy availability.
groovy -v / groovy -version
Now you are all set to code in groovy.
Groovy is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk.
Groovy supports a wide range of data types. They are categorized as Simple Data Types and
Collective Data Types.
Here are some of the important simple data types of Groovy.
byte: a numerical data type, Range -(-2^7) to (2^7-1).
short: a numerical data type, Range -(-2^15) to (2^15 -1).
int: a numerical data type, Range -(-2^31) to (2^31 -1)
long: a numerical data type, Range -(-2^63) to (2^63 -1).
Examples: int x = 10; long a = 10L;
Groovy - Data Types (cont....)
float: a numerical data type with 32-bit floating point numbers. , Range -(-3.4E+38) to (+3.4E+38)
double: a numerical data type with 64-bit floating point numbers, Range -(-1.7E+308) to (+1.7E+308)
char: a single character data type. Example-‘x’.
String: a data type with a group of characters.Example-“Hello World”.
Boolean: a data type representing a Boolean value which can either be true or false.
Collective datatype includes
Lists
Maps
Ranges
Dates and Times
A list is a structured collection of data.
The list elements are enclosed within square brackets.
Here is an example of defining a list in Groovy.
def empId = [321, 345, 897]
def empName = ["Peter", "Raja", "Anne"]
Below are some of the list methods available in Groovy.
add(), get(), contains(), reverse(), sort(), size()
A map is an unstructured collection of data.
Each element in the map will be mapped to a key.
Below is an example for a map.
def empDetails = [Name : Sam, Id : 1234, Age : 28, 'Date of Birth':11-Aug]
NOTE: If a map element contains space as in the above example, it should be placed within single
quotes.
Some methods used in map are
containsKey(), get(), keySet(), size(), values()
Ranges are lists of sequential values.
To create a range, ".." operator is used.
Below is an example for a range, which contains the list of 1 to 100.
def indexes = 1..100
Some of the methods in ranges are
contains(), get(), getFrom(), getTo(), size()
The Class Date in Groovy specifies the instant date and time.
Following is the example to print the current date and time.
Date date= new Date()
println(date.toString())
Below are some of the methods of date and time.
after(), equals(), toString(), getTime(), setTime()
Operators
Following are the Operators used in Groovy:
Arithmetic Operators *(+, -, , /)
Relational Operators (<, > ,<=, !=)
Logical Operators (&&, ||, !)
Bitwise Operators (&, !)
Assignment Operators *(+=, -=, =, /=, %=)
Object Operators
Groovy is Superset of JAVA
Object Operator
The . operator is called the Object Operator.<br>
This is used to set and get an object and to call a method in Groovy.<br>
Below is an example.<br>
def employee1 = new employee()
employee1.name ="Sam"
Classes & Scripts
Groovy Class:
The class declaration in Groovy looks similar to JAVA. By default, a Groovy class will be declared as
public.
Below is an example for a Class in Groovy.
Class MyClass
static void main(String[] args)
println("Hello World")
Classes and Scripts (cont...)
Script:
When a Groovy code is not enclosed in a class declaration, it is considered as a Script.
The code shown in the previous card is equivalent to the below script.
println("Hello World")
While compiling, the script will be compiled as a class. So during the script execution, it is copied to
the run() method. It would be compiled as below.
import org.codehaus.groovy.runtime.InvokerHelper
class Main extends Script
{ def run()
{println("Hello World");
static void main(String[] args) {
InvokerHelper.runScript(Main, args)
Optional Typing
Optional Typing is a feature of Groovy which allows types to be declared for fields, parameters and
methods.
This is used for interacting with statically typed languages such as Java.
When Java calls Groovy code, there is no need to map everything to its real type to use it.
In the below code, the variable is not defined, Groovy declares the variable types automatically.
def x = 5
def y = "Hello World"
println(x.getClass())
println(y.getClass())
The output of the code is
class java.lang.Integer
class java.lang.String
In Groovy, there is no need to specify types of parameters while declaring a parameterized method.
Properties
A property is a combination of a private field and getters/setters. You can define a property with:
No access modifier
one or more optional modifiers (static, final, synchronized)
an optional type
a mandatory name
Groovy will generate the getters/setters appropriately. <br>
Let us have a look at the example.
class Person {
String name
int age
p=new Person()
p.name="Sam" //*setname is implicitly called
p.age=30 //**setage method is implicitly called
println p.name //*getname method is implicitly called
println p.age //*getage method is implicitly called
NOTE: If you have a reference to a property name that doesn’t appear to exist, it might be invoking a
getter method by default.
Multimethods
Multi-methods is one of the features of Java and Groovy as well. The difference is the way they
invoke methods.
Java invokes during compile time.
Groovy invokes during runtime.
For example,, look at the code below.
class MultiMethod
{
int multiMethod(String arg){
println ("This is a string")
return 0
int multiMethod(Object arg){
println ("This is an Object")
return 0
public static void main(String[] args) {
MultiMethod sample = new MultiMethod()
Object obj = "object"
sample.multiMethod(obj)
If we run the code on Java and Groovy,
Java gives the output as This is an object and
Groovy gives the output as This is a String.
Groovy is smart!!
Control Structures
Groovy handles the if/else, for/in loop syntaxes and switch statements similar to JAVA.
if-else:
Groovy supports normal if-else and nested ifs. Below are some examples.
normal ifs
int z=11
if(z==11)
println("The answer is 11")
else
println("The answer is not 11")
nested ifs
int a = 12
if (a<100) {
println("The value is less than 100");
else if (a>100) {
println("The value is greater than 100");
} else {
println("The value is equal to 100");
Switch Statement
Below is a basic example of Switch case.
int x=100
switch(x)
case 100:
println("The value is 100")
break;
case 200:
println("The value is 200")
break;
case 300:
println("The value is 300")
break;
default:
println("The value is unknown")
break;
Groovy Switch case can also be used
to match range of values
with regular expressions
to match the class
While Statement
In while statement, the condition would be evaluated first and the statement would be executed
next.<br>
The loop will terminate when the condition of the while statement fails.<br>
Below is an simple example.<br>
int count = 0
while(count<5)
println(count)
count++;
FOR Loop
For loop is used when a task is to be repeated n number of times.
Here is a basic example.
for(i=0; i<5; i++)
println i
For Loop has the following 3 parts.
Variable declaration is used to declare any variable which will be used in the loop.
Expression section will consist of an expression which will be evaluated for each iteration of the loop.
Increment section will contain the logic needed increment for the declared variable.
For in Loop
For in statement is used to loop through lists, ranges and maps.
<br><br>
Here is an example where for in loop is used with maps.
def map = [p1:'q1', p2:'q2']
for ( item in map )
println (item.value +" is mapped to "+item.key)
A Groovy method can be defined either with return typeor with the def keyword.
Following is an example of a simple Groovy method.
class Method {
static def DisplayName() {
println("This is an example of a simple method");
static void main(String[] args) {
DisplayName();
Defining Methods (Cont...)
Both typed and untyped arguments are accepted in Method signatures.
// untyped arguments
def sMap(argu1, argu2) {
return [argu1: argu2]
// typed arguments
Map sMap(String argu1, String argu2) {
return [argu1: argu2]
It is optional to use “return” statement. The last evaluated expression value is returned by default.
def asMap(argu1, argu2) {
[argu1: argu2]
Defining Methods (cont...)
Methods are defined to accept named parameters using “Map” keyword.
def myMethod(Map person) {
"$person1.fName, $person1.lName"
Default values for Parameters can be defined in methods. The default would be used if the
parameter is not passed.
def person(fname, lname, mname = "") {
"Welcome, $fname $mname $lname"
}
def greetGanga = defaultParams("Ganga", "Cauveri", "Tapti")
def greetKrishna = defaultParams("Yamuna", "Krishna")//mname is not passed and hence default
would be used.
All defined methods are public by default.
Calling methods
The main concept which we should follow when using the Method in Groovy is that, Methods that
do not accept any parameters must include the parentheses.
<br>
def myMethod1() {
// ...
def myOtherMethod2(someArgu1, someArgu2) {
// ...
myMethod1() // OK
myMethod1 // error
myOtherMethod2(2, 3) // OK
myOtherMethod2 4, 5 // OK
In Groovy, we are always free to handle exceptions if we want or disregard them.
Groovy does not require you to handle so-called checked exceptions
To handle general exceptions, you can place the potentially exception-causing code in a try/catch
block:
By not declaring the type of exception we can catch, any exception.
Exception Methods available in Groovy
public String getMessage()
public Throwable getCause()
public String toString()
public void printStackTrace()
public StackTraceElement [] getStackTrace()
public Throwable fillInStackTrace()
Exception Handling (cont...)
Here is an example for exception handling.
Here the code is accessing an array whose index value is greater than the size of the array. We have
written try/catch block to handle the exception.
class Example {
static void main(String[] args) {
try {
def arr = new int[3];
arr[5] = 5;
} catch(Exception ex) {
println("Exception Occured");
println("We will move on after the exception");
Standard JAVA code is used in Groovy for I/O operations.
Many helper methods are provided which is very convenient to handle files.
Easier classes are available to handle the following functionalities in Files.
- Reading Files
- Writing into Files
- Traversing file Trees
- Reading and writing data objects to File
File I/O (cont...)
Groovy Methods are added to the following JAVA classes which take care of I/O functions.
java.io.File
java.io.InputStream
java.io.OutputStream
java.io.Reader
java.io.Writer
java.nio.file.Path
Let us look at an example of one built-in method ‘eachLine’ of File Class in Groovy.
This method is used to print all the lines in the file. It can also mention the line number if required.
The following sample clearly explains it.<br>
import java.io.File
class Sample {
static void main(String[] args)
new File("E:/Sample.txt").eachLine
{
line, nb -> println "line : $line";
Groovy provides multiple methods to traverse a file tree in order to find some specific files.
The below sample code helps to print all the file name in the directory.
dir.eachFile {
file ->
println file.name
java.io.InputStream and **java.io.OutputStream**Classes are used to read and write data objects to
a file in Groovy.
Below is a sample code:
Person p = new Person(name:'Bob', age:76)
file.withObjectOutputStream { out ->
out.writeObject(p)
file.withObjectInputStream { input ->
def p2 = input.readObject()
assert p2.name == p.name
assert p2.age == p.age
}
As you all are aware, XML is a portable language which helps to create an application that is used for
exchanging data between applications.
Groovy language provides good support of the XML language. The two XML basic classes used are
XML Markup Builder – This is used to create an XML document.
XML Parser– This is used to read an XML document.
How it works?
XML document is parsed by an object of the class XmlParser
Parser is provided with information of XML file location
Groovy supports different databases and some are listed here.
HSQLDB
Oracle
SQL Server
MySQL
MongoDB
The following Operations can be done using Groovy.
Database Connection
Creating Database table – Insert, Read, Write & Delete Operations
Performing Transactions
Commit and Rollback Operations
Disconnecting Databases
Integrating Applications with Groovy
Integrating Groovy with Java is easier on the existing projects.<br>
Here are some examples where Groovy is integrated into applications.<br>
A banking application required a definition of business rules in a script. Using Groovy, this is defined
at run time without a new development and testing which reduced the time to market and increases
the responsiveness to changes in financial practices.<br>
An office suite of applications offered a macro system to create reusable functions that could be
invoked with a keystroke.
The image depicts an example of an integration solution.
Any request/response entered by user in the UI layer gets executed in the business layer.
NOTE: Groovy shell is a command-line application that helps in evaluating
Groovy expressions
Functions
Define classes
Run Groovy commands.
Unit Testing in Groovy is a built-in Class and it does not require any separate framework as it already
includes JUnit (Java Unit Testing Framework)
Groovy Unit Testing does not affect the production in run time and code is easier to read and
maintain.
JUnit Testing is performed by creating a class which inherits from test case. GroovyTestCase is the
class to be used to extend for Groovy Unit Testing.
GroovyTestCase is found in the groovy.util package. As it is implicitly available, it does not require any
imports.
Course Summary
Hope you enjoyed this course and had great learning !!!
To summarize, you have learned
Groovy Installation
Datatypes and Operators
Control Structures
Methods and Exception Handling
File I/O Operations
Applications of Groovy
In the next course on Groovy, you get to know more about
MOPping and MetaProgramming
In depth Working with XML
Database Development
Testing