Learn Java for Web Development

(Tina Meador) #1
APPENDIX B: Introduction to Groovy 405

GStrings


GStrings are an instance of groovy.lang.GString and allow placeholders to be included in the
text. GStrings are not a subclass of String because the String class is final and can’t be extended.
A GString is just like a normal string, but it allows the embedding of variables within it using ${..}.
The curly braces are required only if the embedded variable is a placeholder for an expression.
Groovy supports a concept found in many other languages such as Perl and Ruby called string
interpolation, which is the ability to substitute an expression or variable within a string. If you have
experience with Unix shell scripts, Ruby, or Perl, this should look familiar. Java doesn’t support string
interpolation. You must manually concatenate the values. Listing B-5 is an example of the type of
code you need to write in Java, and Listing B-6 shows the same code using a GString.


Listing B-5. Building Strings with Java


String name = "Vishal" ;
String helloName = "Hello " + name ;
System.out.println(helloName) ;


Listing B-6. String Interpolation in Groovy/GString



  1. str1= "Vishal"

  2. str2 = "Hello "

  3. println "$str2$str1"


In line 3, curly braces are not used because curly braces are required only if the embedded variable
is a placeholder for an expression. When Groovy sees a string defined with double quotes or slashes
and an embedded expression, Groovy constructs an org.codehaus.groovy.runtime.GStringImpl
instead of a java.lang.String. When the GString is accessed, the expression is evaluated. Notice
that you can include any valid Groovy expression inside the ${} notation; this includes method calls
or variable names.


Groovy supports single-line strings and the strings that span multiple lines. In the sections that
follow, you will learn a variety of strings supported in Groovy.


Single-Line Strings

Single-line strings can be single quoted or double quoted. A string enclosed in single quotes is taken
literally. Strings defined with single quotes do not interpret the embedded expressions, as illustrated
in Listing B-7.


Listing B-7. Single-Quote Strings Do Not Interpret Embedded Expressions


name = "vishal"
s1 = 'hello $name'
println s1
Here is the output:
hello $name


You can nest a double quote in a single quote, as illustrated in Listing B-8.

Free download pdf