Sub topic 8
Combining Strings
A Java String is a value that holds text. Often, the text you want is made from several pieces. For example, a greeting might combine a fixed word with a person’s name.
Concatenation means joining pieces of text into one string. It matters when you build messages, labels, and other text from values that can change.
Join text with `+`
The + sign is an operator: a symbol that tells Java to perform an action. When you use it to combine a string with another value, it joins their text.
A string literal is text written between double quotation marks, such as "Hello, ". A variable is a named place to store a value. In this example, name stores a string:
class Greeting {
public static void main(String[] args) {
String name = "Ada";
String greeting = "Hello, " + name + "!";
System.out.println(greeting);
}
}Save the code as Greeting.java. Then compile and run it:
javac Greeting.java
java GreetingThe output is:
Hello, Ada!A class groups Java code. The main method is where this program starts. A method is a named action that code can use. Here, System.out.println prints the greeting.
Java joins the pieces in this order:
- The literal
"Hello, ", which ends with a space. - The value of
name, which is"Ada". - The literal
"!".
The result is stored in the greeting variable. Changing name in the program lets you create a different greeting.
Spaces and punctuation are your job
Concatenation does not add spaces or punctuation. You must include them in the pieces you join.
For example, "Hello," + "Ada" produces "Hello,Ada". To put a space after the comma, use "Hello, " + "Ada".
An empty string is a string with no text, written as "". Joining it to another string adds nothing you can see. A string containing one space, written as " ", is not empty.
Combine strings with other values
Java can also join a string with a number or a boolean value. A boolean is a value that is either true or false. Java turns the other value into text for the combined result.
For example, "Score: " + 10 produces "Score: 10", and "Ready: " + true produces "Ready: true".
This conversion does not change the original value. If an int variable holds 10, it still holds the number 10 after you use it in a message. An int is a type used for whole numbers.
Watch the order of operations
The + operator also adds numbers. An expression is a piece of code that produces a value. In a chain of + operations, Java groups the operations from left to right.
| Expression | Result | What happens |
|---|---|---|
| `2 + 3 + " points"` | `"5 points"` | Java adds the numbers first. |
| `"Points: " + 2 + 3` | `"Points: 23"` | Java joins each number as text. |
| `"Points: " + (2 + 3)` | `"Points: 5"` | Parentheses make Java add the numbers first. |
Parentheses group the calculation you want Java to perform. This is useful when a message contains a total.
class OrderTotal {
public static void main(String[] args) {
int apples = 2;
int oranges = 3;
System.out.println("Items: " + apples + oranges);
System.out.println("Items: " + (apples + oranges));
}
}Save this as OrderTotal.java, compile it with javac OrderTotal.java, and run it with java OrderTotal. It prints:
Items: 23
Items: 5In the first line, Java has already started joining text when it reaches oranges. In the second line, it calculates the total inside the parentheses first.
Add to a string variable with `+=`
The += operator is a shorter way to combine a variable’s current value with another value and store the result back in that variable.
class AddToMessage {
public static void main(String[] args) {
String message = "Hello";
String original = message;
message += ", Ada";
message += "!";
System.out.println(message);
System.out.println(original);
}
}Save this as AddToMessage.java, compile it with javac AddToMessage.java, and run it with java AddToMessage. The output is:
Hello, Ada!
HelloThe statement message += ", Ada"; has the same effect here as message = message + ", Ada";. It stores the combined text in message.
Strings cannot be changed after they are created. Combining text gives message a result; it does not change the "Hello" value held by original.
Join several pieces with a separator
Sometimes each piece needs the same separator, such as a comma and a space. A separator is text placed between items. The String.join method can add one for you.
class JoinColors {
public static void main(String[] args) {
String colors = String.join(", ", "red", "blue", "green");
System.out.println(colors);
}
}Save this as JoinColors.java, compile it with javac JoinColors.java, and run it with java JoinColors. It prints:
red, blue, greenThe first value, ", ", is the separator. The other values are the pieces to join. The method places the separator between pieces, not after the last one.
This can be easier to read than writing "red" + ", " + "blue" + ", " + "green". It also helps you avoid missing a separator. Empty pieces still count: joining "red", "", and "blue" with ", " produces "red, , blue".
Know how `null` affects combining
null means that a variable does not hold an object. It is different from an empty string.
When + combines a string with null, the result contains the four letters null. For example, if name is null, then "Hello, " + name produces "Hello, null". That may be valid Java, but it may not be the message you want a person to see.
One way to provide a fallback is to check the value before combining it:
class OptionalName {
public static void main(String[] args) {
String name = null;
if (name == null) {
name = "guest";
}
String greeting = "Hello, " + name + "!";
System.out.println(greeting);
}
}Save this as OptionalName.java, compile it with javac OptionalName.java, and run it with java OptionalName. It prints Hello, guest!.
The if statement runs its code only when its condition is true. Here, the check replaces a missing name before the greeting is built.
Another option: `concat`
A string also has a concat method. For example, "Hello, ".concat("Ada") produces "Hello, Ada".
For a few pieces, + is often easier to read. There is also a difference when the value to add is null: + can turn it into the text "null", but concat does not accept null as the value to add. It throws an exception, which is an error reported while the program runs.
Practice
Exercise
What does "Total: " + 4 + 5 produce? Change the expression so it produces "Total: 9".
Show answer
It produces "Total: 45". Use "Total: " + (4 + 5) to add the numbers before joining them to the text.
Exercise
What does String.join(" - ", "cat", "dog", "bird") produce?
Show answer
It produces "cat - dog - bird". The separator appears between the three pieces, but not after the last one.