String concatenation
- Java course
- Beginner
- Lesson 15/116
- 4 min
Learn text joining with +.
The String + operator
In Java the + operator does two things: it adds numbers and concatenates Strings. If at least one side is a String, + concatenates.
String name = "Alex";
String msg = "Hello " + name;
// "Hello Alex"If you concatenate a String with a number, the number is automatically turned into a String:
"Age: " + 28 // "Age: 28"Number + String
When you concatenate a String and a number with +, Java turns the number into a String and places them side by side:
int age = 28;
System.out.println("Age: " + age);
// Age: 28Watch out: 1 + 2 + "x" first adds 1 + 2 (3), then concatenates 3 + "x" ("3x"). "x" + 1 + 2 becomes "x12" because it goes left to right.
Operator precedence and associativity matter.
Practice Concatenate Strings
Write a Main class with a main method. Assign "Alex" to String name and 28 to int age. Print "Hello " + name + " " + age with println.
Sample solution
public class Main {
public static void main(String[] args) {
String name = "Alex";
int age = 28;
System.out.println("Hello " + name + " " + age);
}
}Expected output
Hello Alex 28
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the concatenation
String msg = "Hello " + ____;
String msg = "Hello " + "Alex";
Explanation: Two Strings are joined with +.
2 Match the concatenation types
| Term | Meaning |
|---|---|
"a" + "b" |
Concatenation |
5 + 3 |
Addition |
"" + 5 |
To string |
+ |
Operator |
3 Which is a String concatenation?
- 5 + 3
- 4 * 2
- 10 - 2
- "x" + 5 Correct answer
Explanation: String + number concatenates.