Sidebar LogoHomeIndexIndexGitHub </> Back Next Basics

Basics


Hello, world!

The program is:

project1/hello_world.groovy
println "Hello world!"

The execution is:

>groovy hello_world.groovy
Hello world!

See here to know how to compile a Java class file out of this Groovy script and to run it in Java runtime.


Variables

Also see [groovy_site, Semantics].

project1/variables.groovy
// variable type inference
def _value1 = 52       // underscore may be the first symbol in identifier names
println _value1.class  // class java.lang.Integer

Double doubleValue = 52   // type may also be specified explicitly
println doubleValue       // 52.0

globalName = "Bob" // omitting type makes the variable global

def printName() {
    println globalName
    // println doubleValue // ERROR
    // groovy.lang.MissingPropertyException: No such property: doubleValue for class: variables
}

printName()  // Bob

var interpolatedString = "${globalName}'s age is $doubleValue" // {} may be omitted
// `var` is a synonym for `def`
println interpolatedString  // Bob's age is 52.0

def literalString = '${globalName} is $doubleValue years old'
println literalString // ${globalName} is $doubleValue years old

def (a, b, c) = ["first", 23, true]   // Multiple assignments (destructuring)
print a; print b; print c; println() // first23true

def (a1, b1, c1) = ["first", 23] // not all values provided - variable will get the default value
print a1; print b1; print c1; println() // first23null

def (int a2, int b2) = [100, 200, 300] // types specified, unused values will be ignored
print a2; print b2; println() // 100200

Data types

Also see [groovy_site, Object orientation].

Numbers

project1/data_types_numbers.groovy
println "Type | Min value | Max value"
println "---- | --------: | --------:"
println "byte | " + Byte.MIN_VALUE + " | " + Byte.MAX_VALUE
println "short | " + Short.MIN_VALUE + " | " + Short.MAX_VALUE
println "int | " + Integer.MIN_VALUE + " | " + Integer.MAX_VALUE
println "long | " + Long.MIN_VALUE + " | " + Long.MAX_VALUE
println "float | " + Float.MIN_VALUE + " | " + Float.MAX_VALUE
println "double | " + Double.MIN_VALUE + " | " + Double.MAX_VALUE
println "char | " + (int) Character.MIN_VALUE + " | " + (int) Character.MAX_VALUE
>groovy data_types_numbers.groovy > data_types_numbers_out.txt

The result is:

Type Min value Max value
byte -128 127
short -32768 32767
int -2147483648 2147483647
long -9223372036854775808 9223372036854775807
float 1.4E-45 3.4028235E38
double 4.9E-324 1.7976931348623157E308
char 0 65535

Strings

Also see:

project1/data_types_strings.groovy
def s1 = "a"
println s1.getClass().getName() // java.lang.String

def char c1 = "a" // double quotes may be used for the `char` data type
println c1.getClass().getName() // java.lang.Character

def gs = "value = ${2 + 2}"
println gs.getClass().getName() // org.codehaus.groovy.runtime.GStringImpl
println gs // value = 4

String multiline = """
 1
 2
""" // three single quotes may be also used
println multiline.collect { String.format("0x%02X", (int) it) }
// [0x0A, 0x20, 0x31, 0x0A, 0x20, 0x32, 0x0A]
// 0x0A - newline, 0x20 - space

def numbers = "abcde"
println numbers[2] // c
println numbers[-1] // e
println numbers[1..3] // bcd
println numbers[3..1] // dcb
println numbers[0, 2, 4] // ace
println numbers.substring(3) // de
println numbers.subSequence(1, 3) // bc
println numbers.toList() // [a, b, c, d, e]
println numbers.equalsIgnoreCase("Abcde") // true

def spaced = "May      there are always be sunshine!"
println spaced.split() // [May, there, are, always, be, sunshine!]

println "Groovy " * 3 // Groovy Groovy Groovy

println(/"slashy" string/) // "slashy" string
// println /"slashy" string/ // doesn't work without braces

println(/Slashy strings 
are multiline. \/Slashes\/ must be masked./) 
// Slashy strings
// are multiline. /Slashes/ must be masked.

println($/Dollar slashy string. Dolar ($$) is the escape symbol./$)
// Dollar slashy string. Dolar ($) is the escape symbol.

