Is there any difference when using a if-statement to check if the string is empty by using String = null or String.isEmpty() ?
ie:
public String name;
if(name == null)
{
//do something
}
or
public String name;
if(name.isEmpty())
{
//do something
}
if there is any different (including performance issues) please let me know.
isEmpty(<string>) Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.
The concept of NULL and empty string often creates confusion since many people think NULL is the same as a MySQL empty string. However, this is not the case. An empty string is a string instance of zero length. However, a NULL has no value at all.
The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.
The empty string is a string with zero length. The null value is not having a string at all.
s == null
will return false
if s is an empty string.NullPointerException
if the string is null.Here's a table showing the differences:
+-------+-----------+----------------------+
| s | s == null | s.isEmpty() |
+-------+-----------+----------------------+
| null | true | NullPointerException |
| "" | false | true |
| "foo" | false | false |
+-------+-----------+----------------------+
The variable name
isn't a String. It's a reference to a String.
Hence the null check determines if name
actually references a String
. If it does, then (and only then) can you perform a further check to see if it's empty. i.e.
String name = null; // no string
String name = ""; // an 'empty' string
are two different cases. Note that if you don't check for nullness first, then you'll try and call a method on a null reference and that's when you get the dreaded NullPointerException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With