I know that the following:
String s = null;
System.out.println("s: " + s);
will output: s: null
.
How do I make it output just s:
?
In my case this is important as I have to concatenate String
from 4 values, s1, s2, s3, s4
, where each of these values may or may not have null
value.
I am asking this question as I don't want to check for every combinations of s1 to s4 (that is, check if these variables are null
) or replace "null"
with empty
String
at the end, as I think there may be some better ways to do it.
null
, even if you use+=
onnull
itself. E.g.:String s = null; s += null;
. After those two statements,s
becomes the distinctly non-null
string"nullnull"
. It's also safe to concatenate an object which is notnull
, but whosetoString()
method is overridden to returnnull
. In all cases, the concatenation substitutes"null"
fornull
. – Misapprehend""
and will print as nothing. A null reference is not even a String. – Hazeltonnull
. – Hazelton