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.
One way to concatenate multiple strings or columns is to use the "+" operator. For the rows where MiddleName is NULL, the concatenation result will be NULL.
Using + Operator The + operator is one of the easiest ways to concatenate two strings in Java that is used by the vast majority of Java developers. We can also use it to concatenate the string with other data types such as an integer, long, etc.
Concatenating Data When There Are NULL ValuesTo resolve the NULL values in string concatenation, we can use the ISNULL() function. In the below query, the ISNULL() function checks an individual column and if it is NULL, it replaces it with a space.
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
The most concise solution this is:
System.out.println("s: " + (s == null ? "" : s));
or maybe create or use a static helper method to do the same; e.g.
System.out.println("s: " + denull(s));
However, this question has the "smell" of an application that is overusing / misusing null
. It is better to only use / return a null
if it has a specific meaning that is distinct (and needs to be distinct) from the meanings of non-null values.
For example:
null
, consider explicitly initializing them to ""
instead. null
to denote empty arrays or collections.null
when it would be better to throw an exception.Now obviously there are counter-examples to all of these, and sometimes you have to deal with a pre-existing API that gives you nulls ... for whatever reason. However, in my experience it is better to steer clear of using null
... most of the time.
So, in your case, the better approach may be:
String s = ""; /* instead of null */ System.out.println("s: " + s);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With