三元运算符和意外的NullPointerException

Vaa*_*ndu 6 java ternary-operator

NullPointerException有时会从下面的线上得到.

System.out.println("Date::"+ row != null ? row.getLegMaturityDate() : "null");
Run Code Online (Sandbox Code Playgroud)

添加括号后,它很好.

System.out.println("Date::"+ (row != null ? row.getLegMaturityDate() : "null"));
Run Code Online (Sandbox Code Playgroud)

请澄清我的行为.提前致谢.

Chr*_*röm 13

"Date::" + row永远不会是空的,尽管row有时是.

也就是说,"Date::"+ row != null相当于("Date::"+ row) != null总是如此.