Addition Operator (+)
Adds the value of one numeric expression to another or concatenates two strings.
The type of the expressions determines the behavior of the + operator.
Both expressions are char
Both expressions are numeric
Both expressions are strings
One expression is char and the other is numeric
One expression is char and the other is a string
One expression is numeric and the other is a string
For concatenation, numbers are coerced into a string representation of the numeric value, and chars are considered to be strings of length 1. For addition of a char and a number, the char is coerced into a numeric value, and the two numbers are added.
In scenarios where type annotation is not used, numeric data may be stored as a strings. Use explicit type conversion or type annotate variables to ensure that the addition operator does not treat numbers as strings, or vice versa.
The following example illustrates how the addition operator processes expressions of different types.
var str : String = "42"; var n : double = 20; var c : char = "A"; // the numeric value of "A" is 65 var result; result = str + str; // result is the string "4242" result = n + n; // result is the number 40 result = c + c; // result is the string "AA" result = c + n; // result is the char "U" result = c + str; // result is the string "A42" result = n + str; // result is the string "2042" // Use explicit type coversion to use numbers as strings, or vice versa. result = int(str) + int(str); // result is the number 84 result = String(n) + String(n); // result is the string "2020" result = c + int(str); // result is the char "k"