Check if String is Empty in Groovy

Check if String is Empty in Groovy

  • Groovy
  • 2 mins read

Here is an example of how to check if a string is empty in Groovy:

This code defines a is_empty function that takes a string as its argument, and checks if the string is null or empty. If the string is null or empty, the function returns true, otherwise it returns false. The code then tests the function with some strings, and prints the results to the console.

Check if String is Empty in Groovy Example

// Define a function to check if a string is empty
def is_empty(str) {
  if (str == null || str.isEmpty()) {
    return true
  } else {
    return false
  }
}

// Test the function with some strings
println is_empty("")  // should return true
println is_empty("hello")  // should return false
println is_empty(null)  // should return true

In this example, the is_empty function first checks if the given string is null or empty by using the == operator and the isEmpty method. If the string is null or empty, the function returns true, indicating that the string is empty. Otherwise, the function returns false, indicating that the string is not empty. The code then tests the function with three different strings, and prints the results to the console.

The output of the program would be:

true
false
true

You can modify this code to handle different cases or to use different comparison operators. For example, you could use the != operator to check if the string is not null or not empty, or the size() method to check if the string has a length greater than zero. You can also use the is_empty function in other parts of your program to check if a string is empty, and take appropriate action based on the result.