Any difference between String = null and String.isEmpty?

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


isEmpty() checks for empty string "",

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


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                |
+-------+-----------+----------------------+

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

Tags:

Java

String

Null