Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - String repeatition



Syntax

The repetition of strings can be done by the simple * operator or using repeat() method.

String * number 

Parameters

The parameters will be

  • A string as the left operand for the * operator

  • A number at the right side of the operator to indicate the number of times the strings needs to be repeated.

Return Value

The return value is a string.

Example - Repeating a string literal

Following is an example of the usage of repeating a string literal in Groovy −

Example.groovy

class Example { 
   static void main(String[] args) { 		
      println("Hello " * 3); 
   } 
}

Output

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

Hello Hello Hello 

Example - Repeating a string using string variable

Following is an example of the usage of repeating a string variable value in Groovy −

Example.groovy

class Example { 
   static void main(String[] args) { 	
      String text = "Hello ";   
      println(text * 3); 
   } 
}

Output

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

Hello Hello Hello 

Syntax - Use of repeat() method

String.repeat(n)

Parameters − The parameters will be a number of times a string is to be repeated.

Return Value − The return value is a repeated string

Example - Repeating Strings using repeat method

Following is an example of the string repeatition using repeat() method in Groovy.

Example.groovy

class Example { 
   static void main(String[] args) { 	
      String text = "Hello ";   
      println(text.repeat(3)); 
      println("Hello ".repeat(3)); 
   } 
}

Output

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

Hello Hello Hello 
Hello Hello Hello 
groovy_strings.htm
Advertisements