Sub topic 8
Combining Strings
Joining text with `+`
Concatenation means joining pieces of text. In Java, the + operator can concatenate strings. An operator is a symbol that tells Java to perform an action.
For example, "Hello, " + "Ada" produces the string "Hello, Ada". Java does not add spaces between the pieces. The space after the comma is inside the first string.
You can combine string literals and variables in the same way. A string literal is text written between double quotes. A variable is a named place for a value.
A worked example
Save this program as CombineText.java, then compile and run it.
class CombineText {
public static void main(String[] args) {
String name = "Ada";
String greeting = "Hello, " + name + "!";
System.out.println(greeting);
System.out.println(name);
int apples = 2;
int pears = 3;
System.out.println("Total: " + apples + pears);
System.out.println("Total: " + (apples + pears));
String status = "Order";
status += " ready";
System.out.println(status);
}
}The output is:
Hello, Ada!
Ada
Total: 23
Total: 5
Order readyThe first line joins three pieces: "Hello, ", the value of name, and "!". The result is stored in greeting.
The next line shows that name is still "Ada". Combining it with other text did not change it. Strings are immutable, which means their contents cannot be changed after they are created.
Numbers and order
The two total lines give different results:
- In
"Total: " + apples + pears, Java combines the text andapplesfirst. The result is"Total: 2". It then addspearsas text, giving"Total: 23". - In
"Total: " + (apples + pears), the parentheses tell Java to add the numbers first. The sum is5, so the result is"Total: 5".
When + combines a string and a number, Java turns the number into text for the result. When both values are numbers, + adds them.
Adding to a variable
The last part of the program uses += to add text to the value stored in status:
class AddToStatus {
public static void main(String[] args) {
String status = "Order";
status += " ready";
System.out.println(status);
}
}Here, status += " ready"; is a shorter way to write status = status + " ready";. It combines the current value with the new text, then stores the result back in status.
This does not change the original string. The variable now refers to the combined string instead.
Exercise
If int count = 4;, what does "Count: " + count + 1 produce? How can you produce "Count: 5" instead?
Show answer
It produces "Count: 41" because the numbers are joined as text. Use "Count: " + (count + 1) to add them first.
Exercise
If String word = "rain";, what are the values of word and result after String result = word + "bow";?
Show answer
word is still "rain", and result is "rainbow".