Groovy Basic Examples
1) String Usage
String usage in Groovy is similar to many programming languages, but Groovy has some unique features. Here are the basics of String usage:
String s1 = 'Single-quoted string'
String s2 = "Double-quoted string"
String s3 = '''Triple-quoted
multi-line
string'''
In Groovy, you can directly add variable values in double-quoted strings. This feature is called "String interpolation" or "GString".
String ad = "Ali"
String selam = "Merhaba, ${ad}!"
println(selam) // Output: Merhaba, Ali!
2) Differences Between Single, Double, and Triple Quote Usage in Strings
In Groovy, you can use single quote ('), double quote ("), and triple quote (''' or """) to define String. The differences in their usage are:
Single Quote (' '):
- Single-quoted strings are plain strings.
- String interpolation (variable insertion) cannot be done within them.
String s1 = 'Merhaba, ${isim}!'
println(s1) // Output: Merhaba, ${isim}!
Double Quote ("):
- Double-quoted strings are known as "GString".
- String interpolation (variable insertion) can be done within them.
String isim = "Ali"
String s2 = "Merhaba, ${isim}!"
println(s2) // Output: Merhaba, Ali!
Triple Quote('''):
- Used to define multi-line strings.
- String interpolation can be done within them.
String isim = "Ali"
String s3 = '''Merhaba,
${isim}!
Nasılsın?'''
println(s3)
// Output:
// Merhaba,
// Ali!
// Nasılsın?
3) Checking if String is Empty in Groovy
In Groovy, you can use the isEmpty() method to check if a string is empty.
String s = ""
if(s.isEmpty()) {
println("String is empty!")
} else {
println("String is not empty!")
}
4) Checking if Object is Empty in Groovy
In Groovy, you can use == null or != null expressions to check if an object is empty.
def obj = null
if(obj) {
println("Object is not empty!")
} else {
println("Object is empty!")
}
Output: "Object is empty!"
5) For Loop in Groovy
A for loop in Groovy is written as in Java. A basic example:
def toplam = 0
for(int i = 0; i < 10; i++) {
toplam +=i
responseBodyTextToClient = "toplam: ${toplam}"
}
//Output : "toplam: 45"