Check if Variable is Null in Groovy

Check if Variable is Null in Groovy

  • Groovy
  • 2 mins read

This post provides an example of how to check if a variable is null in Groovy. The code defines a is_null function that takes a variable as its argument, and checks if the variable is null. If the variable is null, the function returns true, indicating that the variable is null. Otherwise, the function returns false, indicating that the variable is not null. The code then tests the function with some variables, and prints the results to the console.

Check if Variable is Null in Groovy Example

Here is an example of how to check if a variable is null in Groovy:

// Define a function to check if a variable is null
def is_null(var) {
  if (var == null) {
    return true
  } else {
    return false
  }
}

// Test the function with some variables
def name = null
println is_null("")  // should return false
println is_null(name)  // should return true
println is_null(null)  // should return true

This code defines a is_null function that takes a variable as its argument, and checks if the variable is null. If the variable is null, the function returns true, otherwise it returns false. The code then tests the function with some variables, and prints the results to the console. The output of the program would be:

false
true
true

In this example, the is_null function first checks if the given variable is null by using the == operator. If the variable is null, the function returns true, indicating that the variable is null. Otherwise, the function returns false, indicating that the variable is not null. The code then tests the function with three different variables, and prints the results to the console.

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 variable is not null, or the instanceof operator to check if the variable is an instance of a specific class. You can also use the is_null function in other parts of your program to check if a variable is null, and take appropriate action based on the result.

Related:

  1. Check if String is Empty in Groovy