Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringification of null in Java [duplicate]

Tags:

java

Consider

public String toString()
{
    return foo + bar;
}

where foo and bar are both fields of the class.

If foo and bar are either or both null, does the JLS guarantee that the string (null) is returned for each field, or does it reserve the right to throw an NPE?

like image 977
P45 Imminent Avatar asked Aug 06 '26 21:08

P45 Imminent


1 Answers

http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.11:

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

So yes, it will not throw a NPE (as long as the + resolves to a string concatentation, rather than an arithmetic operation)

EDIT:

Actually, looking at this carefully, the behaviour isn't technically defined.

String conversion only applies to an argument to + that is not a string. If both arguments are a string, then no conversion is done (so 5.1.11 does not apply).

We then move onto http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1, which only specifies the following:

...The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

Note there's no reference to nulls.

So I don't think the behaviour of (String)null + (String)null is technically defined...

like image 50
thecoop Avatar answered Aug 08 '26 10:08

thecoop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!