Reputation: 398
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".
Upvotes: 0
Views: 8923
Reputation: 1338
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;
}
Upvotes: 0
Reputation: 39532
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
Upvotes: 2
Reputation: 427
this is something you can do for converting those values into string values.
decimal dValue = 59.24;
String sValue = dValue+"";
Upvotes: 0