DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

Trending

  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • AI’s Role in Everyday Development
  • Docker Base Images Demystified: A Practical Guide
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  1. DZone
  2. Coding
  3. Languages
  4. Concatenate Strings in Groovy

Concatenate Strings in Groovy

Learn more about how to concatenate different types of string representations in Groovy.

By 
Rajesh Bhojwani user avatar
Rajesh Bhojwani
·
Mar. 12, 19 · Presentation
Likes (5)
Comment
Save
Tweet
Share
294.6K Views

Join the DZone community and get the full member experience.

Join For Free

1. Introduction

Groovy has two ways of instantiating strings. One is plain java.lang.String and 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.String or  groovy.lang.GString in 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 first and last are variables.

Let's write a simple test that sets the value of the first and last variable 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 $first and$last as 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 GString and GString closure:

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, eagerGString represents plain interpolation of GString and lazyGString represents 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  eagerGString value even after changing the  first variable value.

However, with a closure expression, the closure is called upon each coercion of the GString into  String, resulting in an updated lazyGString containing the new value of the first variable.

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 String as 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.

Strings Data Types Groovy (programming language)

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

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!