Summary of methods for Java to determine whether a string is empty

Source: Internet
Author: User
Tags java se

Here are four ways that Java determines whether a string is empty:

Method One: Most people use a method that is intuitive, convenient, but inefficient:

if (s = = NULL | | "". Equals (s));
Method Two: Compare string length, high efficiency, is the best I know of a method:

if (s = = NULL | | s.length () <= 0);
Method Three: Java SE 6.0 only begins to provide methods that are nearly equal in efficiency and method two, but for compatibility reasons it is recommended to use method two.

if (s = = NULL | | s.isempty ());

Method Four: This is a more intuitive, simple method, and the efficiency is very high, and the efficiency of method two or three is similar:

if (s = = NULL | | s = = "");

Note: s = = null is necessary to exist.

If the String type is null, the Go to equals (string) or length () will throw java.lang.NullPointerException.

and the order of S==null must appear in front, otherwise it will also throw java.lang.NullPointerException.

The following Java code:

String str = NULL;

if (Str.equals ("") | | Str= = = null) {//throws an exception

SYSTEM.OUT.PRINTLN ("Success");

}

". Equals (str); the rear ensures that no null error is encountered.

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.