Concatenate Strings with Groovy

1. Overview

In this tutorial, we’ll look at several ways to concatenate Strings using Groovy. Note that a Groovy online interpreter comes in handy here.

We’ll start by defining a numOfWonder variable, which we’ll use throughout our examples:

def numOfWonder = 'seven'

2. Concatenation Operators

Quite simply, we can use the + operator to join Strings:

'The ' + numOfWonder + ' wonders of the world'

Similarly, Groovy also supports the left shift << operator:

'The ' << numOfWonder << ' wonders of ' << 'the world'

3. String Interpolation

As a next step, we’ll try to improve the readability of the code using a Groovy expression within a string literal:

"The $numOfWonder wonders of the world\n"

This can also be achieved using curly braces:

"The ${numOfWonder} wonders of the world\n"

4. Multi-line Strings

Let’s say we want to print all the wonders of the world, then we can use the triple-double-quotes to define a multi-line String, still including our numOfWonder variable:

"""
There are $numOfWonder wonders of the world.
Can you name them all?
1. The Great Pyramid of Giza
2. Hanging Gardens of Babylon
3. Colossus of Rhode
4. Lighthouse of Alexendra
5. Temple of Artemis
6. Status of Zeus at Olympia
7. Mausoleum at Halicarnassus
"""

5. Concatenation Methods

As a final option, we’ll look at String‘s concat method:

'The '.concat(numOfWonder).concat(' wonders of the world')​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

For really long texts, we recommend using a StringBuilder or a StringBuffer instead:

new StringBuilder().append('The ').append(numOfWonder).append(' wonders of the world')
new StringBuffer().append('The ').append(numOfWonder).append(' wonders of the world')​​​​​​​​​​​​​​​

6. Conclusion

In this article, we had a quick look at how to concatenate Strings using Groovy.

As usual, the full source code for this tutorial available over on GitHub.

Leave a Reply

Your email address will not be published.