---
title: "Data types in Groovy"
canonical: "https://support.appfire.com/space/JMWE/461571205/Data%20types%20in%20Groovy"
format: markdown
---
> Macro (aura-html)

<span style="color: #000000">When you create a variable you reserve some space in memory to store the value associated with the variable. Y</span><span style="color: #000000">ou 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. </span><span style="color: #000000">Groovy offers built-in data types just as in Java. Following is a list of some useful data types:</span>

> ℹ️ See [here](https://appfire.atlassian.net/wiki/spaces/JMWE/pages/461571253) for methods on how to manipulate the data types explained below.

<span style="color: #000000">**On this page:**</span>


# <span style="color: #404040">Simple data types</span>

<span style="color: #404040">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.</span>

## <span style="color: #404040">Strings</span>

<span style="color: #000000">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. </span><span style="color: #000000">See </span>[<span style="color: #000000">her</span>](http://docs.groovy-lang.org/latest/html/documentation/#all-strings)<span style="color: #000000">e for more information on Strings.</span>

### <span style="color: #000000">Plain Strings</span>

<span style="color: #000000">Strings can be defined using single, double, triple single quotes or triple double quotes. All these are a series of characters surrounded by the respective quotes. Only double (double and triple double) quoted strings support interpolation. The triple quoted (triple single and triple double) strings </span><span style="color: #000000">are multi-line and y</span><span style="color: #343437">ou can span the content of the string across line boundaries without the need to split the string in several pieces, without contatenation or newline escape characters. Also, </span><span style="color: #343437">neither double quotes nor single quotes need to be escaped in triple double/single quoted strings.</span>

<span style="color: #000000">**String concatenation:**</span>

<span style="color: #000000">Groovy allows both </span>`+`<span style="color: #000000"> and </span>`-`<span style="color: #000000"> on Strings as shown in the example below.</span>

**<span style="color: #000000">Instantiating a String:</span>**

##### **Strings**

```groovy
//Define strings with quotes
def a = "First String"
def b = 'Second String'

def multi-line = """First
Second
Third
lines"""

def multiline = '''Multiple
lines
with
triple single quotes'''

def multiline = '''Line
with
"double quotes"
in triple single quotes'''

//String concatenation
"Groovy" + " in JMWE" == "Groovy in JMWE"
"Groovy in JMWE" - " in" == "Groovy JMWE"
```

<span style="color: #000000">You can escape special characters in a String as explained </span>[<span style="color: #000000">here</span>](http://docs.groovy-lang.org/latest/html/documentation/#_escaping_special_characters)<span style="color: #000000">.</span>

### <span style="color: #404040">GStrings</span>

<span style="color: #404040">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</span><span style="color: #404040"> </span>`${}`<span style="color: #404040"> </span><span style="color: #404040">syntax. GStrings are implemented differently to capture the fixed and the dynamic parts</span><span style="color: #404040"> (</span>`values)`<span style="color: #404040"> separately as shown in the example below.</span>

##### **GStrings**

```groovy
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"
```

### <span style="color: #404040">Slashy Strings</span>

<span style="color: #404040">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 </span>[<span style="color: #404040">regular expressions</span>](#DatatypesinGroovy-Regularexpressions)<span style="color: #404040"> discussed later on this page. </span>

<span style="color: #404040">**Examples**</span>

##### **Slashy Strings**

```groovy
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
```

**<span style="color: #404040">Note:</span>**<span style="color: #404040"> An empty slashy string cannot be represented with a double forward slash (//), as it’s understood by the Groovy parser as a line comment.</span>

<span style="color: #404040">**Dollar slashy string**</span>

<span style="color: #343437">Dollar slashy strings are multiline GStrings delimited with an opening </span>`$/`<span style="color: #343437"> and and a closing </span>`/$.`

##### **Dollar Slashy String**

```groovy
def name = "Groovy"
def name2 = "JMWE"

def dollarSlashy = $/
    Hello $name,
    we're ${name2}. /$
```

<span style="color: #404040">See </span>[<span style="color: #404040">here</span>](http://groovy-lang.org/syntax.html#_slashy_string)<span style="color: #404040"> for more information on slashy strings.</span>

## <span style="color: #404040">Numbers</span>

<span style="color: #404040">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 </span>[<span style="color: #404040">here</span>](http://docs.groovy-lang.org/latest/html/documentation/#_numbers)<span style="color: #404040"> for more information on numbers.</span>

##### **Numbers**

```groovy
def x = 1
def y = 2

x + y == 3
x.plus(y) == 3

```

## <span style="color: #404040">Regular expressions</span>

<span style="color: #000000">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 </span>[<span style="color: #000000">here</span>](https://www.tutorialspoint.com/java/java_regular_expressions.htm)<span style="color: #000000"> for a </span><span style="color: #000000">table listing down all the regular expression metacharacter syntax. See </span>[<span style="color: #000000">here</span>](http://docs.groovy-lang.org/latest/html/documentation/#_regular_expression_operators)<span style="color: #000000"> for more information on regular expressions.</span>

**Defining a regular expression**

##### **Regex**

```groovy
def regex = ~"Groovy"
def p = ~$/dollar/slashy $ string/$
def p = ~"${pattern}"
```

Groovy relies on [Java's regex suppor](https://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html)t and adds three operators for convenience:

- The regex find operator` =~`
- The regex match operator `==~`
- The regex pattern operator `~String`

Groovy supports the following tasks for regular expressions:

- Tell whether the pattern fully matches the whole string
- Tell whether there is an occurrence of the pattern in the string
- Count the occurrences
- Do something with each occurrence
- Replace all occurrences with some text
- Split the string into multiple strings by cutting at each occurrence

**Find operator**

<span style="color: #000000">Returns a </span>`Matcher object`<span style="color: #000000"> </span><span style="color: #000000">if the string on the left-side contains the pattern on the right of the operator.</span>

##### **Find operator**

```groovy
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**

<span style="color: #000000">Returns </span>`true`<span style="color: #000000"> if the string on the left-side matches (match must be strict) the pattern provided on the right of the operator</span>

##### **Match operator**

```groovy
def regex = ~/https?:\/\/.*/
def httpUrl = 'http://www.example.com/'

httpUrl ==~ regex //returns true
```

**Pattern operator**

<span style="color: #222222">The pattern operator (</span>`~`<span style="color: #222222">) provides a simple way to create a</span><span style="color: #222222"> </span>`java.util.regex.Pattern`<span style="color: #222222"> </span><span style="color: #222222">instance</span>

##### **Pattern operator**

```groovy
def p = ~"Groovy"
p instanceof java.util.regex.Pattern //returns true
```

## <span style="color: #404040">Booleans</span>

`true` and `false` are the only two primitive boolean values. See [here](http://docs.groovy-lang.org/latest/html/documentation/#_booleans) for more information on this.

**Defining a boolean object**

##### **Boolean**

```groovy
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`
- <span style="color: #222222">Non-empty Maps are evaluated to </span>`true`
- <span style="color: #222222">Non-empty Strings, GStrings and CharSequences are coerced to </span>`true`
- <span style="color: #222222">Non-zero numbers are </span>`true`
- <span style="color: #222222">Non-null object references are coerced to </span>`true`

<span style="color: #222222">Any other value is considered </span>`Falsy`<span style="color: #222222">. Eg: An empty string.</span>

## <span style="color: #222222">Arrays</span>

<span style="color: #000000">An Array is </span><span style="color: #000000">an object that contains elements of similar data type.</span><span style="color: #000000"> </span><span style="color: #222222">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. </span><span style="color: #222222">You can also create multi-dimensional arrays. </span><span style="color: #000000">Once an array has been created its size cannot be changed,</span><span style="color: #000000"> you should use a</span><span style="color: #000000"> </span>[<span style="color: #000000">List</span>](#DatatypesinGroovy-Lists)<span style="color: #000000"> </span><span style="color: #333333">for dynamically-sized arrays</span><span style="color: #000000">. See </span>[<span style="color: #000000">here</span>](http://docs.groovy-lang.org/latest/html/documentation/#_arrays)<span style="color: #000000"> for more information on Arrays in Groovy.</span>

> ⚠️ 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:**

##### **Array[]**

```groovy
String[] arrStr = ["Apple", "Banana", "Kiwi"] 
arrStr[2] = "Mango" //Inserting element into an array
```


##### **Array[][]**

```groovy
def matrix3 = new Integer[3][3]  //Array with bounds
def matrix = new String[][]      //Array without bounds
```

<span style="color: #000000">**Accessing the elements of an array:**</span>

- <span style="color: #000000">Accessing the second element of the array:</span>` arrStr[1]`
- <span style="color: #000000">Adding a new value to the array: </span>`arrStr[3] = "Mango"`
- <span style="color: #000000">Accessing an element of the multi-dimensional array: </span>`matrix3[1][1]`

# <span style="color: #404040">Collections</span>

<span style="color: #222222">Collections </span><span style="color: #000000">is a framework that provides an architecture to store and manipulate a group of objects. </span><span style="color: #000000">All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed on Collections. The </span><span style="color: #000000">Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc). </span><span style="color: #222222">This section lists some of the collections in Groovy. See </span>[<span style="color: #222222">here</span>](https://livebook.manning.com/#!/book/groovy-in-action-second-edition/chapter-4)<span style="color: #222222"> for detailed information on Collections.</span>

## <span style="color: #222222">List</span>

<span style="color: #000000">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</span><span style="color: #000000"> is a subinterface of Collection that contains methods to insert and delete elements on the index basis. G</span><span style="color: #222222">roovy lists are plain JDK</span><span style="color: #222222"> </span>[<span style="color: #222222">java.util.List</span>](https://docs.oracle.com/javase/8/docs/api/java/util/List.html)<span style="color: #222222">[,](https://docs.oracle.com/javase/8/docs/api/java/util/List.html)</span><span style="color: #222222"> as Groovy doesn’t define its own collection classes. You can create multi-dimensional lists too. See </span>[<span style="color: #222222">here</span>](http://docs.groovy-lang.org/latest/html/documentation/#_lists)<span style="color: #222222"> for more information on Lists.</span>

**Instantiating a List:**

<span style="color: #222222">You can initialize a list delimiting the values </span><span style="color: #222222">by commas and surrounded by square brackets. </span><span style="color: #222222">You can also create lists containing values of heterogeneous types:</span>

##### **List**

```groovy
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
```

<span style="color: #222222">**Accessing a List:**</span>

- <span style="color: #222222">You can access the first element of the list on zero-based counting: </span>`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

<span style="color: #353833">Set is a collection that contains no duplicate elements. </span><span style="color: #000000">Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. All these permit null values too.</span>

**Instantiating a Set:**

<span style="color: #222222">You can initialize a Set delimiting the values </span><span style="color: #222222">by commas and surrounded by square brackets. A Set can have </span><span style="color: #222222">values of heterogeneous types:</span>

##### **Set**

```groovy
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
```

## <span style="color: #000000">Maps</span>

<span style="color: #222222">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 </span>[<span style="color: #222222">here</span>](http://docs.groovy-lang.org/latest/html/documentation/#_maps)<span style="color: #222222"> for more information on Maps.</span>

**<span style="color: #222222">Initialising a Map:</span>**

<span style="color: #222222">You need to pass quoted strings if your key string isn’t a valid identifier Eg: "block-no". Y</span><span style="color: #222222">ou must surround a variable or expression with parentheses, when </span><span style="color: #222222">y</span><span style="color: #222222">ou need to it as a key in your map definition. Eg:</span>

##### **Map**

```groovy
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
```

<span style="color: #000000">**Accessing the elements of a Map:**</span>

- Check the value associated with the key, `red`: `colors["red"]`
- <span style="color: #000000">Add a new pair to the Map: </span>`colors["pink"] = "``#FF00FF"`<span style="color: #000000"> or </span>`colors.pink = "``#FF00FF"`
- <span style="color: #000000">Check the Map contains a specific key: </span>`colors.blue == true`

## Ranges

<span style="color: #000000">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 </span>[<span style="color: #000000">here</span>](http://docs.groovy-lang.org/latest/html/documentation/#_range_operator)<span style="color: #000000"> for more information on Ranges.</span>

**<span style="color: #222222">Instantiating a Range:</span>**

##### **Range**

```groovy
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
def days = yesterday..today
```

<span style="color: #000000">**Accessing the elements of a Range:**</span>

- <span style="color: #000000">Check the range contains a specific element: </span>`r.contains(10) == false`
- <span style="color: #000000">Size of the range: </span>`days.size() == 2`