Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between String = null and String.isEmpty?

Tags:

java

string

null

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.

like image 251
Danny Avatar asked Dec 03 '12 18:12

Danny


People also ask

Does string isEmpty check for null?

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.

Is null better than empty string?

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.

What is string isEmpty?

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.


2 Answers

The empty string is a string with zero length. The null value is not having a string at all.

  • The expression s == null will return false if s is an empty string.
  • The second version will throw a 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                |
+-------+-----------+----------------------+
like image 112
Mark Byers Avatar answered Sep 29 '22 12:09

Mark Byers


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

like image 36
Brian Agnew Avatar answered Sep 29 '22 12:09

Brian Agnew