Java method to determine whether a string is empty
Method 1: The most popular method, intuitive, convenient, but very efficient Low:
if(s == null || s.equals(""))
Method 2: Compare string lengths, high efficiency, the best method I know:
if(s == null || s.length() == 0)
length is an attribute, a property owned by a general collection class object, to obtain the collection the size of.
For example: array.length
is to get the length of the array.
length() is a method. Generally, string class objects have this method, which also obtains the length of the string. [Recommended learning: java course]
For example: String.length();
Method 3: Only available in Java SE 6.0 Method, the efficiency is almost the same as 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 and simple method, and the efficiency is also very high, compared with The efficiency of methods two and three is almost the same:
if (s == null || s == "")
Note: s == null is necessary.
If the String type is null, perform equals( String) or length() operations will throw java.lang.NullPointerException
.
And the order of s==null must appear first, otherwise java.lang.NullPointerException
will also be thrown.
The difference between Java empty string and null:
1. Type
null represents the value of an object, not a character string. For example, when declaring a reference to an object, String a = null;
"" represents an empty string, which means its length is 0. For example, declare a string String str = "" ;
2. Memory allocation
String str = null;
means declaring a string object The reference, but the pointer is null, which means that it does not point to any memory space;
String str = "";
means declaring a reference of string type, its value is " "Empty string, this str reference points to the memory space of the empty string;
In Java, variables and reference variables are stored in the stack (stack), and objects (generated by new) are stored in In the heap:
is as follows:
String str = new String("abc") ;
ps: = The one on the left is stored in the stack (stack), = The one on the right is stored in the heap (heap).
The above is the detailed content of How to determine whether a Java string is empty?. For more information, please follow other related articles on the PHP Chinese website!