16

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.

3
  • 4
    An empty string is not null but isEmpty() Commented Dec 3, 2012 at 18:01
  • They are not interchangeable as they don't do anything like each other so there is no point comparing their performance. BTW: Why would you have a special method if it did the same thing as an operator? Commented Dec 3, 2012 at 18:44
  • in the second you will get NullPointerException Commented Jan 15, 2019 at 11:05

8 Answers 8

51

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                |
+-------+-----------+----------------------+
Sign up to request clarification or add additional context in comments.

3 Comments

I love that table from @mark-byers and will add that as a .NET guy I miss stringvalue.IsNullOrEmpty() returning a boolean. So I added this to a helper class: public static Boolean IsNullOrEmpty(String value){ return (value == null || (value != null && value.isEmpty())); } and now in app code I don't need to worry about the construct anymore: if(Helper.IsNullOrEmpty(mystring)) { // do something }
@TonyG you don't need the value != null because java ifs are lazy: if it gets to that point, it's already not null and you're safe to run .isEmpty() on the value.
awesome explanation..! :)
3

Strings that have assigned with "", don't contain any value but are empty (length=0), Strings that are not instantiated are null.

Comments

2

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

Comments

1

isEmpty() checks for empty string "",

it will throw NullPointerException if you invoke isEmpty() on null instance

Comments

0

Look at source code of your java version.

For example, in openjdk-7: http://www.docjar.com/html/api/java/lang/String.java.html

  119       /** The count is the number of characters in the String. */
  120       private final int count;

  663       /**
  664        * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
  665        *
  666        * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
  667        * <tt>false</tt>
  668        *
  669        * @since 1.6
  670        */
  671       public boolean isEmpty() {
  672           return count == 0;
  673       }

Comments

0

isEmpty checks for String "". Best practise is to check:

if (str != null && !str.isEmpty() {
   // process string
}

Comments

0

If you apply this code:

if(name.isEmpty())
{
    //do something
}

when name is null, you'll get NullPointerException.

null checking shows you whether there is an object generally.
isEmpty checking shows you whether the content of existing String object is empty.

Comments

0

I had this issue this week while modifying some old JaVa code and i learn here that i must always make all those check. The answer is indeed correct but i find it hard to remember each time so i decide to make a little function that do it for me in 1 simple call.

whit this, you always get the answer you want :

      public boolean StringIsNull(String pi_sChaine)
        {  boolean bTrueOrFalse = true;

           if (pi_sChaine == null || pi_sChaine.isEmpty())
             { bTrueOrFalse = true; }
           else
             { bTrueOrFalse = false; }

           return bTrueOrFalse;
        }

2 Comments

Welcome to StackOverflow! Please edit your answer to add an explanation to your code. This question is almost seven years old, and already has an accepted answer. Adding an explanation will bring your answer closer to the quality of the others', and make yours less likely to be removed.
Great! Please add your explanation directly in the question, not as a comment underneath it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.