Because the +
occurs shortly after a string, the " "
, then the object there is of the type string. Operators are overloaded (in Java this is kind of a gambiarra, but still it is), so in each type of data, the operator can run something different. You cannot set your own overloads, but the so-called Java primitives already have one ready. The +
when he finds a string
is a concatenation operation, so it gathers all the texts and does no sums.
To join, in this case, Java resolved that it would be weak typing and do an automatic coercion to string
because the initial expression was string
. So " " + 7
gives " 7"
, there " 7" + 2
gives " 72"
and finally " 72" + " "
gives " 72 "
.
So that’s it, overload plus partial weak typing have made Java give this result that looks weird, but makes some sense, even if it’s a questionable rule.