String judgment is null, string judgment
There are three methods to determine whether a string is null
(Note: length is an attribute. Generally, a collection class object has an attribute to obtain the set size. For example, array. length indicates that the attribute of the array gets the length of the array.
Length () is a method. Generally, this method is used to obtain the length of a string. Example: String. length ()
In java, there is a () Representation Method and no representation attribute)
Note:
String str1 = null; str reference is empty
String str2 = ""; stri references an empty String
4. When determining whether a string is null, make sure that it is not null and then determine its length. String str = "xxx"; if (str! = Null & str. lengt> 0)
Below is a code Test
public class TestEmpty { public static Long function1(int n, String s) { long startTime = System.nanoTime(); for (int i = 0; i < n; i++) { if (s == null || "".equals(s)) ; } long endTime = System.nanoTime(); return endTime - startTime; } public static Long function2(int n, String s) { long startTime = System.nanoTime(); for (int i = 0; i < n; i++) { if (s == null || s.length() <= 0) ; } long endTime = System.nanoTime(); return endTime - startTime; } public static Long function3(int n, String s) { long startTime = System.nanoTime(); for (int i = 0; i < n; i++) { if (s == null || s.isEmpty()) ; } long endTime = System.nanoTime(); return endTime - startTime; } public static void main(String[] args) { String s = "ss"; for (int i = 0; i < 20; i++) { System.out.println(function1(1000, s)); // 90788 System.out.println(function2(1000, s)); // 22499 System.out.println(function3(1000, s)); // 33947 System.out.println("---------------------------"); } }
Function2 and function3 are similar when the number of cycles is less than 100,
When it reaches 1000, it is obvious that there is less time for function2. We recommend that you use s = null | s. length () <= 0. The method for judging whether it is null is also s! = Null & s. length> 0 is short
Most references