0

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 3

2

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

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, I did just this. It just seemed a bit too long to write at first, but ok
@TiberiuDorianMoşescu You're welcome. If it's annoying to keep writing it, simply make your own util class and use StringUtils.valueOfNull(foo).
0

this is something you can do for converting those values into string values.

decimal dValue = 59.24;
String sValue = dValue+"";

Comments

0

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

casting will throw a classCastException or sth similar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.