Groovy – Maps

Groovy – Maps ”; Previous Next A Map (also known as an associative array, dictionary, table, and hash) is an unordered collection of object references. The elements in a Map collection are accessed by a key value. The keys used in a Map can be of any class. When we insert into a Map collection, two values are required: the key and the value. Following are some examples of maps − [‘TopicName’ : ‘Lists’, ‘Author’ : ‘Raghav’] – Collections of key value pairs which has TopicName as the key and their respective values. [ : ] – An Empty map. In this chapter, we will discuss the map methods available in Groovy. Sr.No. Methods & Description 1 containsKey() Does this Map contain this key? 2 get() Look up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then return null. 3 keySet() Obtain a Set of the keys in this Map. 4 put() Associates the specified value with the specified key in this Map. If this Map previously contained a mapping for this key, the old value is replaced by the specified value. 5 size() Returns the number of key-value mappings in this Map. 6 values() Returns a collection view of the values contained in this Map. Print Page Previous Next Advertisements ”;

Groovy – Object Oriented

Groovy – Object Oriented ”; Previous Next In Groovy, as in any other Object-Oriented language, there is the concept of classes and objects to represent the objected oriented nature of the programming language. A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain. A class in Groovy declares the state (data) and the behavior of objects defined by that class. Hence, a Groovy class describes both the instance fields and methods for that class. Following is an example of a class in Groovy. The name of the class is Student which has two fields – StudentID and StudentName. In the main function, we are creating an object of this class and assigning values to the StudentID and StudentName of the object. class Student { int StudentID; String StudentName; static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.StudentName = “Joe” } } getter and setter Methods In any programming language, it always a practice to hide the instance members with the private keyword and instead provide getter and setter methods to set and get the values of the instance variables accordingly. The following example shows how this can be done. Live Demo class Student { private int StudentID; private String StudentName; void setStudentID(int pID) { StudentID = pID; } void setStudentName(String pName) { StudentName = pName; } int getStudentID() { return this.StudentID; } String getStudentName() { return this.StudentName; } static void main(String[] args) { Student st = new Student(); st.setStudentID(1); st.setStudentName(“Joe”); println(st.getStudentID()); println(st.getStudentName()); } } When we run the above program, we will get the following result − 1 Joe Note the following key points about the above program − In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class. Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method – void setStudentName(String pName) Instance Methods It’s normally a natural to include more methods inside of the class which actually does some sort of functionality for the class. In our student example, let’s add instance members of Marks1, Marks2 and Marks3 to denote the marks of the student in 3 subjects. We will then add a new instance method which will calculate the total marks of the student. Following is how the code would look like. In the following example, the method Total is an additional Instance method which has some logic built into it. class Student { int StudentID; String StudentName; int Marks1; int Marks2; int Marks3; int Total() { return Marks1+Marks2+Marks3; } static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.StudentName=”Joe”; st.Marks1 = 10; st.Marks2 = 20; st.Marks3 = 30; println(st.Total()); } } When we run the above program, we will get the following result − 60 Creating Multiple Objects One can also create multiple objects of a class. Following is the example of how this can be achieved. In here we are creating 3 objects (st, st1 and st2) and calling their instance members and instance methods accordingly. Live Demo class Student { int StudentID; String StudentName; int Marks1; int Marks2; int Marks3; int Total() { return Marks1+Marks2+Marks3; } static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.StudentName = “Joe”; st.Marks1 = 10; st.Marks2 = 20; st.Marks3 = 30; println(st.Total()); Student st1 = new Student(); st.StudentID = 1; st.StudentName = “Joe”; st.Marks1 = 10; st.Marks2 = 20; st.Marks3 = 40; println(st.Total()); Student st3 = new Student(); st.StudentID = 1; st.StudentName = “Joe”; st.Marks1 = 10; st.Marks2 = 20; st.Marks3 = 50; println(st.Total()); } } When we run the above program, we will get the following result − 60 70 80 Inheritance Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). Extends extends is the keyword used to inherit the properties of a class. Given below is the syntax of extends keyword. In the following example we are doing the following things − Creating a class called Person. This class has one instance member called name. Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class. In the Student class constructor, we are calling the base class constructor. In our Student class, we are adding 2 additional instance members of StudentID and Marks1. Live Demo class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; st.name = “Joe”; println(st.name); } } class Person { public String name; public Person() {} } class Student extends Person { int StudentID int Marks1; public Student() { super(); } } When we run the above program, we will get the following result − Joe Inner Classes Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, a inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes. Following is an example of an Outer and Inner class. In the following example we are doing the following things − Creating an class called Outer which will be our outer class. Defining a string called name in our Outer class. Creating an Inner or

