views:

97

answers:

6
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");

The fix for this issue is encompassing the ternary operator in brackets:

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

How is this possible?

+2  A: 

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

BobTurbo
If it bypasses, then it should not cause a NullPointerException, right? Sorry if I got you wrong.
SidCool
Yes, it never calls the method toString on the null object. If you call a method on a null object (sb), it causes a NullPointerException.
BobTurbo
I feel dumb after this. This was so logical. Thanks!
SidCool
+1  A: 

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.

objects
+6  A: 

A + has a higher precedence than a !=.

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

tanascius
I feel dumb after this.
SidCool
+4  A: 

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.

Jon Skeet
+2  A: 

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! :)

andrewmu
+1  A: 

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

stacker