Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Nobody writes "" + null. They write "" + myVariableRef. And myVariableRef is null. As I posted earlier, the code is compiled to "" + String.valueOf(myVariableRef).

Since the empty String is a valid String, and Strinfg.valueOf() also returns a String, what other behavior would you ever imagine being sane or possible?



> Since the empty String is a valid String, and Strinfg.valueOf() also returns a String, what other behavior would you ever imagine being sane or possible?

IMHO, String.valueOf() throwing NPE upon encountering a null reference would be both sane and possible.

Unfortunately, it does indeed appear that it returns "null" instead [1].

[1] https://docs.oracle.com/javase/7/docs/api/java/lang/String.h...


On the other hand, it's quite convenient to not have to do null checks in debug messages. Compare:

log.trace("doStuff(" + obj1 + ", " + obj2 + ")");

to this:

log.trace("doStuff(" + (obj1 != null ? obj1 : "null") + ", " + (obj2 != null ? obj2 : "null") + ")");

The second one is IMHO quite hard to read, even in this short example (and code readability is important when you do code reviews)


That is why you should use string formatting instead of concatenation.

For string formatting, rendering "null" (or "") makes sense; for coercion not.


That just resolves into everyone always doing formatting, and never doing concatenation, which yields the same problem.


It should just throw NPE. I understand why people writing quick debug printlns could be infuriated by that, but the way it works now leads to much more subtle bugs.


An empty string of it HAS to be a string would make infinitely more sense. However a type error wouldn't toady on a strongly typed language




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: