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();
}
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());