Groovy Tutorial

Just like humans have different languages to communicate with each other, programmers need a language to communicate with the computer. The languages that are used by the programmers to communicate with the computer are called programming languages. Nowadays, we can find various programming languages that have been emerging. The main objective of these languages is to help the programmers to make the addition of new features to the product. An interesting language that has emerged whose syntax is like Java is Groovy. In this blog, let us learn about Groovy, the importance of Groovy, features of Groovy, History of Groovy, prerequisites, Installation steps and many other concepts of Groovy. So, Without further ado, let's get started.

Groovy Tutorial - Table of Content

What is Groovy? 

Groovy is a java-based object-oriented language. This is a static and dynamic language. Groovy has the same functionality as Python, Perl, Ruby and Smalltalk, and it can be used as a programming language as well as a scripting language for a Java platform. Groovy possesses a number of productive functionalities such as dynamic input, DSL support and closures. In contrast to other programming languages, Groovy may not be used instead of Java. Groovy's source code is consistent with Java Bytecode. Therefore, it can be executed on any platform on which JRE is installed.

  To gain in-depth knowledge with practical experience in Groovy, Then explore HKR'S Groovy Training !

Why is Groovy?

Groovy is a powerful language that fits perfectly with any Java program. This is also an excellent scripting language with a powerful syntax that can be easily learned. It is designed to enhance developer productivity with a familiar, brief, and easy-to-learn syntax. It easily integrates into any Java program and instantly delivers powerful features to your application, including scripting capability, compile-time and runtime metaprogramming, as well as functional programming and domain-specific language authoring.

Features of Groovy:

Following are some of the features of Groovy:

  • Groovy supports both Static and dynamic typing
  • It has familiar, brief and easy-to-learn syntax.
  • The learning curve is quite short
  • Support for regular expressions
  • Support for domain-specific languages
  • Support for unit testing
  • Support for markup languages such as HTML and XML
  • The native syntax for associative arrays and lists.

Prerequisites : 

In order to learn Groovy, we need to have some hands-on experience in Java or some basic knowledge of object-oriented programming language.

Install Groovy on Windows operating system:

Following are the steps to be followed to install Groovy on Windows Operating system:

1. In order to install Groovy, we need Java installation in our OS. If Java is already installed in your OS then check for the version of Java. Groovy needs java version 8.1 or above for its installation. 

2. Then go to the website https://groovy.apache.org/ and click on the download tab.

Windows operating system

3. Under distributions you can find the windows installer option. Click on it.

windows installer option

4. After that go to downloads and click on the groovy installer, it will start installation.

groovy installer

5. Select the language and click ok.

groovy 1

6. Then the Installation wizard appears. Click on the next button.

welcome to groovy 6

7. Then click on the I agree button on the License Agreement Window.

7 groovy

Then click on the next button.

8. Select the destination folder where you want Groovy to be installed.

Groovy 8 image

9.Then click on the install button. The installation will be started.

groovy 9

groovy 9A

10. Then a message “Set up was completed successfully” will be displayed when the installation is completed.

Groovy 10

11. Check create GROOVY_HOME, Add to Path and Add to System Environment by setting here, the path will be automatically defined in an environment variable. Then click on the next button. 

groovy 11

groovy 11A

12. Then click on Finish. Now Groovy is installed in your system.

groovy 12

13. Now make sure that Groovy is installed correctly. So, open command prompt type groovy -v and click enter. Then the groovy installer version is displayed on the command prompt.

groovy 13

14.  If the command prompt is not recognizing the above command then set the path in the environment variable.

Install Groovy on Eclipse

Following are the steps to install Groovy on Eclipse:

1. Make sure that Eclipse is installed in your system.

2. Then go to the website https://groovy.apache.org/ and click on the documentation. In the tools section, you can find IDE integration. Click on that.

Install Groovy on Ellipse

3. You can find the IDE and text editors list that are supported with Groovy. Now click on the Groovy Eclipse Plugin.

Groovy Eclipse Plugin

4. Then you will get the GitHub page for “Groovy Eclipse”. Go to the documentation section. In the users section click on “wiki”.

wiki

Groovy Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

5. Under the Release section, there will be links to install Groovy in your eclipse. Two methods can be used for installing Groovy in your eclipse.

A. Directly installing the software through the link on Eclipse:

1. In Eclipse, go to Help.

go to Help

2. Now click on the option “install new software”.

