I set a string with a method that can either return any string or null.
I want the string to be "" whenever it’s null. So i use:
String mString = getMyString();
mString = mString==null ? "" : mString;
Or (less eficciently, but in one line):
String mString = getMyString() == null ? "" : getMyString();
Any cleaner way to do this?
EDIT: I’ve considered using an if statement:
String mString = getMyString();
if (mString == null); mString = "";
Which one (the 1st or 3rd) would perform faster?
Many errors result in
nulls propagating. It’s much better to use an empty string if you mean an empty string. Same for collections. So throw an NPE at the earliest available opportunity. Java SE 7 introduces (a verbose, incorrectly capitalised, poorly located) method for doing this.