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

后端 未结 6 1386
你的背包
你的背包 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:04

    System.out.print() is implemented like that:

    public void print(String s) {
            if (s == null) {
                s = "null";
            }
            write(s);
    }
    

    With sb = null, sb.toString() means null.toString() which leads to you NullPointerException

提交回复
热议问题