Java skills sharing: three ways to determine whether a string is empty

Many friends who are new to Java must have encountered a situation where it is necessary to judge whether a string is empty, so do you know how to implement it? Today, Xiaoqian will introduce three different methods to everyone, and students will see which one is right for you.

There are three common ways to determine whether a string is empty:

1. str!=null;

2. "".equals(str);

3. str.length()!=0;

(Note: length is a property, the property of a general collection object, to obtain the size of the collection. For example: array.length is to obtain the length of the array. length() is a method, and general string objects have this method, which is also to obtain a string Length. For example: string.length();)

The following is the detailed code of the three ways

3.png

The first method is currently the most commonly used method. It is intuitive and convenient, but it is very inefficient. Running time on the machine is 141ms (machine performance varies, for reference only)

4.png

The second way is to compare the length of the string, which is more efficient and is a better method. The running time on the machine is 46ms (machine performance varies, just for reference)

5.png

The third method is the method provided by Java SE 6.0. The efficiency and method two are almost equal, but due to compatibility considerations, it is not recommended. Running time on the machine is 47ms (machine performance varies, for reference only)

After reading it, you must remember to type the code yourself. Many times your mind tells you to remember, but in fact your hand tells you that I did not remember~~~

This article is from Qianfeng Education , please indicate the source for reprinting.

Guess you like

Origin blog.51cto.com/15128702/2676124