Learn Java for Web Development

(Tina Meador) #1

406 APPENDIX B: Introduction to Groovy


Listing B-8. Nested Double Quote in Single Quote


s1 = 'hello "vishal"'
println s1


Strings defined using double quotes will interpret embedded expressions within the string, as
illustrated in Listing B-9.


Listing B-9. Double-Quoted Strings Interpret Embedded Expressions


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


You can nest single quotes in double quotes, as illustrated in Listing B-10.


Listing B-10. Nested Single Quote in Double Quote


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


Multiline Strings

Groovy supports strings that span multiple lines. A multiline string is defined by using three
double quotes or three single quotes. Multiline string support is useful for creating templates or
embedded documents (such as XML templates, SQL statements, HTML, and so on). For example,
you could use a multiline string and string interpolation to build the body of an e-mail message,
as shown in Listing B-11. String interpolation with multiline strings works in the same way as it
does with regular strings: multiline strings created with double quotes evaluate expressions, and
single-quoted strings don’t.


Listing B-11. Using Multiline Strings


def name = "Vishal"
def multiLineString = """
Hello, ${name}
This is a multiline string with double quotes
"""
println multiLineString


Hello, Vishal
This is a multiline string with double quotes

Free download pdf