Strange Null pointer exception case: ternary conditional operator not working with string concatenation

后端 未结 6 1391
你的背包
你的背包 2020-12-21 07:54
StringBuffer sb=null;

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

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

// Throws Nu         


        
6条回答
  •  醉酒成梦
    2020-12-21 08:26

    Let's bracket the expression the way that the compiler effectively would, in the broken vase:

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

    Now "Value" + sb will never be null even if sb is null... so when sb is null, it's calling toString() and going bang.

提交回复
热议问题