5

Today I found a bug in legacy code, which led me to a shocking discovery:

String s = null + ""; //results in "null" string
s = String.valueOf(null); // NullPointerException is thrown
Integer i = null;
s = String.valueOf(i); //results in "null" string

First question is: Why such an unexpected behavior happens?
It mean that a convenient code like this:

String age = person.getAge() + "";

is being totally unexpected.
Second question: What is the best (most elegant) way to get a null instead of "null"

Constant
  • 377
  • 4
  • 10

1 Answers1

3

String.valueOf(null) calls public static String valueOf(char data[]) due to method overloading resolution rules (char[] is more specific than Object). That method throws NullPointException for a null argument.

String.valueOf(i) calls public static String valueOf(Object obj), which returns the String "null" for a null argument.

To avoid this exception, either don't call s = String.valueOf(null); (you can always assign s = "null"; directly, or cast the null value to some type other than char[] (for example s = String.valueOf((String)null);).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    The exception bothers me less than an incorrect value being passed around in case you expect null, but instead get "null" string. – Constant Dec 05 '17 at 08:24
  • @Constant In that case, make sure you never concatenate a `null` to a `String` and never pass `null` to `String.valueOf()`. – Eran Dec 05 '17 at 08:26