112

I want to get string values of my fields (they can be type of long string or any object),

if a field is null then it should return empty string, I did this with guava;

nullToEmpty(String.valueOf(gearBox))
nullToEmpty(String.valueOf(id))
...

But this returns null if gearbox is null! Not empty string because valueOf methdod returns string "null" which leads to errors.

Any Ideas?

EDIt: there are 100s fields I look for something easy to implement

Nutella
  • 83
  • 8
Spring
  • 11,333
  • 29
  • 116
  • 185

9 Answers9

247

You can use Objects.toString() (standard in Java 7):

Objects.toString(gearBox, "")

Objects.toString(id, "")

From the linked documentation:

public static String toString(Object o, String nullDefault)

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

Parameters:
o - an object
nullDefault - string to return if the first argument is null

Returns:
the result of calling toString on the first argument if it is not null and the second argument otherwise.

See Also:
toString(Object)

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • @Spring You should consider upgrading, especially with Java 8 coming out soon. In any case, I'll leave this answer in case it can be helpful for future visitors. – arshajii Feb 21 '14 at 14:09
  • 4
    Downvoter: please leave a comment. I would like to know what is wrong with my answer, and a downvote alone doesn't tell me. – arshajii Feb 21 '14 at 14:21
  • 1
    NIce. I suggest `Objects.toString(id, "").trim()` – Wender Oct 21 '17 at 18:26
  • why it requires > API 19... its a simple check. i guess i have to write that my self – M.kazem Akhgary Nov 01 '18 at 09:58
  • 2
    The risk is that u r losing the type of your string. It is currently a String but if it will change to a different type in the future he compiler won't protect u – ozma Jul 29 '19 at 06:32
68

For java 8 you can use Optional approach:

Optional.ofNullable(gearBox).orElse("");
Optional.ofNullable(id).orElse("");
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • 2
    if id is not a string, it seems that the second line code cannot work – jack jin Nov 18 '19 at 07:23
  • 2
    This does two method calls and allocates a new object and immediately discards it. This is not an improvement over the simple `gearBox == null ? "" : gearBox`. A single method call like `StringUtils.defaultString` is more JIT friendly. – Vroo Jul 21 '20 at 01:56
  • @Vroo if you don't want the discard then the `orElseGet` can be use instead – Federico Piazza Jul 21 '20 at 02:11
  • 1
    @FedericoPiazza That's not an improvement. First, `orElseGet` takes a delegate so now I have ***three*** method calls. Second, an `Optional` object still gets created and then discarded. – Vroo Jul 22 '20 at 03:12
37

If you don't mind using Apache commons, they have a StringUtils.defaultString(String str) that does this.

Returns either the passed in String, or if the String is null, an empty String ("").

If you also want to get rid of "null", you can do:

StringUtils.defaultString(str).replaceAll("^null$", "")

or to ignore case:

StringUtils.defaultString(str).replaceAll("^(?i)null$", "")
Keppil
  • 45,603
  • 8
  • 97
  • 119
  • what if string is string "null"? thats my problem – Spring Feb 21 '14 at 14:04
  • @Spring: Updated to take care of that case too. – Keppil Feb 21 '14 at 14:11
  • `StringUtils.defaultString` already checks for null. So the `replaceAll` is only changes the string is when it's a literal `"null"`, which is not what was asked for. Here's the source: `public static String defaultString(String str) { return str == null ? "" : str; }` – Vroo Jul 21 '20 at 02:00
  • I believe the first comment concerned the literal string `"null"` – Keppil Aug 04 '20 at 08:56
23

If alternative way, Guava provides Strings.nullToEmpty(String).

Source code

String str = null;
str = Strings.nullToEmpty(str);
System.out.println("String length : " + str.length());

Result

0
coder
  • 8,346
  • 16
  • 39
  • 53
Won-Sik Kim
  • 411
  • 3
  • 6
10

Use an inline null check

gearBox == null ? "" : String.valueOf(gearBox);
Samhain
  • 1,767
  • 1
  • 12
  • 20
10

StringUtils.defaultString(String str) Returns either the passed in String, or if the String is null, an empty String ("").

Example from java doc

StringUtils.defaultString(null) will return "" StringUtils.defaultString("") will return "" StringUtils.defaultString("bat") will return "bat"

Akshay Sardhara
  • 129
  • 2
  • 7
6

Since you're using guava:

Objects.firstNonNull(gearBox, "").toString();
renke
  • 1,180
  • 2
  • 12
  • 27
3

In Java 9+ use : Objects.requireNonNullElse (obj, defaultObj) https://docs.oracle.com/javase/9/docs/api/java/util/Objects.html#requireNonNullElse-T-T-

//-- returns empty string if obj is null
Objects.requireNonNullElse (obj, "")   
Ari Singh
  • 1,228
  • 7
  • 12
0

This should do the trick: "" + gearBox

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 24 '23 at 09:25