install new software

3. Now copy the Groovy link(from the website) and paste it into the work with, and press Enter.

releases

releases 2a

4. Then select the options and click on next. Then the groovy support will be installe

groovy installing software

B. Installing groovy on Eclipse as follows:

1. In Eclipse, go to Help.

go to Help

2. Click on the Eclipse Marketplace.

Marketplace

3. In the Find section type “Groovy” and press enter.

press enter

4. You will now obtain the most recent version of Groovy. Click on the install button.

install new button4

5. Then click on the confirm button. 

6. Now Accept the license agreement and click on the finish button.

license agreement

7. Then restart the Eclipse IDE by clicking on the Restart button.

Eclipse IDE

8. Now, you need to check if Groovy is installed. In Eclipse, go to help and click on the marketplace. Now click on install. Groovy will be installed. 

if Groovy is installed

Groovy Basic Syntaxes:

The following conditions are applicable when writing a groovy program:

  • In groovy, you do not need to put a semicolon at the end of the statement as in java.

Syntax: 

package com.app  

  class Example {  

  static void main(args) {  

print "Groovy Example syntax " 

}  

}  
  • A line may be printed without the use of round brackets.

Syntax: 

print "Groovy Example syntax " 
  • Both double quotes and single quotes are used in a string.

Syntax: 

print ‘SINGLE QUOTE Example syntax’

print "DOUBLE QUOTE Example syntax " 
  • We can use single line comments and multiple line comments as in Java.

Syntax: 

// this is a single line comment  
/* 

*  

* this is a 

* multi-line comment 

*/  
  • In Groovy, there is no need to have any class or main function.

Syntax: 

package com.app  

print "Welcome to Groovy... "  

Groovy Hello World Example

Writing a Hello World program is very simple in Groovy.

package com.app  

class Example {  

  static void main(args) {  

println "Hello World!" 

// println also prints the output to the console.

}  

}  

When we execute the above program, the output will be:

Hello World!

Groovy Variables:

1. In Groovy Variables can be defined

  • Using native data type syntax
  • Using the def keyword

2. Some of the basic types of Variables in Groovy are byte, short, int, long, float, double, char, string, boolean.

3. For Variable Definitions, we need to provide  a type name explicitly or use “def” as a substitute. This is a requirement for the Groovy Parser.

4. Groovy also supports other kinds of variables like classes, arrays, and structures.

5. Variable declaration informs the compiler where how much storage to create for that variable.

Syntax: 

class Demo { 

   static void main(String[] args) { 

      // a is defined as the variable 

      String a = "Hello";

 

      // The variable value will be printed to the console 

      println(a);

   }

}

When we execute this program the output will be:

“Hello”

6. In Groovy, uppercase and Lowercase letters are different. A Variable name can include numbers, letters and underscore. A variable name can be started with a letter or underscore.

class Demo { 

   static void main(String[] args) { 

      // A variable defined in lowercase  

      int p = 2;

     // A variable defined in uppercase  

      int P = 3; 

     // A variable defined with an underscore in its name 

      def _Name = "Ravi"; 

      println(p); 

      println(P); 

      println(_Name); 

   } 

}

When we execute this program the output will be:

2

3

“Ravi”

Groovy Operators:

An operator is a symbol which indicates the compiler should run particular mathematical or logical manipulations.

Following are some of the operators used in Groovy:

Arithmetic operators:

Arithmetic operators are used to perform arithmetic operations. Some of the examples of Arithmetic operators are +, -, *, /, %, etc.

Relational operators:

Relational operators are used to compare the objects. Examples of Relational operators are ==, !=, <, >, <=, >=

Logical operators:

 Logical operators are used to evaluate the boolean expressions. Examples of logical operators are &&, ||, !

Bitwise operators:

Examples of Bitwise operators are &, |, ^, ~

Assignment operators:

 Examples of Bitwise operators are +=, -=, *=, /=, %=

Subscribe to our youtube channel to get new updates..!

Groovy Loops:

A loop is a sequence of instructions which continuously repeats itself until a given condition is reached. Following are the loop statements used in Groovy:

While Statement:

after evaluating the condition expression, While statement is executed. If the result is true then statements in While loop will execute.

Syntax:

class example_pgm{

   static void main(String[] args) {

      int x = 0;

       while(x<5) {

         println(x);

         x++;

      }

   }

}

When we execute this program the output will be:

