Case of excluding random pointers: a ternary conditional operator that does not work with string concatenation

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 problem includes the ternary operator in brackets:

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

How is this possible?

+3
source share
6 answers

A +has a higher precedence than a !=.

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

+8
source

Copy the expression like a compiler efficiently in a broken vase:

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

Now it "Value" + sbwill never be empty, even if sbit is null ... so when sbit is null, it calls toString()and goes into action.

+5

, , :

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

(+) , .

"Value" + null , sb.toString() , sb , , NullPointerException.

- ! !:)

+4

toString , NullPointerException.

+2

, sb.toString().

, sb null , .

+1

System.out.print() :

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

With sb = null, sb.toString()means null.toString()leading to you a NullPointerException

0
source

Source: https://habr.com/ru/post/1755278/


All Articles