3

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?

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78

2 Answers2

10

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...

thecoop
  • 45,220
  • 19
  • 132
  • 189
  • Hum. That's even more interesting following your edit. I guess the pragmatic thing to do is to prefix the expression with `""`. – P45 Imminent Feb 11 '16 at 13:01
  • 1
    `null` is of the null type, not of the String type - so string conversion is applied... – assylias Feb 11 '16 at 13:17
  • @P45Imminent it's a safe bet that it will work as you expect, it's merely a hole in the spec. Any half-decent java compiler will deal with this correctly. – thecoop Feb 11 '16 at 13:40
-2

It does not throw any error. It tries to convert both the arguments to string if they are not already strings. String representation of null is "null" Hence, here is the output:

foo ------- bar ------ foo+bar

null ------ null ------"nullnull"

null ------"str" ------"nullstr"

"str" -----null -------"strnull"

Sravya
  • 35
  • 1
  • 2
  • Can someone let me know why my answer is being downvoted? I tried a sample and those are the outputs it gives exactly. Where am I going wrong? – Sravya Feb 11 '16 at 15:14
  • The fact that you observe this behaviour doesn't at all address any guarantees the JLS might give. – P45 Imminent Feb 11 '16 at 15:39
  • Oh. Thanks. The fact that null is converted to "null" is from JLS only. Anyways thanks. I will try to be specific. – Sravya Feb 11 '16 at 16:51