Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get empty string when null

Tags:

java

guava

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

like image 582
Spring Avatar asked Feb 21 '14 13:02

Spring


People also ask

Is a null string an empty string?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

Does an empty string return null?

Empty string is a blank value,means the string does not have any thing. Show activity on this post. No method can be invoked on a object which is assigned a NULL value. It will give a nullPointerException .

Can we return empty string in Java?

isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false.

How do you handle empty and null string in Java?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.


2 Answers

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)

like image 175
arshajii Avatar answered Oct 10 '22 14:10

arshajii


For java 8 you can use Optional approach:

Optional.ofNullable(gearBox).orElse(""); Optional.ofNullable(id).orElse(""); 
like image 33
Federico Piazza Avatar answered Oct 10 '22 14:10

Federico Piazza