Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Concatenation of Strings



The concatenation of strings can be done by the simple + operator or using concat() method provided by String class.

Syntax - Use of + Operator

String + String

Parameters − The parameters will be 2 strings as the left and right operand for the + operator.

Return Value − The return value is a concatenated string

Example - Concatenating Strings using + operator

Following is an example of the string concatenation in Groovy.

Example.groovy

class Example {
   static void main(String[] args) {
      String a = "Hello";
      String b = " World";
		
      println("Hello" + " World");
      println(a + b);
   }
}

Output

When we run the above program, we will get the following result −

Hello World
Hello World

Syntax - Use of concat() method

String.concat(String)

Parameters − The parameters will be a string to be concatenated.

Return Value − The return value is a concatenated string

Example - Concatenating Strings using concat method

Following is an example of the string concatenation using concat() method in Groovy.

Example.groovy

class Example {
   static void main(String[] args) {
      String a = "Hello";
      String b = " World";
      String concatenatedString = a.concat(b);	 	
      
      println(concatenatedString);
   }
}

Output

When we run the above program, we will get the following result −

Hello World

Example - Concatenating String literals using concat() method

Following is an example of the string literal concatenation using concat() method in Groovy.

Example.groovy

class Example {
   static void main(String[] args) {
      String concatenatedString = "Hello".concat(" World");
      println(concatenatedString);
   }
}

Output

When we run the above program, we will get the following result −

Hello World
groovy_strings.htm
Advertisements