We can concatenate strings with other types of data.
For example,
int age = 9; String s = "He is " + age + " years old."; System.out.println(s);
age
is an int rather than another String.
The int value in age
is automatically converted into its string representation.
Java will convert an operand to its string equivalent whenever the other operand of the + is an instance of String.
Consider the following:
String s = "four: " + 2 + 2;
System.out.println(s);
This fragment displays
four: 22
rather than the
four: 4
The concatenation of "four" with the string 2 happens first.
This result is then concatenated with the string equivalent of 2 again.
To complete the integer addition first, you must use parentheses, like this:
String s = "four: " + (2 + 2);
Now s contains the string "four: 4".