Search code examples
javanullpointerexceptionternary-operatorbigdecimal

Ternary operator for Bigdecimal null validation


Why am I getting null pointer exception in this code?

    BigDecimal test = null;
    String data = "";
    try {
    System.out.println(test==null?"":test.toString());
    data = test==null?"":test.toString();
    System.out.println(data);
    data = data +  " " + test==null?"":test.toString(); // catching null pointer in this line
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

Solution

  • It's evaluating the expressions as:

    data = (data +  " " + test==null)?"":test.toString();
    

    so, since data + " " + test is not null, it attempts to call test.toString() even when test is null.

    Change

    data = data +  " " + test==null?"":test.toString();
    

    to

    data = data +  " " + (test==null?"":test.toString());