Java String null and empty value processing __java

Source: Internet
Author: User

In the development process, the author often encountered the following errors in use:

1, Error usage one:

if (name = = "") {
Do something
}

2, Error usage two:
if (Name.equals ("")) {
Do something
}


3, Error usage three:
if (. Name.equals ("")) {
Do something

}



The above error usage 1 is the easiest for beginners, and the least likely to be found, because their syntax is no problem, the Java compiler compiles without error. However, this condition may cause a bug in the program at run time and will never be true, that is to say, the statement in the If block will never be executed.

The above usage two, usage Three's writing, is including many Java proficient also very easy to make the mistake, why is wrong. Maybe you'll be wondering.
Yes, the writing itself is correct, but, without a null judgment condition, imagine, if name=null, what will happen to the consequences? The consequence is that your program will throw NullPointerException exceptions, the system will be suspended and no longer provide normal service.
Of course, if you have previously made null judgments on name exceptions.

The correct wording should precede the condition of name!= NULL, as an example:

if (name!= null &&. Name.equals ("")) {
Do something
}

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.