What do you thínk about Java designers decided java.lang.String.valueOf((Object)null) returns "null" but not ""

106 Views Asked by At

[edited this question at 2020/07/27 01:30 UTC]

What do you thínk about Java designers decided java.lang.String.valueOf((Object)null) returns "null" but not "" which is the length 0 text ?

I think that "" text is better than "null" text instead of null text.

I have already understood that null and "" are different, but sometimes "" and null means empty value on programs.

Actually, org.apache.commons.lang3.StringUtils.isEmpty() that returns true if value is "" or null. If String.valueOf(null) returns "", String.valueOf(null).isEmpty() returns true.

To avoid NullPointerException, we sometime use [] array instead of null array. new String((char)[]) returns "".

I think that a meaning of "zero" is "nothing", so length of null should be 0.

2

There are 2 best solutions below

2
user13784117 On

It's consistent with calling Object.toString(null).

Why should that specific result matter? I'd argue that when converting an object to a String, it's more generally useful to get "null" rather than an empty string.

For example, if you call

System.out.printf("the value is %s", obj);

where obj is null, then it seems more useful in general to see

the value is null

rather than

the value is

If you want something different, you can code valueOf(obj != null ? obj : ""). Of course, the same argument could have been made for the reverse decision - that you could have been made to write valueOf(obj != null ? obj : "null"). It thus boils down to judgement of which is the more common need.

0
Tashkhisi On

"null" is completely different from "". null means that you never set the value of a variable while when you have a variable with "" value it means you have once set that variable to something, even if that value is "".

some tips:

Tony Hoare introduced null reference while designing ALGOL and many languages after that have followed that approach but Hoare called it "my billion dollar mistake", many languages don't use that any more because of its pitfalls. Java 8 has introduced Optional type. to tackle these problems use that instead.