Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - String concat() method



concat() method is used to concatenate a string to the end of the string.

Syntax

String concat(String str)

Parameters

str − the string that is to be concatenated to the end of this String.

Return Value

This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters.

Example - Concatenating two Not-Null Strings

Following is an example of the usage of this method. If the given string value is not null, the concat() method concatenates them and returns a new string.

Example.groovy

class Example { 
   static void main(String[] args) { 
      //create an object of the String
      String str1 = new String("Hello");
      String str2 = new String(" World");
      println("The given string values are: " + str1 + " and" + str2);
      
      //using the concat() method
      println("After concatenation the new string is: " + str1.concat(str2));
   } 
}

Output

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

The given string values are: Hello and World
After concatenation the new string is: HelloWorld

Example - Getting Exception while Concatenating a Null String

Following is an example of the usage of this method. If the given string argument value is null, this method throws a NullPointerException

Example.groovy

class Example { 
   static void main(String[] args) { 
      try {
         
         //instantiate the String class
         String str1 = new String("Hello");
         String str2 = new String();
         str2 = null;
         println("The given string values are: " + str1 + " and " + str2);
         
         //using the concat() method
         println("After concatenation the new string is: " + str1.concat(str2));
      } catch(NullPointerException e) {
         e.printStackTrace();
         println("Exception: " + e);
      }
   } 
}

Output

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

The given string values are: Hello and null
java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "str" is null

Example - Concatenating two empty Strings

Following is an example of the usage of this method. If the given string values are empty, the concat() method returns an empty string.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // create the String literals
      String str1 = "";
      String str2 = "";
      System.out.println("The given string values are: " + str1 + ", " + str2);
         
      // using the concat() method
      System.out.println("After concatenation the new string is: " + str1.concat(str2));
   } 
}

Output

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

The given string values are: ,
After concatenation the new string is: 
groovy_strings.htm
Advertisements