gpt4 book ai didi

java - 奇怪的空指针异常情况 : ternary conditional operator not working with string concatenation

转载 作者:搜寻专家 更新时间:2023-11-01 04:00:22 24 4
gpt4 key购买 nike

StringBuffer sb=null;

// Some more logic that conditionally assigns value to the StringBuffer

// Prints Value=null
System.out.println("Value="+sb);

// Throws NullPointerException
System.out.println("Value=" + sb != null ? sb.toString() : "Null");

此问题的解决方法是将三元运算符括在括号中:

// Works fine
System.out.println("Value=" + (sb != null ? sb.toString() : "Null"));

这怎么可能?

最佳答案

+ 有更高的 precedence而不是 !=

所以你首先计算 "(Value="+sb ) != null

关于java - 奇怪的空指针异常情况 : ternary conditional operator not working with string concatenation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3279743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com