N. P. O'Donnell, 2021
Groovy runs in the JVM. All valid Java is valid Groovy.
// hello-world.groovy
println("hello world")
Run with:
groovy hello-world.groovy
Alternatively, shebang line can be used and program can be invoked directly:
#!/usr/bin/env groovy
// hello-world.groovy
println("hello world")
Output:
user@dev:~/groovy$ chmod +x hello-world.groovy
user@dev:~/groovy$ ./hello-world.groovy
hello world
Program arguments are accessed through this.args
:
#!/usr/bin/env groovy
// args.groovy
print("Args are:")
for (int i = 0; i < this.args.size(); i++) {
print(" " + this.args[i]);
}
println()
Output of this program:
user@dev:~/groovy$ ./args.groovy 4 6
Args are: 4 6
Variables are dynamically typed and don't need to be declared:
#!/usr/bin/env groovy
// variables.groovy
x = 1
println(x)
x = 2
println(x)
x = 2.5
println(x)
x = "hi"
println(x)
x = true
println(x)
Output of this program:
user@dev:~/groovy$ ./variables.groovy
1
2
2.5
hi
true
The def
keyword is used to declare a variable without specifying a type, similar to the statement <classname> x;
in Java. The default value of a variable declared with def
is null
:
#!/usr/bin/env groovy
// def.groovy
def x
println(x)
x = 1
println(x)
x = "hi"
println(x)
Output of this program:
user@dev:~/groovy$ ./def.groovy
null
1
hi
Math is similar to Java, with a few caveats:
#!/usr/bin/env groovy
// math.groovy
println(2 + 2)
println(2.5 + 2.5)
println(2.5 - 3)
println(-2 + +2)
println(3 * 3)
println(12 / 5) // division casts to floats
println(12.intdiv(5))
println(2.multiply(3))
Output of this program:
user@dev:~/groovy$ ./math.groovy
4
5.0
-0.5
0
9
2.4
2
6
String length can be found using the length
accessor:
#!/usr/bin/env groovy
// stringlength.groovy
str = "Groovy"
println str.length()
Output of this program:
user@dev:~/groovy$ ./stringlength.groovy
6
Use single quotes if you want everything in the string to be interpreted literally.
#!/usr/bin/env groovy
// strings.groovy
name = "Jay"
println('Hey, ${name}')
println("Hey, ${name}")
Output of this program:
user@dev:~/groovy$ ./strings.groovy
Hey, ${name}
Hey, Jay
To spread a string over multiple lines without the need for concatenation and line-feeds:
#!/usr/bin/env groovy
// multstring.groovy
greeting = '''Hello
World
!
'''
print(greeting)
Output of this program:
user@dev:~/groovy$ ./multstring.groovy
Hello
World
!
Strings can be divided into smaller strings with string slices:
#!/usr/bin/env groovy
// stringslice.groovy
fullName = "Joe Bloggs"
firstName = fullName[0..2]
lastName = fullName[4..9]
println("First Name: ${firstName}, Last Name: ${lastName}")
Output of this program:
user@dev:~/groovy$ ./stringslice.groovy
First Name: Joe, Last Name: Bloggs
The *
operator creates a new string by repeating the same string multiple times:
#!/usr/bin/env groovy
// stringrep.groovy
str = "Doctor "
println(str * 2)
Output of this program:
user@dev:~/groovy$ ./stringrep.groovy
Doctor Doctor
Unlike Java, ==
and !=
can be used to test string equality:
#!/usr/bin/env groovy
// stringeq.groovy
str1 = "Groovy"
str2 = "groovy"
str3 = "Groovy"
println(str1 == str1)
println(str1 == str2)
println(str1 == str3)
println(str1 != str1)
println(str1 != str2)
println(str1 != str3)
Output of this program:
user@dev:~/groovy$ ./stringeq.groovy
true
false
true
false
true
false
A string can be split using the split
method:
#!/usr/bin/env groovy
// stringsplit.groovy
str = "I love groovy"
words = str.split(" ")
println("String was split into ${words.size()} words:")
for (i = 0; i < words.size(); i++)
println("${i + 1}. ${words[i]}")
Output of this program:
user@dev:~/groovy$ ./stringsplit.groovy
String was split into 3 words:
1. I
2. love
3. groovy
Either of these will convert the string into an array of individual characters:
str.split("")
str.toList()
str.split()
will split ignoring repeated whitespaces.
replaceAll
performs a find-and-replace within a string:
#!/usr/bin/env groovy
// stringreplace.groovy
str1 = "I love Java. Java is my favourite language."
str2 = str1.replaceAll("Java", "Groovy")
println(str1)
println(str2)
Output of this program:
user@dev:~/groovy$ ./stringreplace.groovy
I love Java. Java is my favourite language.
I love Groovy. Groovy is my favourite language.
Groovy has several ways to inject values into strings. This example prints the same line 3 different ways:
#!/usr/bin/env groovy
// stringformat.groovy
a = 42
b = 1.5
c = true
d = "Groovy"
println "a is $a, b is $b, c is $c, d is $d"
println("a is ${a}, b is ${b}, c is ${c}, d is ${d}")
printf("a is %d, b is %.1f, c is %b, d is %s\n", a, b, c, d)
Output of this program:
user@dev:~/groovy$ ./stringformat.groovy
a is 42, b is 1.5, c is true, d is Groovy
a is 42, b is 1.5, c is true, d is Groovy
a is 42, b is 1.5, c is true, d is Groovy
Reading input from console:
#!/usr/bin/env groovy
// input.groovy
print("What is your name? ")
name = System.console().readLine()
println("Hello, ${name}!")
Output of this program:
user@dev:~/groovy$ ./input.groovy
What is your name? Joe
Hello, Joe!