What is the best way to convert an object I get from a database to String in Java? For example, I have a field which returns a BigDecimal. How do I convert it to String, while keeping it as null (primitive), if it comes back null? I was using String.valueOf(obj), but this actually transforms it to the String representation "null".
3 Answers
As you've noticed you get the string "null" instead of an actual null value. This is by design:
Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
That said, you could just check if it's null before converting it:
import java.math.BigDecimal;
class Main
{
public static void main (String[] args)
{
BigDecimal foo = new BigDecimal(1.0);
BigDecimal bar = null;
// if the value isn't NULL, use String.valueOf, else use NULL
String fooString = foo != null ? String.valueOf(foo) : null;
String barString = bar != null ? String.valueOf(bar) : null;
System.out.println(fooString == null ? "REALNULL" : "\"" + fooString + "\"");
System.out.println(barString == null ? "REALNULL" : "\"" + barString + "\"");
}
}
Output:
"1"
REALNULL
2 Comments
Tiberiu Dorian Moşescu
thanks, I did just this. It just seemed a bit too long to write at first, but ok
h2ooooooo
@TiberiuDorianMoşescu You're welcome. If it's annoying to keep writing it, simply make your own util class and use
StringUtils.valueOfNull(foo).I think casting the Object to a String or indeed using String.valueOf(obj) would work, but just do a check if the value isn't null, like:
if(obj == null) {
//Do something
}
else {
String s = (String) obj;
}
1 Comment
Tiberiu Dorian Moşescu
casting will throw a classCastException or sth similar