null
is an "implicit" value assigned to a reference to indicate the absence of an object. It is not an operator.
When you perform concatenation of a string and another type, the other value is simply converted to its "String" representation using String.valueOf(object)
and appended to the first String.
For example:
"XYZ" + 1
=> "XYZ" + String.valueOf(1)
=> "XYZ" + "1"
=> "XYZ1"
Similarly,
"Jay" + null
=> "Jay" + String.valueOf(null)
=> "Jay" + "null"
=> "Jaynull"
See implementation of String::valueOf(Object)
method here. It is clearly evident that if the object is null
, a string "null"
should be returned.
Pro Tip: Try putting a break point on the return statement, you will see this code executing while running a java program with string + object concatenation.
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Hope this helps!