0

1

2

3

4

For Statement:

For statement, is used to iterate across a set of values.

Syntax:

class example_pgm { 

   static void main(String[] args) {

        for(int a = 0;a<5;a++) {

         println(a);

      }

 

   }

}

When we execute this program the output will be:

0

1

2

3

4

For-in Statement:

For-in Statement is used to iterate across a set of values.

Syntax:

class Example {

   static void main(String[] args) {

       for(int i in 1..5) {

         println(i);

      }

 

   } 

}

When we execute this program the output will be:

5

Loop Control Statements:

Break statement:

It is used to change the flow of control inside the switch statement and loops.

Syntax:

class demo {

   static void main(String[] args) {

      int[] array = [1,2,3, 4];

       for(int a in array) {

         println(a);

         if(a == 3)

         break;

      }

   } 

}

When we execute this program the output will be:

3

Continue statement:

 It is used to complement the break statement. It will be limited to for and while loops.

Syntax:

class demo {

   static void main(String[] args) {

      int[] array = [1,2,3, 4];

       for(int a in array) {

       

         if(a == 3)

         Continue;

         println(a);

      }

   } 

}

When we execute this program the output will be:

2

4

Groovy Decision Making:

Decision making structures need the programmer to specify some conditions that are to be evaluated by the program. The statements will be executed if the condition is true otherwise the other statement will be executed.

If statement:

A condition will be evaluated and if the condition is true then the statement will be executed.

Syntax:

class demo { 

   static void main(String[] args) { 

      int a = 2 

       if (a<10) { 

 //Below statement will be executed if the condition is true.

         println("This value is smaller than 10."); 

      } 

   } 

}

  When we execute this program the output will be:

This value is smaller than 10.

If - else statement:

Generally the condition in the if statement will be evaluated and if the condition is true then the statements in the if statement block will be executed and exit the loop. If the condition is false then the statements in the else statement block will be executed and exit the loop

Syntax:

