Single or Double Quotation Marks In Groovy

In Groovy you can choose between single quotation marks ' or double quotation marks " to represent a string. As opposed to Java, where single quotation marks denote a single character and double quotation marks denote a string.

Groovy provides groovy.lang.GString which you can think of a java.lang.String on steroids, as it has templating built-in.

For example, the value of a variable x should be included in a string, you can write:

def x = 1
println "Variable x has a value of ${x}"

Whereas in Java you had to write:

void test() {
    int x = 1;
    System.out.println("Variable x has a value of " + x);
}

Or by using a StringBuilder or StringBuffer:

void test() {
    int x = 1;
    StringBuilder builder = new StringBuilder();
    builder.append("Variable x has a value of ").append(x);
    System.out.println(builder.toString());
}

Difference

But what’s the difference in Groovy? With single marks a java.lang.String is created – no templating available – and with double quotation marks a GString can be used. So using GString where String is enough you will do unnecessary things and maybe loose performance.

Look at these examples:

Single quotation marks

println ''.getClass()
class java.lang.String

Double quotation marks, no template -> no GString

println "".getClass()
class java.lang.String

Single quotation marks with template (bad idea)

def x = 1
println '${x}'.getClass()
class java.lang.String

Double quotation marks with template

def x = 1
println "${x}".getClass()
class org.codehaus.groovy.runtime.GStringImpl
This entry was posted in Software Development and tagged , , . Bookmark the permalink.