Grails Cookbook - A collection of tutorials and examples

Groovy String reverse()

Java developers will just love using Groovy. it is a natural transition because every library that can be used in Java can be used in Groovy, plus we get to use a wonderful programming language that is very convenient to use. For example, the String class reverse method. It reverses a String with no external library necessary to use, nor we need to code anything special. We explore in this post how to use Groovy String reverse method.

Groovy String reverse syntax

This is the syntax of the reverse method in Groovy String class.

public static String  reverse(String  self)

For those new to Groovy, reading this means there is no parameter, because self is default and not needed to be passed. The official documentation says this method Creates a new String which is the reverse (backwards) of this string. So it returns a new String with all the characters reversed. Very simple and straightforward. But very convenient because we are using Groovy!!!

Groovy String reverse example

There is nothing special on how we explain usage of reverse. Just see below example:

println "rex".reverse()

And this will reverse all the characters in the String, so we get this outpuit:
xer

And that is it. We can try more samples like below:

println "hello".reverse()
println "world".reverse()
println "love".reverse()
println "you".reverse()

And we get this output:
olleh
dlrow
evol
uoy