1

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Twinone
  • 2,949
  • 4
  • 28
  • 39
  • 3
    Move it into the method and never return `null`. – Brian Roach Feb 21 '13 at 22:30
  • It's a closed-source method, i do not have acces to it. – Twinone Feb 21 '13 at 22:32
  • Then ... write your method that calls that method :) What you're doing is fine, and there's literally any number of ways to go about it ... but they all do the same thing. – Brian Roach Feb 21 '13 at 22:33
  • 1
    It's a could idea to use standard layout on those `if` statements... – Tom Hawtin - tackline Feb 21 '13 at 22:35
  • If that's a behavior you want to replicate, and should depend on the string rather than the method, you could consider creating a wrapper class for String that offers the same functionalities, but automatically treats null as "". – 0x5C91 Feb 21 '13 at 22:36
  • 1
    Because of the semicolon after your `if` statement, your String will now **always** be `""`, even if it was not `null` before. – jlordo Feb 21 '13 at 22:43

7 Answers7

3

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.

String mString = java.util.Objects.requireNonNull(getMyString());
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • 1
    what do you mean by _incorrectly capitalised_? I don't think the method is helpful in this case, as it will throw a NPE instead of _fixing_ the value. – jlordo Feb 21 '13 at 22:36
  • Generally hyphenated words only have the leading path capitalised (if appropriate). Just as well as there is a tendency to remove hyphens - don't want to under up uncoOrdinated. / The value is almost certainly broken. Fixing hides the problem, which is an incredibly bad idea. – Tom Hawtin - tackline Feb 21 '13 at 22:50
  • I agree that it's a bad idea to hide the problem (in most cases). As far as the method name goes, it perfectly fits the Java naming conventions, imho. Class names start with a capital letter, and methods with a lower-case letter and then use camel case. – jlordo Feb 21 '13 at 22:55
  • this solution is only applicable if the user us using Java 7 – user1428716 Feb 21 '13 at 23:56
  • 1
    @user1428716 There will be no further public supported updates of Java SE 6, so 7 is a jolly good idea. It's only the specific method which requires Java SE 7 - writing equivalent code is not too difficult. – Tom Hawtin - tackline Feb 22 '13 at 00:02
1

No, not really :)

Or you could create another method called getMyNonNullString which does it for you - good luck!

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
1

Like what Brian Roach commented:

If you have control over getMyString() implement it in a way that it returns an empty string instead of null. Otherwise I also use your first approach (trying to optimize it for branch prediction) :

String mString = getMyString();
// if I know getMyString() might return null and I can't change it:
mString = mString != null ?  mString : "";
jlordo
  • 37,490
  • 6
  • 58
  • 83
1

I would recommend using Apache Common's:

StringUtil.isBlank(strVariable);

Its a nice way to standardize projects, especially large ones. Otherwise you have to repeat your home cooked logic everywhere.

The following is a link for your reference: http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html

James Oravec
  • 19,579
  • 27
  • 94
  • 160
1

The second is definitely not the way to go since it is not the same.

Don't do any of these though. Write a convenience function like the below once and statically import it so that the intent is clear.

public static @Nonnull String nullToEmptyString(@Nullable String s) {
  return s != null ? s : "";
}
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

I'd do the 3rd form. Performance wise there shouldn't be any noticeable difference.

irreputable
  • 44,725
  • 9
  • 65
  • 93
-1

May I suggest a different approach. I don't have JAVA 7 due to MACOSX restriction yet so if there is syntax error , please guide me through. Comments Welcome

This is based on the question I had asked on Stacoverflow error : Why is the switch statement faster than if else for String in Java 7?

 The Java compiler generates generally more efficient bytecode from switch statements that   
 use "String objects" than from chained if-then-else statements.

So , --> Switch Statement would be more efficient than if-else block. The performance with try-catch is debatable

   String str = getMyString(); // only one call

   try {
    switch (str) {
      default:   break;
    }

    } catch(NullpointerException e){

      str="";//Null means Str is null
    }
Community
  • 1
  • 1
user1428716
  • 2,078
  • 2
  • 18
  • 37
  • down voter care to explain ? – user1428716 Feb 22 '13 at 16:05
  • Just guessing at potential reasons here: (a) using exceptions as control flow in this way is definitely not cleaner code (and are likely [much slower](http://stackoverflow.com/a/567593/836214); (b) a switch statement with strings is unlikely to be more efficient if there is only a single case. – Krease Feb 22 '13 at 17:28