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. Groovy offers built-in data types just as in Java. Following is a list of some useful data types:
See here for methods on how to manipulate the data types explained below.
On this page:
Simple data types
Groovy supports a limited set of datatypes at the language level; that is, it offers constructs for literal declarations and specialized operators. This section covers the simple datatypes like strings, regular expressions, and numbers.
Strings
Just like in Java, character data is mostly handled using the java.lang.String class. Groovy strings come in two flavors: plain strings and GStrings. Plain strings are instances of java.lang.String, and GStrings are instances of groovy.lang.GString. GStrings allow placeholder expressions (usually called string interpolation in many scripting languages) to be resolved and evaluated at runtime. See here for more information on Strings.
Plain Strings
Strings can be defined using single, double, or triple quotes. Groovy allows both +
and -
on Strings as shown in the example below.
Instantiating a String:
def a = "First String" def b = 'Second String' def c = """Third String""" a - " String" == "First" b + " and " + c == "Second String and Third String"
You can escape special characters in a String as explained here.
GStrings
Strings defined with double quotes (double quotes and triple double quotes) support interpolation. This allows you to substitute any Groovy expression into a String at the specified location. These are called GStrings. This is achieved using the ${}
syntax. GStrings are implemented differently to capture the fixed and the dynamic parts (values)
separately as shown in the example below.
def name = "Groovy" def greeting = "Welcome to ${name} language" greeting == "Welcome to Groovy language" greeting.strings[0] == "Welcome to " greeting.strings[1] == " language" greeting.values[0] == "Groovy"
Slashy Strings
The slashy form of a string literal allows strings with backslashes to be specified simply without having to escape all the backslashes. This is particularly useful with regular expressions discussed later on this page.
Examples
def path = /C:\Windows\System32/ path == C:\Windows\System32 //returns true def fooPattern = /.*foo.*/ fooPattern == ".*foo.*" //returns true //Slashy strings are multiline def multilineSlashy = /one two three/ multilineSlashy.contains('\n') //returns true //Slashy strings can also be interpolated (ie. a GString) def color = "blue" def interpolatedSlashy = /a ${color} car/ interpolatedSlashy == "a blue car" //returns true
Note: An empty slashy string cannot be represented with a double forward slash (//), as it’s understood by the Groovy parser as a line comment.
Dollar slashy string
Dollar slashy strings are multiline GStrings delimited with an opening $/
and and a closing /$.
def name = "Groovy" def name2 = "JMWE" def dollarSlashy = $/ Hello $name, we're ${name2}. /$
See here for more information on slashy strings.
Numbers
Numbers are objects in Groovy. Unlike in Java, they are first-class objects rather than primitive types. In Groovy, you can use numbers with numeric operators, and you can also call methods on number instances. See here for more information on numbers.
def x = 1 def y = 2 x + y == 3 x.plus(y) == 3
Regular expressions
A regular expression is a pattern that is used to find substrings in a text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represents the expression for comparison. See here for a table listing down all the regular expression metacharacter syntax. See here for more information on regular expressions.
Defining a regular expression
def regex = ~"Groovy" def p = ~$/dollar/slashy $ string/$ def p = ~"${pattern}"
Groovy relies on Java's regex support and adds three operators for convenience:
- The regex find operator
=~
- The regex match operator
==~
- The regex pattern operator
~String
Find operator
Returns a Matcher object
if the string on the left-side contains the pattern on the right of the operator.
def regex = ~/:[0-9]+/ def httpUrl1 = 'http://www.example.com:8080/' httpUrl1 =~ regex //returns java.util.regex.Matcher[pattern=:[0-9]+ region=0,28 lastmatch=]
Match operator
Returns true
if the string on the left-side matches (match must be strict) the pattern provided on the right of the operator
def regex = ~/https?:\/\/.*/ def httpUrl = 'http://www.example.com/' httpUrl ==~ regex //returns true
Pattern operator
The pattern operator (~
) provides a simple way to create a java.util.regex.Pattern
instance
def p = ~"Groovy" p instanceof java.util.regex.Pattern //returns true
Booleans
true
and false
are the only two primitive boolean values. See here for more information on this.
Defining a boolean object
boolean isActive = true isActive = false
Groovy has special rules to coerce non-boolean objects to a boolean value, referred as Truthy
and Falsy
. It decides whether to consider the expression as being true
or false
by asking the object for the result of its asBoolean()
method. Groovy expression is Truthy
when;
- A boolean value is
true
- Non-empty Collections and Arrays are
true
- The Matcher has at least one match
- Iterators and Enumerations with further elements are coerced to
true
- Non-empty Maps are evaluated to
true
- Non-empty Strings, GStrings and CharSequences are coerced to
true
- Non-zero numbers are
true
- Non-null object references are coerced to
true
Any other value is considered Falsy
. Eg: An empty string.
Arrays
An Array is an object that contains elements of similar data type. Groovy reuses the list notation for arrays, but to make such literals arrays, you need to explicitly define the type of the array through coercion or type declaration. You can also create multi-dimensional arrays. Once an array has been created its size cannot be changed, you should use a List instead. See here for more information on Arrays in Groovy.
Note that Java’s array initializer notation is not supported by Groovy, as the curly braces can be misinterpreted with the notation of Groovy closures (discussed later).
Instantiating an Array:
String[] arrStr = ["Apple", "Banana", "Kiwi"] arrStr[2] = "Mango" //Inserting element into an array
def matrix3 = new Integer[3][3] //Array with bounds def matrix = new String[][] //Array without bounds
Accessing the elements of an array:
- Accessing the second element of the array:
arrStr[1]
- Adding a new value to the array:
arrStr[3] = "Mango"
- Accessing an element of the multi-dimensional array:
matrix3[1][1]
Collections
Collections is a framework that provides an architecture to store and manipulate a group of objects. All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed on Collections. The Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc). This section lists some of the collections in Groovy. See here for detailed information on Collections.
Lists
The List is a structure used to store a collection of data items. In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. It is a subinterface of Collection that contains methods to insert and delete elements on the index basis. Groovy lists are plain JDK java.util.List
, as Groovy doesn’t define its own collection classes. You can create multi-dimensional lists too. See here for more information on Lists.
Instantiating a List:
You can initialize a list delimiting the values by commas and surrounded by square brackets. You can also create lists containing values of heterogeneous types:
def numbers = [1, 2, 3] //Elements of same data type def hetero = [1, "a", true] //Elements of heterogenous data types def multi = [[0, 1], [2, 3]] multi[1][0] == 2 List newValues = [] //Empty list
Accessing a List:
- You can access the first element of the list on zero-based counting:
hetero[0]
- You can access the last element of the list with a negative index:
hetero[-1]
- Add an element to the list:
numbers[3] = 5
- Size of the list:
numbers.size() == 4
Set
Set is a collection that contains no duplicate elements. Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. All these permit null values too.
Instantiating a Set:
You can initialize a Set delimiting the values by commas and surrounded by square brackets. A Set can have values of heterogeneous types:
Set names = [] //Initialising a HashSet set.add("Oliver") set.add("Casper") set.add("elvis") set.add("Elvis") set.add("John") set.add("Carter") set.add("Oliver") names.size() == 6 Set numbers = [3,4,6,"Special","@",5,1.2,3,4] numbers as Set numbers //returns [3, 4, 6, Special, @, 5, 1.2, 3, 4] Set newValues = [] //Empty set
Maps
Groovy features maps. Maps associate keys to values, separating keys and values with colons, and each key/value pairs with commas, and the whole keys and values surrounded by square brackets. See here for more information on Maps.
Initialising a Map:
You need to pass quoted strings if your key string isn’t a valid identifier Eg: "block-no". You must surround a variable or expression with parentheses, when you need to it as a key in your map definition. Eg:
def colors = [red: "#FF0000", green:"#00FF00", blue: "#0000FF"] def doctor = [name: "Oliver","block-no":33,speciality:"Cardiology"] //Map where the key isn't a valid identifier place = [(address):"Oliver"] //Variable "address" as the key def emptyMap = [:] //An empty map
Accessing the elements of a Map:
- Check the value associated with the key,
red
:colors["red"]
- Add a new pair to the Map:
colors["pink"] = "
#FF00FF"
orcolors.pink = "#FF00FF"
- Check the Map contains a specific key:
colors.blue == true
Ranges
A range is a shorthand for specifying a sequence of values. A range has a left bound and a right bound denoted by the first and last values in the sequence, and it 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. See here for more information on Ranges.
Instantiating a Range:
def range = (0..10) //defining a range - Inclusive range Range r = (0..<10) //defining a range - Exclusive range def today = new Date() def yesterday = today-1
Accessing the elements of a Range:
- Check the range contains a specific element:
r.contains(10) == false
- Size of the range:
(yesterday..today).size() == 2