Reputation: 131
This program supposed to avoid null when calling toFloat with null. but I'm still getting NPE .. any help
System.out.println(toFloat(null, null));
private static Float toFloat(Float def, String str) {
try {
return str != null ? Float.parseFloat(str) : def;
} catch (NumberFormatException e) {
return def;
}
}
Upvotes: 10
Views: 234
Reputation: 1074238
It's very subtle. Float.parseFloat
returns float
, not Float
. The second two operands of a conditional operator must be of the same type, but you're giving it float
(the result of Float.parseFloat
) and Float
(def
). The compiler picks float
because Float
can be coerced to float
through auto-unboxing.
So what the compiler outputs is as though you'd written this:
private static Float toFloat(Float def, String str) {
try {
return str != null ? Float.parseFloat(str) : def.floatValue();
// Note ----------------------------------------^^^^^^^^^^^^^
} catch (NumberFormatException e) {
return def;
}
}
...and of course, calling floatValue
on null
throws an NPE.
You can fix it by making sure the second operand's type is Float
, not float
. Lots of ways to do that, but as Zefick points out, the simplest is Float.valueOf(String)
:
private static Float toFloat(Float def, String str) {
try {
return str != null ? Float.valueOf(str) : def;
} catch (NumberFormatException e) {
return def;
}
}
Upvotes: 14