1

I have been wondering recently about usage of empty string vs null.

I know what these values mean, but I wonder when I should use each? It is not about exact programming language or approach.

2
  • 1
    every programming language is different and has a different (similar sometimes) behaviour Commented Sep 11, 2018 at 7:24
  • but shortly: string initialized with null means that there's no string at all, empty string means there's a string but it's empty, if someone else is using your API then you might decide to not accept null or empty so you have to check for both. Commented Sep 11, 2018 at 7:25

2 Answers 2

2

As a general guideline, I avoid using null no matter what.

null is not an object, it can't do anything and you can't expect anything from it. It will evenatually leak as a rather obscure NullPointerException. You can't access any field or any method in null and trying to do so, will lead you to the aforementioned excpetion.

You can avoid using it with:

  • Null Object pattern
  • Raising Exception with a more useful than message than an empty NullPointerException
  • Designing your classes to have its fields private final therefore avoiding nulls by design
Sign up to request clarification or add additional context in comments.

Comments

1

Moste of the time you want to prevent both. The difference is that a null value is returned most of the time when you try to use a variable which doesn't exist or has not been instantiated by you or the programm. The empty string is most of the time a human approach of emptying a variable which already exists.

Comments

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.