0

From Apex document: Expression Operators:

If x is a String and y is a String or any other type of non-null argument, concatenates y to the end of x.

But running the following code in the developer console, it works and output nullnull.

String a;
Integer b;
System.debug(a + b); // output nullnull

Why does Salesforce add any other type of non-null argument in the document?

1
  • Have you tried executing this code snippet in other api versions? For operators on non-string types (like, say, Integer), this would produce something like Argument cannot be null.
    – Derek F
    Jan 21, 2020 at 12:56

1 Answer 1

1

This behavior is a species of type coercion.

In Apex, as in many other languages, when you apply an operator to operands of mixed type, the value of one of the operands is coerced to the type of the first to make the operation meaningful. For example,

Date myDate = Date.today();
String hello = 'Hello on ';

System.debug(hello + myDate);

will print out a message with today's date (n.b. in a date locale format that is often not very useful!) because the Date value is coerced to a String.

This behavior applies to a variety of types to make concatenating them with strings (+) meaningful, and it means you don't have to explicitly call String.valueOf() when you do so.

So I think that's part of what's going on in your question. When we do

String a;
Integer b;
System.debug(a + b); // output nullnull

b is being coerced to a string without regard to its (null) value, yielding 'null'.

That's what the docs mean when they say

If x is a String and y is a String or any other type of non-null argument, concatenates y to the end of x.

The second clause is stating that type coercion will be performed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .