I would think everyone would be adverse to setting defaults because ""
is not the same as the null value.
That is exactly why I don't set defaults.
I guess now we are getting into philosophical issues but why would
toString return the string "null"?
Because the object itself is null. It can't print that. Actually, it can't
even run it. Null is exactly that -- NULL. It doesn't point to anything.
There is no object at all to reference. If this were anything but toString(),
calling a method on a null reference would result in a runtime exception.
You're lucky it prints "null".
Example:
Integer i;
int i = i.intValue(); // NullPointerException
I have my own methods for things that that, too, that return an empty string
if the object is null.
This is Java. It takes a lot of it's stuff from C. Go make some stuff in C
and find out how lucky you are that it does what it does and doesn't core
dump all over. *LOL*
It seems to me that it makes sense to
return "" if you're explicity calling toString on a null value.
To you, maybe, but there is a BIG difference between an empty string and a
null value. toString prints what it has. It doesn't make up the value. It
isn't going to print an empty string when it doesn't have an empty string. It
has a null object which is not even a String. It's nothing. Nada. It may have
been supposed to be a String, but for all the JVM knows, it might have been
supposed to be an Integer or ArrayList. All it sees is a call to toString
from a null reference.
If you don't like the default behavior, override toString in your objects and
make a utility function for Java data types, like I did.
Mine returns 0 for numeric types (i.e. Double or Integer) and "" for anything
else.
Java is very flexible. If you don't like something, override or change it.
--