if(condition) { 

   statement_1 

   statement_2 

   ... 



else{ 

   statement_3 

   statement_4  

}

Nested If statement:

At times we need several if statements inside each other.

Syntax: if(condition) { 

   statement_1 

   statement_2 

   ... 

} else if(condition) { 

   statement_3 

   statement_4 

} else { 

   statement_5 

   statement_6 

}

Switch Statement:

It is a multi branch statement. It allows you to easily run various parts of the code that are based on the value of the expression.

Syntax:

class Demo { 

   static void main(String[] args) { 

      int p = 2

  switch(p) { 

         case 1: 

            println(" p value is One"); 

            break; 

         case 2: 

            println("p value is Two"); 

            break; 

         case 3: 

            println("p value is Three"); 

            break; 

         case 4: 

            println("p value is Four"); 

            break; 

         default: 

            println("p value is unknown"); 

            break; 

      }

   }

}

When we execute this program the output will be:

P value is Two.

Groovy Strings:

A string is defined as a sequence of characters. In Groovy there are different ways to represent a string literal. So, In Groovy, a string can be enclosed in single quote, double quote and triple quote.

Single quoted string: String will be enclosed in single quote(’)

Syntax: '________Example_String________'  

package com.app  

class GroovyStringExample1 {  

static void main(args)  

{  

        String s1 = 'groovy tutorial'  

        println s1  

     }  

When we execute this program the output will be:

Groovy tutorial

Double quote string: String will be enclosed in double quote(“)
Syntax: "________Example_String________" 

Triple quoted String: String will be enclosed in triple quote(“””). Triple quote strings can also be used for multiple lines within a single variable.

Syntax: '''________Example_String________'''  

Example:

package com.app  

class GroovyStringExample7 {  

static void main(args)  

{  

String s = """ 1st line  

2nd line  

3rd line  

4th line  """  

        println s  

}  

}

When we execute this program the output will be:

1st line  

2nd line  

3rd line  

4th line

Slashy String: String will be enclosed in forward(/). Slashy strings are helpful in defining the regular expressions and patterns where backslashes escape is not necessary.

Syntax: /________Example_String________ /

Dollar slashy string: String will be enclosed in $/ and /$. Dollar slashy strings are helpful in defining the regular expressions and patterns where backslashes escape is not necessary.

Syntax: $/________Example_String________/$ 

Groovy Lists:

In Groovy, A list is a structure used for storing a collection of data items. It includes a sequence of object references. In a list object references occupy a position in the sequence and are separated by an integer index. A literal list takes the form of a series of objects separated by the objects that are placed in square brackets. In order to process data from a list, we need access to individual elements. In Groovy lists are indexed through the [] indexing operator. List indices begin from zero, which corresponds to the first element.

Examples of Lists:

  • List of integers - [1, 2, 3, 4, 5]
  • List of strings - [‘Groovy’, ‘tutorial’]
  • Nested list - [4, 5, [6, 7], 8]
  • Empty list - []

Some of the list methods available in groovy are add(), contains(), get(), plus(), minus(), size(), etc.

Groovy Maps:

In Groovy, Map is an unordered collection of the object references. A key value provides access to the elements in the map collection. Keys used in the Map may belong to any class. When inserting in a map collection, we need the key and the value.

Example: 

[‘Name’ : ‘ABC’, ‘Place’ : ‘Singapore’]

[ : ] - (Empty map)

Map methods available in Groovy are get(), containsKey(), keySet(), put(), values(), size().

Groovy Closure:

In Groovy Closure is an anonymous block of code that usually covers a couple of lines of code. A method may even use the block of code as a parameter. They have an anonymous nature.

Syntax: 

class Demo {
static void main(String[] args) {
def clos = {println "Example for Closure"};
clos.call();
}
}

Here {println “Example for Closure’} is the closure. The code block referred to by this identifier will be executed with a call statement.

When we execute this program the output will be:

Example for Closure

Methods that are used with groovy are find(), any() & every(), findAll(), collect()

Pros of Groovy:

  • Dynamic typing makes it possible to program quicker, most of the time.
  • Currying or partial software allows you to replicate the feature with multiple arguments.
  • Support for tools to obtain helpful APIs by applying @DelegatesTo.
  • Native associative array or key-value mapping support through which associative array literal is generated.
  • String interpolation
  • Regex has first class residents.

Cons of Groovy:

  • The JVM and Groovy script starts slowly, which limits the OS level scripting.
  • Groovy does not have full acceptance in other communities.
  • Using Groovy without the use of IDE is not practical.
  • Groovy may be slower that has lengthened the development time.
  • Groovy can require a lot of memory.
  • Familiarity with Java is a must.

Groovy Tools:

There are three important tools in Groovy scripting.

  • Groovysh
  • GroovyConsole
  • Groovy

Groovysh: 

  • Command-line shell
  • Assists you in executing the Groovy code in an interactive way.
  • Allows you to enter statements or entire scripts.

Groovysh

GroovyConsole: 

  • Swing interface that functions as a minimal Groovy development editor.
  • Gives you the ability to interact with the Groovy code.
  • Allows loading and running the Groovy script files.

GroovyConsole

Groovy: 

  • It runs a groovy script. 
  • This is the processor that runs Groovy programs and the scripts.
  • It is suitable for testing simple groovy expressions.

groovy expressions

History of Groovy:

Groovy was developed by Bob McWhirter & James Strachan in 2003. The Beta version of Groovy was made available in 2004. Groovy 1.0 was released on January 2, 2007, with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0. In 2015, Groovy became a project of Apache Software Foundation.

Groovy Training

Weekday / Weekend Batches

 Conclusion:

In this groovy tutorial, we have learned about Groovy from the basic details like what is Groovy, Why we use Groovy, features, prerequisites of Groovy, Installation of Groovy on Windows Operating system, Installation of Groovy on Eclipse, Basic syntaxes in Groovy, Groovy variables, operators, loops, decision making statements, strings, lists, maps, closures, Groovy tools, Pros and cons of Groovy, and History of Groovy. We hope you found this Groovy tutorial helpful for you.  

Find our upcoming Groovy Training Online Classes

  • Batch starts on 1st Jun 2022, Weekday batch

  • Batch starts on 5th Jun 2022, Weekend batch

  • Batch starts on 9th Jun 2022, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Kavya Gowda
Kavya Gowda
Research Analyst
Kavya works for HKR Trainings institute as a technical writer with diverse experience in many kinds of technology-related content development. She holds a graduate education in the Computer science and Engineering stream. She has cultivated strong technical skills from reading tech blogs and also doing a lot of research related to content. She manages to write great content in many fields like Programming & Frameworks, Enterprise Integration, Web Development, SAP, and Business Process Management (BPM). Connect her on LinkedIn and Twitter.