The “+” operator has a very special meaning in Java. It can only ever mean one of two things: addition of numbers, or concatenation of Strings.
[A number] + [another number] follows these rules:
·
A byte + a byte, short, char, or int = an int
·
A byte + a double, long, or float = the non-byte
type
·
A char + a char or int = an int
·
A char + a long, float, or double = the non-char
type
·
A double + a double = a double
·
A float + a float = a float
·
A float + a double = a double
·
An int + an int = an int
·
An int + a double, float, or long = the non-int
type
·
A long + a long = a long
·
A long + a float or double = the non-long type
·
A short + a byte, short, or char = an int
·
A short + a long, float, or double = the
non-short type
Let’s suppose we have an int with value 73, and another with
value 1234. Then if we “+” them, the result will be the totally expected 1307.
The other numeric types work similarly. Just be mindful of the promotion rules
for certain results.
Strings are a little bit more complex. Let’s start with a
straightforward case: a String “+” a String.
Suppose one String has the value “Hello,” (note the comma is inside the String)
and the other has the value “World!” and we assign
String result = s1+ s2;
Then the variable result will contain “Hello, World”—that is, every character
in the first String, including leading or trailing spaces, immediately followed
by every character in the second String, including leading or trailing spaces.
Now if we mix in numbers, things get more complex, because concatenation and
numerical addition happen left to right:
Using “+” with “Hello” and “2” and 345 in the following order:
“Hello” + 2 + “345”
may produce some behavior that at first glance is unexpected.
This will, in fact, produce “Hello2345”—not, as some of you may (reasonably)
expect, “Hello347”.
The concatenator operator sees the first operand is “Hello”
and the second is a number, so it converts the number to a String, and we get “Hello2”.
Then, it sees the String “345” and appends it to “Hello2” to get the final result
of “Hello2345”.
Now, if the things to be concatenated were in another order,
with slightly different types, the result would be much more in line with what you
first expected:
2 + 345 + “Hello” indeed produces “347Hello” because the addition of numbers 2 +
345 is done first, then that number is converted to a String as “347” and then
it is appended to “Hello”
Any behavior other than straightforward addition of numbers, or
concatenation of strings, is not allowed with +, and, for example, trying to
somehow combine a Puppy and a Kitten with + (now, calling Puppy’s toString()
method and concatenating that with Kitten’s toString() is a different story)
will cause a compilation error. No other behavior for + can ever be defined by
the user.