12

I'm getting the null values from DB, but I need to display the empty string "" instead.


For example, I have to append four values to display in the single cell of a Excel sheet like below:

sheet.addCell(new Label(4, currentRow, a.getPar()+" "+a.getO()+" "+a.getPar()));


How to achieve the expected result (the replacement) in Java?

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
user2408111
  • 225
  • 1
  • 2
  • 5
  • Please post some of your code... – vikingsteve May 28 '13 at 13:28
  • can you elaborate your problem? and some code snippet on what you talking about? – rahul maindargi May 28 '13 at 13:29
  • Can you clarify? If you're trying to print a null value and you want it to be displayed as an empty space, then check if the string is null, and if it is, display an empty space. – SubSevn May 28 '13 at 13:29
  • 3
    you could use Apache commons `StringUtils` for this: http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#defaultString%28java.lang.String%29 – Marco Forberg May 28 '13 at 14:15
  • 2
    Try [com.google.common.base.Strings.nullToEmpty()](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html#nullToEmpty(java.lang.String)) – Ilya Serbis Jun 04 '15 at 09:23
  • 5
    how is this not a question? If you want to avoid null checking and have to deal with legacy APIs doing something like `Strings.nullToEmpty(s)` makes things clearer and better rather than cluttering the code with ternaries. – Alexander Oh May 27 '16 at 13:53
  • 1
    All good answers are here: https://stackoverflow.com/questions/21936503/get-empty-string-when-null – Vadzim Nov 15 '17 at 09:28

2 Answers2

32

If I understand correctly, you can use the ternary opperator:

System.out.println("My string is: " + ((string == null) ? "" : string));

In case you are not familiar with it, it reads "Is string null? If it is, then 'return' en empty string, else 'return' string". I say 'return' because you can consider ((string == null) ? "" : string) as a function that returns a String.

You can replace the empty string with any other String of course.

Djon
  • 2,230
  • 14
  • 19
15

If I understand correctly, you need this

public static String replaceNull(String input) {
  return input == null ? "" : input;
}

and the use it where ever you need it like

sheet.addCell(new Label(4,currentRow, replaceNull(a.getParan())+" "+replaceNull(a.getO())+" "+replaceNull(a.getParan())));

Hope this helps

Axel Fontaine
  • 34,542
  • 16
  • 106
  • 137
rahul maindargi
  • 5,359
  • 2
  • 16
  • 23