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

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

    0 讨论(0)
  • 2020-12-21 08:11

    the exception is cause when sb.toString() gets executed.

    In the fix you check if sb is null before executing so the offending call is not attempted.

    0 讨论(0)
  • 2020-12-21 08:17

    I think the issue is that the statement is being parsed like this:

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

    The string concatenation operator (+) has a heigher precedence than the ternary operator.

    Since "Value"+null is always not null, sb.toString() will always be called, even if sb is null, hence the NullPointerException.

    If in doubt - parenthesize! Even if not in doubt! :)

    0 讨论(0)
  • 2020-12-21 08:17

    The ternary operation bypasses the toString method on the null object, which is what is causing the NullPointerException.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-21 08:28

    A + has a higher precedence than a !=.

    So you evalutate "(Value="+sb ) != null at first.

    0 讨论(0)
提交回复
热议问题