Groovy Tip 3: How to Determine if an object is empty in an IF condition statement

Source: Internet
Author: User

In the Java language programming, the non null Judgment of object is an eternal topic. For example, we often need to judge a string as follows:

if(str!=null&&!str.equals(""))
  {
    ......
}

Typing such a statement really makes you sick, and sometimes you forget the "!" in the input "!str.equals" statement. Causes the code to have a logical error.

and agile Groovy language development does not require us to worry about such problems. The same judgment statement, we just need to enter the following code:

def str = null
  if(str)
  {
    println"str is not null"
  }
  else
  {
    println'str is null'
}

The execution result of this statement segment is:

STR is NULL

As can be seen, the IF (str) Judgment statement is not executed when STR is null. You might ask, what happens when str = '?

def str = ''
  if(str)
  {
    println"str is not null"
  }
  else
  {
    println'str is null'
}

The results of the execution are:

STR is NULL

In this way, we can rewrite the beginning of the Java code into the following code:

if(str)
  {
    ......
}

This is a lot simpler. Isn't it?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.