Boolean

Also see [groovy_site, The Groovy Truth].

Different value types may be converted to boolean when required.

project1/data_types_boolean.groovy
assert "a"
assert !""
assert [1, 2]
assert ![]
assert 1
assert !0

String process(int n) {
    if (n > 0) return ""
    return "wrong argument"
}

assert process(0)
assert !process(1)

Operators

Also see [groovy_site]:

project1/operators.groovy
assert 3 + 5 == 8
def (int a, int b) = [7, 4]
assert a / b == 1.75 // normal division
assert a.intdiv(b) == 1 // integer division
assert 5 % 3 == 2   // modulo (remainder)
assert 3 ** 3 == 27 // power

int i = 3
assert "${i++}, ${i}" == "3, 4" // postfix increment
assert "${--i}, ${i}" == "3, 3" // prefix decrement

i **= 2 // assignment operators
assert i == 9

assert 1 == 1 || 5 >= 3
assert false && true || true       // && has precedence
assert !(false && (true || true))

// bitwise operators
assert (0b0011 & 0b0101) == 0b0001
assert (0b0011 ^ 0b0101) == 0b0110
assert (~0b01 & 0b11)  == 0b10 // bitwise negation (we need the mask 0b11 to cut the sign digit)

def result = i > 0 ? "OK" : "" // ternary operator
assert result // using the "Groovy truth" rules

def String greeting(String name) {
    return "Hello ${name ?: "stranger"}!" // Elvis operator ?:
}

assert greeting("Bob") == "Hello Bob!"
assert greeting("") == "Hello stranger!"

// Overloading
class Bag {
    int size
    Bag(int size) { this.size = size }
    Bag plus(Bag other) { 
        new Bag(this.size + other.size) // `return` is not required
    }
}

def bag1 = new Bag(2)
def bag2 = new Bag(3)

println((bag1 + bag2).size) // 5

Control structures

Conditionals

Also see [groovy_site, 1.3.1. Conditional structures].

project1/conditionals.groovy
def n = 17
if (n > 0)
    println 'positive'
else if (n == 0)
    println 'zero'
else {
    print 'unfortunately '
    println 'negative'
}
// positive

String result
switch (n) {
    case 0:
        result = "zero"
        break
    case {n > 0}:              // not like in Java
        result = "positive"
        break
    case {n < 0}:
        result = "negative"
        break
    default:
        result = "invalid"
}
println result // positive

Loops

Also see [groovy_site, 1.3.2. Looping structures].

project1/loops.groovy
for (def i = 0; i < 5; ++i) 
    print i + " "
println() // 0 1 2 3 4

for (def i in 1..5) 
    print i + " "
println() // 1 2 3 4 5

for (int fib in [1, 1, 2, 3, 5, 8, 13]) 
    print fib + " "
println() // 1 1 2 3 5 8 13

["a", "b", "c", "d", "e"].each {print it}
println() // abcde

2.upto(5) {print it} // `it` is an explicit loop variable
println() // 2345

4.times {print it}
println() // 0123

3.step(10, 2) {print it}
println() // 3579

String result = ""
Random random = new Random()
while (result.length() < 20)
    result += random.nextInt(9) + " "
println result // 5 7 1 7 8 4 3 1 4 1

do {
    println "This will be printed at least one time"
} while (false)

Exception handling

Also see [groovy_site, 1.3.3. Exception handling].

project1/exceptions.groovy
// def d = 5 / 0
// Caught: java.lang.ArithmeticException: Division by zero
// java.lang.ArithmeticException: Division by zero
//         at exceptions.run(exceptions.groovy:2)

try {
    def d = 5 / 0
} catch (ArithmeticException e) {
    println e.getCause()     // null
    println e.getMessage()   // Division by zero
} finally {
    println "This will be printed anyway." // This will be printed anyway.
}

class CloseMe implements Closeable {

    private String name

    public CloseMe(String name) {
        this.name = name
    }

    @Override
    void close() throws IOException {
        println "closed $name"
    }
}

CloseMe closeMe1 = new CloseMe("1")

try (
    closeMe1 // existing resource may be closed as well
    CloseMe closeMe2 = new CloseMe("2")
) {
    // do something
} // here the resource closing is done

// The output is:
// closed 2
// closed 1

 


Back Next