Because +
occurs soon after a string , " "
, then the object there is of type string . Operators are overloaded (in Java this is half a gambiarra, but still it is), so in each type of data, the operator can execute a different thing. You can not define your own overloads, but the so-called primitive types in Java already have one ready. The +
when it finds a string
is a concatenation operation, so it joins all the texts and does not make sums.
In this case Java decided that it would be poor typing and auto-coercion for string
because the initial expression was string
. Then " " + 7
gives " 7"
, then " 7" + 2
gives " 72"
and finally " 72" + " "
gives " 72 "
.
So it's this, overloading partial weak typing have made Java give this result that looks weird, but it does make some sense, even though it's a questionable rule.