Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NPE when trying to return null

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;
    }
}
like image 780
Felix Avatar asked Jan 17 '17 11:01

Felix


People also ask

How do I fix NullPointerException?

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.

Why does my method return null?

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.

Can exception getMessage be null?

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.

What should I return instead of null?

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.


1 Answers

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;
    }
}
like image 136
T.J. Crowder Avatar answered Oct 20 '22 21:10

T.J. Crowder