-1

I have to convert Strings to Doubles, but may be I have a null value. Does it work with Double.parseDouble(stringValue) or Double.valueOf(stringValue)?

What is the difference between this two methods?

Thank you in advance.

Naman
  • 21,685
  • 24
  • 196
  • 332
  • Both will throw an exception if your string is null. The difference is the return type, not how to handle bad input. – khelwood Jan 09 '19 at 12:37
  • You're asking two different questions here. One of them is a duplicate of [What is the difference between Double.parseDouble(String) and Double.valueOf(String)?](https://stackoverflow.com/questions/10577610/what-is-the-difference-between-double-parsedoublestring-and-double-valueofstr). Please restrict yourself to one question per question. – khelwood Jan 09 '19 at 12:41
  • Does it work with `Double.parseDouble(stringValue) or Double.valueOf(stringValue)`? No it will throw null pointer: difference only return type . – soorapadman Jan 09 '19 at 12:46
  • You can also upvote an answer if you like it ;) – Peter Lawrey Jan 10 '19 at 07:44

1 Answers1

2

Neither method makes any difference. Both will throw a NullPointerExecption. Instead, you need to add a helper method which returns a Double e.g.

static Double parseDouble(String s) {
    return s == null ? null : Double.parseDouble(s);
}

or you can return a double by having a default value

static double parseDouble(String s, double otherwise) {
    return s == null ? otherwise : Double.parseDouble(s);
}

a suitable value might be Double.NaN

static double parseDouble(String s) {
    return s == null ? Double.NaN : Double.parseDouble(s);
}
Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106