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;
}
}
The NullPointerException can be avoided using checks and preventive techniques like the following: Making sure an object is initialized properly by adding a null check before referencing its methods or properties. Using Apache Commons StringUtils for String operations e.g. using StringUtils.
In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.
The getMessage() method of Throwable class is used to return a detailed message of the Throwable object which can also be null. One can use this method to get the detail message of exception as a string value.
Several alternatives for returning null values include using null object reference types, a null object pattern, and a result type as the return type. Therefore, the recommendation is to return an empty value instead of a null to keep the code clean and error-free.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With