Groovy – Strings

Groovy – Strings ”; Previous Next A String literal is constructed in Groovy by enclosing the string text in quotations. Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes (’), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines. Following is an example of the usage of strings in Groovy − Live Demo class Example { static void main(String[] args) { String a = ”Hello Single”; String b = “Hello Double”; String c = “”Hello Triple” + “Multiple lines””; println(a); println(b); println(c); } } When we run the above program, we will get the following result − Hello Single Hello Double ”Hello TripleMultiple lines” String Indexing Strings in Groovy are an ordered sequences of characters. The individual character in a string can be accessed by its position. This is given by an index position. String indices start at zero and end at one less than the length of the string. Groovy also permits negative indices to count back from the end of the string. Following is an example of the usage of string indexing in Groovy − Live Demo class Example { static void main(String[] args) { String sample = “Hello world”; println(sample[4]); // Print the 5 character in the string //Print the 1st character in the string starting from the back println(sample[-1]); println(sample[1..2]);//Prints a string starting from Index 1 to 2 println(sample[4..2]);//Prints a string starting from Index 4 back to 2 } } When we run the above program, we will get the following result − o d el oll Basic String Operations First let’s learn the basic string operations in groovy. They are given below. S.No. String Operation & Description 1 Concatenation of two strings The concatenation of strings can be done by the simple ‘+’ operator. 2 String Repetition The repetition of strings can be done by the simple ‘*’ operator. 3 String Length The length of the string determined by the length() method of the string. String Methods Here is the list of methods supported by String class. S.No. Methods & Description 1 center() Returns a new String of length numberOfChars consisting of the recipient padded on the left and right with space characters. 2 compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences. 3 concat() Concatenates the specified String to the end of this String. 4 eachMatch() Processes each regex group (see next section) matched substring of the given String. 5 endsWith() Tests whether this string ends with the specified suffix. 6 equalsIgnoreCase() Compares this String to another String, ignoring case considerations. 7 getAt() It returns string value at the index position 8 indexOf() Returns the index within this String of the first occurrence of the specified substring. 9 matches() It outputs whether a String matches the given regular expression. 10 minus() Removes the value part of the String. 11 next() This method is called by the ++ operator for the class String. It increments the last character in the given String. 12 padLeft() Pad the String with the spaces appended to the left. 13 padRight() Pad the String with the spaces appended to the right. 14 plus() Appends a String 15 previous() This method is called by the — operator for the CharSequence. 16 replaceAll() Replaces all occurrences of a captured group by the result of a closure on that text. 17 reverse() Creates a new String which is the reverse of this String. 18 split() Splits this String around matches of the given regular expression. 19 subString() Returns a new String that is a substring of this String. 20 toUpperCase() Converts all of the characters in this String to upper case. 21 toLowerCase() Converts all of the characters in this String to lower case. Print Page Previous Next Advertisements ”;

Groovy – Ranges

Groovy – Ranges ”; Previous Next A range is shorthand for specifying a sequence of values. A Range is denoted by the first and last values in the sequence, and Range can be inclusive or exclusive. An inclusive Range includes all the values from the first to the last, while an exclusive Range includes all values except the last. Here are some examples of Range literals − 1..10 – An example of an inclusive Range 1..<10 – An example of an exclusive Range ‘a’..’x’ – Ranges can also consist of characters 10..1 – Ranges can also be in descending order ‘x’..’a’ – Ranges can also consist of characters and be in descending order. Following are the various methods available for ranges. Sr.No. Methods & Description 1 contains() Checks if a range contains a specific value 2 get() Returns the element at the specified position in this Range. 3 getFrom() Get the lower value of this Range. 4 getTo() Get the upper value of this Range. 5 isReverse() Is this a reversed Range, iterating backwards 6 size() Returns the number of elements in this Range. 7 subList() Returns a view of the portion of this Range between the specified fromIndex, inclusive, and toIndex, exclusive Print Page Previous Next Advertisements ”;

Groovy – Command Line

Groovy – Command Line ”; Previous Next The Groovy shell known as groovysh can be easily used to evaluate groovy expressions, define classes and run simple programs. The command line shell gets installed when Groovy is installed. Following are the command line options available in Groovy − Command line parameter Full Name Details -C –color[=FLAG] Enable or disable use of ANSI colors -D –define=NAME=VALUE Define a system property -T –terminal=TYPE Specify the terminal TYPE to use -V –version Display the version -classpath Specify where to find the class files – must be the first argument -cp –classpath Aliases for ”-classpath” -d –debug –debug Enable debug output -e –evaluate=arg Evaluate option fist when starting interactive session -h –help Display this help message -q –quiet Suppress superfluous output -v –verbose Enable verbose output The following snapshot shows a simple example of an expression being executed in the Groovy shell. In the following example we are just printing “Hello World” in the groovy shell. Classes and Functions It is very easy to define a class in the command prompt, create a new object and invoke a method on the class. The following example shows how this can be implemented. In the following example, we are creating a simple Student class with a simple method. In the command prompt itself, we are creating an object of the class and calling the Display method. It is very easy to define a method in the command prompt and invoke the method. Note that the method is defined using the def type. Also note that we have included a parameter called name which then gets substituted with the actual value when the Display method is called. The following example shows how this can be implemented. Commands The shell has a number of different commands, which provide rich access to the shell’s environment. Following is the list of them and what they do. Sr.No Command &smp; Command Description 1 :help (:h ) Display this help message 2 ? (:? ) Alias to: :help 3 :exit (:x ) Exit the shell 4 :quit (:q ) Alias to: :exit 5 import (:i ) Import a class into the namespace 6 :display (:d ) Display the current buffer 7 :clear (:c ) Clear the buffer and reset the prompt counter 8 :show (:S ) Show variables, classes or imports 9 :inspect (:n ) Inspect a variable or the last result with the GUI object browser 10 :purge (:p ) Purge variables, classes, imports or preferences 11 :edit (:e ) Edit the current buffer 12 :load (:l ) Load a file or URL into the buffer 13 . (:. ) Alias to: :load 14 .save (:s ) Save the current buffer to a file 15 .record (:r ) Record the current session to a file 16 :alias (:a ) Create an alias 17 :set (:= ) Set (or list) preferences 18 :register (:rc) Registers a new command with the shell 19 :doc (:D ) Opens a browser window displaying the doc for the argument 20 :history (:H ) Display, manage and recall edit-line history Print Page Previous Next Advertisements ”;

Groovy – Optionals

Groovy – Optionals ”; Previous Next Groovy is an “optionally” typed language, and that distinction is an important one when understanding the fundamentals of the language. When compared to Java, which is a “strongly” typed language, whereby the compiler knows all of the types for every variable and can understand and honor contracts at compile time. This means that method calls are able to be determined at compile time. When writing code in Groovy, developers are given the flexibility to provide a type or not. This can offer some simplicity in implementation and, when leveraged properly, can service your application in a robust and dynamic way. In Groovy, optional typing is done via the ‘def’ keyword. Following is an example of the usage of the def method − Live Demo class Example { static void main(String[] args) { // Example of an Integer using def def a = 100; println(a); // Example of an float using def def b = 100.10; println(b); // Example of an Double using def def c = 100.101; println(c); // Example of an String using def def d = “HelloWorld”; println(d); } } From the above program, we can see that we have not declared the individual variables as Integer, float, double, or string even though they contain these types of values. When we run the above program, we will get the following result − 100 100.10 100.101 HelloWorld Optional typing can be a powerful utility during development, but can lead to problems in maintainability during the later stages of development when the code becomes too vast and complex. To get a handle on how you can utilize optional typing in Groovy without getting your codebase into an unmaintainable mess, it is best to embrace the philosophy of “duck typing” in your applications. If we re-write the above code using duck typing, it would look like the one given below. The variable names are given names which resemble more often than not the type they represent which makes the code more understandable. class Example { static void main(String[] args) { // Example of an Integer using def def aint = 100; println(aint); // Example of an float using def def bfloat = 100.10; println(bfloat); // Example of an Double using def def cDouble = 100.101; println(cDouble); // Example of an String using def def dString = “HelloWorld”; println(dString); } } Print Page Previous Next Advertisements ”;

Groovy – Quick Guide

Groovy – Quick Guide ”; Previous Next Groovy – Overview Groovy is an object oriented language which is based on Java platform. Groovy 1.0 was released in January 2, 2007 with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0. Features of Groovy Groovy has the following features − Support for both static and dynamic typing. Support for operator overloading. Native syntax for lists and associative arrays. Native support for regular expressions. Native support for various markup languages such as XML and HTML. Groovy is simple for Java developers since the syntax for Java and Groovy are very similar. You can use existing Java libraries. Groovy extends the java.lang.Object. The official website for Groovy is http://www.groovy-lang.org/ Groovy – Environment There are a variety of ways to get the Groovy environment setup. Binary download and installation − Go to the link www.groovy-lang.org/download.html to get the Windows Installer section. Click on this option to start the download of the Groovy installer. Once you launch the installer, follow the steps given below to complete the installation. Step 1 − Select the language installer. Step 2 − Click the Next button in the next screen. Step 3 − Click the ‘I Agree’ button. Step 4 − Accept the default components and click the Next button. Step 5 − Choose the appropriate destination folder and then click the Next button. Step 6 − Click the Install button to start the installation. Step 7 − Once the installation is complete, click the Next button to start the configuration. Step 8 − Choose the default options and click the Next button. Step 9 − Accept the default file associations and click the Next button. Step 10 − Click the Finish button to complete the installation. Once the above steps are followed, you can then start the groovy shell which is part of the Groovy installation that helps in testing our different aspects of the Groovy language without the need of having a full-fledged integrated development environment for Groovy. This can be done by running the command groovysh from the command prompt. If you want to include the groovy binaries as part of you maven or gradle build, you can add the following lines Gradle ”org.codehaus.groovy:groovy:2.4.5” Maven <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>2.4.5</version> Groovy – Basic Syntax In order to understand the basic syntax of Groovy, let’s first look at a simple Hello World program. Creating Your First Hello World Program Creating your first hello world program is as simple as just entering the following code line − Live Demo class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println(”Hello World”); } } When we run the above program, we will get the following result − Hello World Import Statement in Groovy The import statement can be used to import the functionality of other libraries which can be used in your code. This is done by using the import keyword. The following example shows how to use a simple import of the MarkupBuilder class which is probably one of the most used classes for creating HTML or XML markup. import groovy.xml.MarkupBuilder def xml = new MarkupBuilder() By default, Groovy includes the following libraries in your code, so you don’t need to explicitly import them. import java.lang.* import java.util.* import java.io.* import java.net.* import groovy.lang.* import groovy.util.* import java.math.BigInteger import java.math.BigDecimal Tokens in Groovy A token is either a keyword, an identifier, a constant, a string literal, or a symbol. println(“Hello World”); In the above code line, there are two tokens, the first is the keyword println and the next is the string literal of “Hello World”. Comments in Groovy Comments are used to document your code. Comments in Groovy can be single line or multiline. Single line comments are identified by using the // at any position in the line. An example is shown below − class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println(”Hello World”); } } Multiline comments are identified with /* in the beginning and */ to identify the end of the multiline comment. class Example { static void main(String[] args) { /* This program is the first program This program shows how to display hello world */ println(”Hello World”); } } Semicolons Unlike in the Java programming language, it is not mandatory to have semicolons after the end of every statement, It is optional. Live Demo class Example { static void main(String[] args) { def x = 5 println(”Hello World”); } } If you execute the above program, both statements in the main method don”t generate any error. Identifiers Identifiers are used to define variables, functions or other user defined variables. Identifiers start with a letter, a dollar or an underscore. They cannot start with a number. Here are some examples of valid identifiers − def employeename def student1 def student_name where def is a keyword used in Groovy to define an identifier. Here is a code example of how an identifier can be used in our Hello World program. class Example { static void main(String[] args) { // One can see the use of a semi-colon after each statement def x = 5; println(”Hello World”); } } In the above example, the variable x is used as an identifier. Keywords Keywords as the name suggest are special words which are reserved in the Groovy Programming language. The following table lists the keywords which are defined in Groovy. as assert break case catch class const continue def default do else enum extends false Finally for goto if implements import in instanceof interface new pull package return super switch this throw throws trait true try while Whitespaces Whitespace is the term used in a programming language such as Java and Groovy to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify

Groovy – Regular Expressions

Groovy – Regular Expressions ”; Previous Next A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison. For example we can create a regular expression object as shown below − def regex = ~”Groovy” When the Groovy operator =~ appears as a predicate (expression returning a Boolean) in if and while statements (see Chapter 8), the String operand on the left is matched against the regular expression operand on the right. Hence, each of the following delivers the value true. When defining regular expression, the following special characters can be used − There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($). Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once. The metacharacter { and } is used to match a specific number of instances of the preceding character. In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character. A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below ”Groovy” =~ ”Groovy” ”Groovy” =~ ”oo” ”Groovy” ==~ ”Groovy” ”Groovy” ==~ ”oo” ”Groovy” =~ ”∧G” ‘Groovy” =~ ”G$” ‘Groovy” =~ ”Gro*vy” ”Groovy” =~ ”Gro{2}vy” Print Page Previous Next Advertisements ”;

Groovy – Home

Groovy Tutorial PDF Version Quick Guide Resources Job Search Discussion Groovy is an object oriented language which is based on Java platform. Groovy 1.0 was released in January 2, 2007 with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0. In this tutorial, we would explain all the fundamentals of Groovy and how to put it into practice. Audience This tutorial is going to be extremely useful for all those software professionals who would like to learn the basics of Groovy programming. Prerequisites Before proceeding with this tutorial, you should have some hands-on experience of Java or any other object-oriented programming language. No Groovy experience is assumed. Print Page Previous Next Advertisements ”;

Groovy – Data Types

Groovy – Data Types ”; Previous Next In any programming language, you need to use various variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory to store the value associated with the variable. You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Built-in Data Types Groovy offers a wide variety of built-in data types. Following is a list of data types which are defined in Groovy − byte − This is used to represent a byte value. An example is 2. short − This is used to represent a short number. An example is 10. int − This is used to represent whole numbers. An example is 1234. long − This is used to represent a long number. An example is 10000090. float − This is used to represent 32-bit floating point numbers. An example is 12.34. double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565. char − This defines a single character literal. An example is ‘a’. Boolean − This represents a Boolean value which can either be true or false. String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. Bound values The following table shows the maximum allowed values for the numerical and decimal literals. byte -128 to 127 short -32,768 to 32,767 int -2,147,483,648 to 2,147,483,647 long -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 float 1.40129846432481707e-45 to 3.40282346638528860e+38 double 4.94065645841246544e-324d to 1.79769313486231570e+308d Class Numeric Types In addition to the primitive types, the following object types (sometimes referred to as wrapper types) are allowed − java.lang.Byte java.lang.Short java.lang.Integer java.lang.Long java.lang.Float java.lang.Double In addition, the following classes can be used for supporting arbitrary precision arithmetic − Name Description Example java.math.BigInteger Immutable arbitrary-precision signed integral numbers 30g java.math.BigDecimal Immutable arbitrary-precision signed decimal numbers 3.5g The following code example showcases how the different built-in data types can be used − Live Demo class Example { static void main(String[] args) { //Example of a int datatype int x = 5; //Example of a long datatype long y = 100L; //Example of a floating point datatype float a = 10.56f; //Example of a double datatype double b = 10.5e40; //Example of a BigInteger datatype BigInteger bi = 30g; //Example of a BigDecimal datatype BigDecimal bd = 3.5g; println(x); println(y); println(a); println(b); println(bi); println(bd); } } When we run the above program, we will get the following result − 5 100 10.56 1.05E41 30 3.5 Print Page Previous Next Advertisements ”;