You can think of the operator +
as a function that takes two arguments, say a
and b
.
Let's replace, for clarity, the +
operator with the keyword add
. Then, our function signature looks like add(a, b)
.
If you let a
and b
be two integers, say a = 1
and b = 2
, then you probably expect add(a, b)
to perform the arithmetic operation of addition and output number 3
.
Perhaps, the confusing part is when a
and b
are not integers, or more generally of numeric type. It turns out that our add
function has what's called an overload. What this means is that our function does different things based on the type of input you provide to it. When a
and b
are integers, add(a, b)
adds a
and b
up. In your example, it happens that the function arguments are of type string. So, instead of performing addition, the function performs concatenation (e.g., putting two things together, just like putting together words forms sentences).
Now, back to the +
operator. This is just syntactic sugar. Same may argue that it feels more natural to write a + b
than add(a, b)
. It definitely is shorter.
In your example, the operator +
is used two times.
"The value of z is " + z + "."
Let's break it down:
// A string.
"The value of z is "
// A number.
z
// A string.
"."
By doing "The value of z is " + z
the operator is trying to do some work on a string and a number. The default behavior in this case is to type cast z
as a string and then perform concatenation. Thus, at the end of this operation the output becomes the string "The value of z is 11
". Next, you are using again the +
operator, but this times on two strings, namely "The value of z is 11"
and "."
. So, the default in this case is to just concatenate those two strings. Therefore, your output becomes "The value of z is 11."