1) Introduction
Groovy is an Object Oriented Scripting Language which provides Dynamic, Easy-to-use and Integration capabilities to the Java Virutual Machine. It absorbs most of the syntax from Java and it is much powerful in terms of funtionalities which is manifiested in the form Closures, Dynamic Typing, Builders etc. Groovy also provides simplified API for accessing Databases and XML. Groovy language is large in terms of functionalities and concepts and this article provides only the basic Introduction and Information about Groovy. The first section of the article concentrates on the very basic concepts and theories of Groovy like Declaring Variables, Flow Control and Looping Structures. Then the next section focusses on Declaring Classes, Objects, Methods and the different ways of accessing them in Groovy. Covered in depth are the most exiting Groovy Closures. Finally the article explored the Groovy Distribution along with the various available Utilities.
2) Basics of Groovy
2.1) The Traditional Hello World Program
Learning a new language generally involves a lot of time and energy because the various program elements like Syntax, Operators, Declarations, Control Structures etc. have to be remembered. But, learning Groovy don't consume much time as the Language Syntax resembles the same as Java. Before going into the various pieces of Program Elements, let us see a simple and the traditional Hello World Program in Groovy.
Copy and Paste the following code in your favorite text Editor. Before running the script, make sure that you have downloaded the Groovy Distribution available at http://dist.groovy.codehaus.org/distributions/groovy-binary-1.1-BETA-1.zip. Following is the code listing for printing the traditional Hello World Program in Groovy.
Hello.groovy
// Printing the word "Hello" using Groovy.
print "Hello\n"
Note that it is not necessary that the Groovy Files must have an extension '.groovy'. It can be anything. Go the command prompt and set the path variable pointing to GROOVY_HOME\bin. Suppose if Groovy is installed in the directory C:\Groovy-1.1, then the path variable must be pointing to C:\Groovy-1.1\bin;.
Setting the Path Variable
set path=%path%;GROOVY_HOME\bin;
After that give the following command and you will see the text "Hello" followed by a new line in the output.
Running the Groovy Program
groovy Hello.groovy
2.2) Declaring Variables
In the previous section, we saw how to write a simple Hello World program using Groovy. Now let us dig into the various Language Basics of Groovy. More specifically, the subsequent sections will tell you how to Declare variables, Defining Control Structures and the various Looping Constructs etc. Variables or Objects have to be declared before being referenced somewhere. The simple way to declare a variable is to just a name along with some value. For example, the following code declares a variable name called 'name' with the value 'Johny'.
// Defining a variable called 'name' in Groovy and assigning it with a value.
def name = "Johny"
The keyword 'def' stands for definition. It is also possible to ignore the keyword 'def' during variable declaration. So, the following code is also possible.
name = "Johny"
If we want to take the value of a variable then the '$' sign should be prefixed along with the variable name. For example, the following code will print "Hello Johny" in the console.
def name = "Johny"
print "Hello $name \n"
By default, the Java Packages java.lang.*, java.util.*, java.io.*, java.math.*, java.net.* will be included automatically by the Groovy Intepreter. The declaration of a Java Object within Groovy follows the same standard as that of a normal Variable. For example the following example shows the usage of the import statement as well as referencing Java Objects within the Groovy Environment,
Declarations.groovy
def strObject = new String("Groovy")
print strObject.length()
// Import statement can occur anywhere
import java.sql.*
Connection connection
import java.lang.reflect.Method
Method aMethod
Having done with the basics of Declaring variables and Objects in Groovy, let us now see how to declare Collection Data Types in Groovy. The syntax of declaring a Collection object in Groovy is very simple and the following code snippet will prove that,
Collection.groovy
// Define a Collection called numbers holding 1, 2 and 3
def numbers = [10, 2, 33]
// Iterate over the collection and print it.
for (number in numbers){
println number
}
// Add two more entries to the Collection.
numbers.add(14)
numbers.add(57)
// Iterate again over the Collection to see the new values.
for (number in numbers){
println number
}
The above code declares a collection populated with elements using the [] syntax. All elements within [] forms the elements in the collection. Elements in the collection are traversed using the Enhanced For Loop (also called for-each). Elements are also added dynamically to the Collection using the add() method.
Here is the output for the above program.
Output
10
2
33
10
2
33
14
57
2.3) Working with Control Structures
Let us look into the various Control structures like If-Else, For Loops and While Loops in this section. The syntax for the Conditional Statements resembles very similar to the one that we normally see in programming languages like C, C++ or Java. Following is the syntax for If-Else Construct.
if ( booleanExpression ){
// Set of Statements
}else{
// Other Set of Statements.
}
The thing to note in the above syntax is which and all evaluates to a boolean expression is Groovy. Consider the following set of statements,
Construct.groovy
boolValue = true
notEmptyStr = new String("Hello");
numberList = ["1","2", "3"]
if (boolValue && notEmptyStr && numberList) {
println "Condition is true"
}else{
println "Condition is false"
}
boolValue = false
emptyStr = new String("");
emptyList = []
if( boolValue || emptyStr || emptyList){
println "Condition is true"
}else{
println "Condition is false"
}
Here is the output for the above program.
Output
Condition is true
Condition is false
Consider how Groovy evaluates the String Object and the Collection Object when being used in the Conditional Construct. A String or a Collection object will return true if the Object is not null or empty.
2.4) Looping Constructs
This section looks into the syntax and the structure of 'for' and 'while' loop constructs in Groovy. The syntax looks very similar to Java and it also provides much more powerful functionality than Java Constructs as the following code snippets will prove.
The syntax of the for loop is given below,
for(Object in IterableObject){
// Set of Statements.
}
The above looks very similar to the Enhanced For Loop (starting from 5.0) in Java. Let us now see what it is an Iterable Object. An Iterable Object is usually a Composite Object having multiple Child Entries that can be iterated over. In Java terms, this exactly means any Object that implements the java.lang.Iterable interface. Most of the Collection Objects like List, Set, etc. all implements the Iterator interface which provides a method called Iterable.iterator(), using that elements with the Composite Object can be iterated over.
Consider the following code snippets for Iterable Object in Groovy.
Loop.groovy
// A String is nothing but a sequence of characters.
def hello = "Hello"
for(aChar in hello){
println aChar
}
// A Collection object holding the four seasons.
def seasons = ["Winter", "Season", "Spring", "Autumn"]
for(season in seasons){
println season
}
// Even a File Object can be iterated in Groovy.
String thisFileName = "Loop.groovy"
thisFile = new File(thisFileName)
for(aLine in thisFile){
println aLine
}
The output for the above program will look something like the following.
Ouput
H
e
l
l
o
Winter
Season
Spring
Autumn
def hello = "Hello"
for(h in hello){
println h
}
def seasons = ["Winter", "Season", "Spring", "Autumn"]
for(season in seasons){
println season
}
// Even a File Object can be iterated in Groovy.
String thisFileName = "Loop.groovy"
thisFile = new File(thisFileName)
for(aLine in thisFile){
println aLine
}
Since a String Object represents a Collection of Characters, it can be considered as an Iterable Object, so is the case of a Collection Object. Examine how the File object is traversed over to print the whole contents. Since a File logically represents a collection of lines followed by new line characters, in Groovy terms, a File object can also be imagined as an Iterable Object.
Following is the syntax of the while loop which resembles very similar to the traditional programming languages like C or Java.
while (condition){
// Repeat the loop till the condition remains true.
}
|