Trending
- The Documentation Crisis Nobody Sees: Why AI Agents Are Breaking Faster Than Humans Can Document Them
- Stop Loading Everything into Redshift: A Spectrum + Iceberg Pattern for Hybrid Analytics
- Engineering Closed-Loop Graph-RAG Systems, Part 1: From Retrieval to Reasoning
- Parallel Kafka Batch Processing With Kotlin Coroutines in Spring Boot
Concatenate Strings in Groovy
Learn more about how to concatenate different types of string representations in Groovy.
Join the DZone community and get the full member experience.
Join For Free1. Introduction
Groovy has two ways of instantiating strings. One is plain java.lang.Stringand the second is groovy.lang.GString.
Plain string is represented with a single or double quote. However, the single quote doesn't support interpolation. Interpolation is supported only with a double quote, and when it is present, it becomes GString. In this article, we will see the different types of string representations in Groovy and how to concatenate them.
2. Types of Strings
So, there are four main types of string representations that are instantiated either through java.lang.Stringor groovy.lang.GStringin Groovy — single-quoted string, double-quoted string, GString, and triple single-quoted string. Let's talk about them with some examples:
Let's first see the single-quoted string. It is also known as a plain string:
'My name is Joe Smith'
Here is an example for double-quoted string:
"My name is Joe Smith"
Double-quoted string also supports interpolation. When we add interpolation in it, it becomesGString. An interpolation is an act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by${}:
"My name is $name"
Now, we will see the example of a triple single-quoted string. It is used for multiline string, but it doesn’t support interpolation:
'''
My name is
Joe
Smith
'''
Now, let's see how to do concatenation of these different types of strings.
3. Using + Operator
Let's start with the simple +operator to see how we can concatenate two plain strings:
'My name is ' + first + ' ' + last
Note, here firstand lastare variables.
Let's write a simple test that sets the value of the firstand lastvariable and verify if the return string is as expected:
name.first = 'Joe';
name.last = 'Smith';
def expected = 'My name is Joe Smith'
assertToString('My name is ' + first + ' ' + last, expected)
Similarly, we can use the double-quote instead of single-quote for concatenating the two plain strings.
4. Using GString
Let's now do the concatenation with GString:
"My name is $first $last"
The output of this string will be:
My name is Joe Smith
Note: here, we have used the double-quote instead of single-quote. If we use single-quote, it will consider $firstand$lastas literals, and the output will be:
My name is $first $last
5. Using GString Closure
A closure in Groovy is an open, anonymous block of code that can take arguments, return a value, and be assigned to a variable.
In GString, when the placeholder contains an arrow, ${→}, the expression is actually a closure expression. Let's see the below example:
"My name is ${-> first} ${-> last}"
Let's do a simple test to understand the difference between GStringand GStringclosure:
def first = "Joe";
def last = "Smith";
def eagerGString = "My name is $first $last"
def lazyGString = "My name is ${-> first} ${-> last}"
assert eagerGString == "My name is Joe Smith"
assert lazyGString == "My name is Joe Smith"
first = "David";
assert eagerGString == "My name is Joe Smith"
assert lazyGString == "My name is David Smith"
Here, eagerGStringrepresents plain interpolation of GStringand lazyGStringrepresents interpolation with closure expression.
We also notice here that in plain interpolation, the value is actually bound at the time of creation of the GString. That's why there is no change in eagerGStringvalue even after changing the firstvariable value.
However, with a closure expression, the closure is called upon each coercion of the GStringinto String, resulting in an updated lazyGStringcontaining the new value of the firstvariable.
6. Using StringConcat Method
Now, let's see how to use the String classconcat()method to do the concatenation:
'My name is '.concat(first).concat(' ').concat(last)
7. Using LeftShift << Operator
Next, let's see the usage of the left shift '<<' operator to concatenate the strings:
'My name is ' << first << ' ' << last
Stringclass also has a leftShift()method that overrides the << operator to provide an easy way of appending strings.
8. Using Array JoinMethod
We will now use an Array to concatenate the objects. An Array has a method called join(), which concatenates the toString() representation of each item in the array, with the given Stringas a separator between each item.
['My name is', first, last].join(' ')
Note: here the separator is an empty space.
9. Using Array InjectMethod
Next, let's see how to use an inject(Object initialValue, Closure closure)method of Array to do the concatenation. This method iterates through the given object, passing in the initial value to the closure along with the first item:
[first,' ', last]
.inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString()
So, here it iterates through the array having [first, ' ', last]. It will pass the initial value as 'My name is ' and then keep appending each element of the array 'Joe' (value of first), ' ', 'Smith' (value of last).
10. Using StringBuilder
Now, let's use theStringBuilderappend()method for concatenating the String objects:
new StringBuilder().append('My name is ').append(first).append(' ').append(last)
11. Using StringBuffer
Next, let's see how to use of the StringBuffer append()method to do the concatenation:
new StringBuffer().append('My name is ').append(first).append(' ').append(last)
12. Concatenate Multiline String
Now, let's see how to do concatenation for triple single-quoted (''' ''') strings:
name.first = '''
Joe
Smith
''';
name.last = 'Junior'
We can use any of the methods discussed in this article to concatenate this triple single-quoted string with other String objects. Let us take one example of how to do it using String concat()method:
'My name is '.concat(first).concat(' ').concat(last)
The output of the String will be:
'''My name is
Joe
Smith
Junior''';
Note that there is an empty space before 'Junior'. concat(' ')method has added this. However, String does have a stripIndent()method to remove such indentation.
13. Conclusion
To summarize, in this article, we have seen various ways of doing the String concatenation in Groovy.
The full implementation of this tutorial can be found over on GitHub.
Opinions expressed by DZone contributors are their own.
Related
-
DataWeave: Play With Dates (Part 1)
-
Tired of Messy Code? Master the Art of Writing Clean Codebases
-
The Long Road to Java Virtual Threads
-
Exploring Exciting New Features in Java 17 With Examples
