Data Types

This section covers simple data types in the Groovy language, collections are a complex complex data types and is covered in the next section.

Groovy Data Types

Groovy supports only Wrapper objects which are listed below, although you could for an example use a byte in the code it autoboxes it to a Byte, some of the data types I will cover in more depth in later sections.

Data Type Wrapper Min/Max Description
byte Byte -128 to 127 represent a byte value
short Short -32,768 to 32,767 represent a short number
int Integer -2,147,483,648 to 2,147,483,647 represent a int value
long Long -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 represent a long value
float Float 1.40129846432481707e-45 to 3.40282346638528860e+38 represent a float value
double Double 4.94065645841246544e-324d to 1.79769313486231570e+308d represent a int value
n/a BigInteger n/a represent a BigInteger value
n/a BigDecimal n/a represent a BigDecimal value
char Character 0 to 65535 represent a char value
n/a Boolean True or False represent a Boolean value
n/a String n/a represent a int value

Here are some examples

Data type examples
byte b = 10                                                 // Byte
println b.class

short s = 1000                                              // Short
println s.class

float f = 1.25                                              // Float - no need to add the f at the end
println f.class

paul = 52                                                   // Integer - you don't even need the data type
println paul.class

def x = 52.6576534                                          // BigDecimal - using the def keyword instead of a specific data type
println x.class

// Groovy will automatically bump up the data type to match the number
println 3.class                                             // Integer
println 432423423423443.class                               // Long
println 975985793475098437598347958734.class                // BigInteger
println 1.345345.class                                      // BigDecimal
println 4.543757349875098437590437594378597345.class        // BigDecimal

// You can use underscores
println 2_167_876.class                                     // Integer

// Display min and max values of a data type
println(Short.MIN_VALUE)                                    // -32768
println(Short.MAX_VALUE)                                    // 32767


Note: if you know what type a value is going to be and it won't change you should really use that type

Numbers

There a few differences with Java and Groovy that you should be made aware of, these are shown in the examples below

Groovy and Numbers
/ Groovy Number Defaults
// ----------------------------------------------------------------------

def number = 10                                 // Integer
println number.class

def decimal = 5.50
println decimal.class                           // BigDecimal

// :: Converting Data Types ::
// ----------------------------------------------------------------------
// Explicit - casting

def myFloat = (float) 1.0
println myFloat.class                           // cast to a Float

// Implicit - coercion

def decimal = 5.50
println decimal.class                           // the conversion happens behind the scenes


// Rules for +,-,*
// ----------------------------------------------------------------------

// If either operand is a Float or a Double the result is a Double
// In Java if only Floats are involved the result is a Float

Float f = 5.25
Double d = 10.50

def result = d / f
println result
println result.class                            // Double

Float a = 10.75
Float b = 53.75
def result2 = b / a
println result2
println result2.class                           // Double

// If either operand is a big decimal

def x = 34.5                                    // BigDecimal
def y = 15
def bigResult = x / y
println bigResult
println bigResult.class                         // BigDecimal


// If either operand is a BigInteger the result is a BigInteger
// If either operand is a Long the result is a Long
// If either operand is a Integer the result is an Integer

// Double division
println 5.0d - 4.1d                             // results may be rounded
println 5 - 4.1                                   // will give correct result

// Integer Division

def intDiv = 1 / 2
println intDiv                                  // this is much different than Java where we would get 0
println intDiv.getClass().getName()
println 1.intdiv(2)                             // this is more like Java
Groovy number methods
assert 2 == 2.5.toInteger()             // conversion
assert 2 == 2.5 as Integer              // enforced coercion
assert 2 == (int) 2.5                   // cast

assert '5.50'.isNumber()                // convert a string into a number
assert 5 == '5'.toInteger()             // convert a string into a Integer

// times | upto | downto | step

20.times {
    print '-'
}

1.upto(10) { num ->
    println num
}

10.downto(1) { num ->
    println num
}

0.step(1,0.1) { num ->
    println num
}

Operator Overloading

Groovy allows you to overload the various operators so that they can be used with your own classes, you have methods like plus(), minus(), multiply(), div(), power() and many more

Overload example
def a = 1
def b = 2

println a + b               // behind the scenes its uses the plus() method
println a.plus(b)           // the overloaded method

def s1 = "Hello"
def s2 = ", World!"

println s1 + s2
println s1.plus(s2)         // the overloaded method
Overload plus class method example
class Account {

    BigDecimal balance

    // the overloaded method (+), remember + is the plus() method
    Account plus(Account other) {
        new Account( balance: this.balance + other.balance )
    }
    
    String toString(){
        "Account Balance: $balance"
    }

}

Account savings = new Account(balance:100.00)
Account checking = new Account(balance:500.00)

println savings
println checking
println savings + checking          // remember + is plus() method, it runs the overloaded method Account::plus

Strings

Everything in Groovy in single or double quotes is a String unless you specific use a Character data type for a single character.

String examples
char c1 = 'c'
println c1.class                            // Character

def c2 = 'c'
println c2.class                            // String

def str2 = 'this is a string'
println str2.class                          // String

// string interpolation
String name = "Paul"
String msg2 = "Hello ${name}"               // String interpolation, must use double quotes
println msg2

String msg3 = 'Hello ${name}'
println msg3

String msg4 = "We can evaulate expressions here: ${1 + 1}"
println msg4
Multi-line strings
// use triple quotes """ .... """
def aLargeMsg = """
A 
Msg
goes 
here and 
keeps going ${1+1}
"""

println aLargeMsg
dollar slashy (escaping)
// the test is surrounded by $/ and /$
def folder = $/C:\groovy\paul\foo\bar/$
println folder

Regular Expressions

Groovy can use regular expressions to search and manipulate strings, the three basic operators are below, there are a number of special symbols you can use which I have already documented in my Java Regular Expressions section.

Here are some regex examples

Basic Regex
String slashy = /a\b/
println slashy
println slashy.class

String url = $/http://datadisk.co.uk/blog/$                 // use the dollar slashy $/ .. /$
println url

def pattern1 = ~/a\b/                                       // replaces the above
println pattern1.class
Find and Match
def text = "Being a Cleveland Sports Fan is no way to go through life" // true
def pattern2 = ~/Cleveland Sports Fan/
def finder = text =~ pattern2
def matcher = text ==~ pattern2

println "finder: " + finder
println "finder size: " + finder.size()
println "matcher: " + matcher               // must be exact match

// ----------------------------------------------------------------------------------

def text3 = "Cleveland Sports Fan"
def pattern3 = ~/Cleveland Sports Fan/
def matcher3 = text3 ==~ pattern3            // this is an exact match

println "matcher3: " + matcher3

if( matcher ) { /* do something */ }

// ----------------------------------------------------------------------------------

def text4 = "Being a Cleveland Sports Fan is no way to go through life" // true
def pattern4 = ~/Cleveland/
text = text4.replaceFirst(pattern4,"Buffalo")
println text