Grails Cookbook - A collection of tutorials and examples

Groovy Compare String

We explore different examples of how String comparison behaves in Groovy. Below are some observations on Groovy compare String operations.

Using Groovy String Equals
We can declare Strings in Groovy using either single quotes or double quotes. Below is an example of the results of comparing Strings using equals:
println "Apple".equals("Apple");
println 'Banana'.equals('Banana');

Since the contents are compared, both will result to true:

true
true

We can mix and match single quotes or double quotes:

println "Carrots".equals('Carrots');
println 'Beans'.equals("Beans");

And it won't matter, the same results will be produced:

true
true

We may also use variables instead of String literals:

def testString = "Fruits"
println testString.equals('Fruits');
println testString.equals("Fruits");

And the output will be the same:

true
true

Using Groovy String ==

We can use the == operator to compare Strings in Groovy. Below are some examples:

println "Apple" == "Apple";
println 'Banana' == 'Banana';
println "Cheese" == 'Cheese';
println 'Lemon' == "Lemon";

The bahavior is the same, the compareTo are invoked to compare contents and will have all as true:

true
true
true
true

Using Groovy String compareTo

We can also compare Strings using compareTo. Below are some examples:

println "Apple" .compareTo("Apple");
println 'Banana' .compareTo( 'Banana');
println "Cheese" .compareTo( 'Cheese');
println 'Lemon' .compareTo( "Lemon");
CompareTo results to zero if the contents are the same:
0
0
0
0

GString and String

There is a small difference with GString, equals will fail if one is GString and the other is not. Below is an example to illustrate:

def testGstring = "${'Juice'}"
def testNormalString = "Juice" 
println testGstring.class
println testNormalString.class
println testGstring.equals(testNormalString)
println testNormalString.equals(testGstring)
println testGstring == testNormalString
println testGstring .compareTo(testNormalString)

And the comparison using equals will fail:

class org.codehaus.groovy.runtime.GStringImpl
class java.lang.String
false
false
true
0