Subscribe to The Way I See It        RSS Feed

Groovy Strings

Icon Leave Comment
I'm back again to write about Strings in Groovy. If you are like me, then you use strings for all sorts of things. Groovy has some nice features that make it a pleasure.


In Groovy, you can declare strings with single or double quotes. Double quotes denote GStrings--strings that allow expressions.
Here is an example of how easy it is to print out variables:

int age = 10
String name = 'Danny'

System.out.println("This person is " + name + "and they are" + age + "years old");

println("This person is ${name} and they are ${age} years old")

You'll notice a few things. First, no ugly System.out.println. println works just fine :^: Second, you'll notice that GStrings allows for a much more readable expression. Both lines are perfectly valid but why choose the first??? Note, GString and String are two distinct classes and mixing the two can lead to issues. I have yet to experience it, but the Groovy site warns

Multi-line Strings

Another nice feature about Groovy is that it allows you to instantiate strings that span multiple lines:

def name = 'Danny'

def text = """\
hello there ${name}
how are you today?


I'm in love with substrings. At my job, I have to parse all sorts of records and Groovy's substring notation makes me happy. I had an issue a few weeks ago where I needed the first character of a string to be lower case and this was my solution:

String string = 'TransactionName'
string = string[0].toLowerCase() + string [1..-1]

This illustrates a few things:

  • You can treat strings as an array of characters
  • You can grab a substring with [x..y]
  • [x..y] is inclusive unlike java's substring(x,y) where y is exclusive
  • You can easily reference from right to left with -x (-1 is the first character from the end)
  • Aubstring is bidirectional! (string[-1..0] would reverse the string)

That's all I have for today. Keep it groovy!

0 Comments On This Entry


Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

January 2022

2324252627 28 29

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)