Sunday, 13 January 2019

Groovy: Strings


Strings are collection of characters. Groovy supports 3 types of strings.
a.   Single Quoted Strings
b.   Double Quoted Strings
c.    Triple Quoted Strings

Single Quoted Strings
Collection of characters surrounded by single quotes. These string are instances of ‘java.lang.String’ class.

HelloWorld.groovy
String message = 'Hello World'

println message
println message.class

Output
Hello World
class java.lang.String

Double Quoted Strings
Collection of characters surrounded by double quotes.


HelloWorld.groovy
String message = "Hello World"

println message
println message.class

Output
Hello World
class java.lang.String

Double quoted strings support string interpolation. Interpolation is a technique to replace the value of an expression or variable upon evaluation of a string.

How to write interpolate expressions?
Surround the expression by ${} or prefix with $ for dotted expressions.


HelloWorld.groovy
String name = "Krishna"
int age = 29

String result = "Hello Mr.${name}, you are ${age} years old"

println result

Output
Hello Mr.Krishna, you are 29 years old

Double quoted strings are instances of java.lang.String if there’s no interpolated expression, but are instances of groovy.lang.GString instances if interpolation is present.

Can I insert multiple statements in a placeholder?
Yes, you can insert multiple statements in a placeholder.


HelloWorld.groovy
println "Sum of 1 and 2 is ${int a = 1, b = 2; a + b}"
println "Subtraction of 1 and 2 is ${int a = 1, b = 2; a - b}"
println "Multiplicaion of 1 and 2 is ${int a = 1, b = 2; a * b}"
println "Division of 1 and 2 is ${int a = 1, b = 2; a / b}"

$ sign prefixing a dotted expression


HelloWorld.groovy
class Employee{
	String firstName
	String lastName
}

Employee emp = new Employee()
emp.firstName = "krishna"
emp.lastName = "Gurram"

println "Employee first name $emp.firstName, last name $emp.lastName"

Output
Employee first name krishna, last name Gurram


Previous                                                 Next                                                 Home

No comments:

Post a Comment