Java String Concatenation: Rules, Examples, and Unicode Encoding
String concatenation (also called joining) is the operation of gluing strings together. In Java it is done with the + operator and its compound form +=. You can attach a value of any type to a String — a number, a character, an object — and it is automatically converted to text. The very same + sign sometimes means addition and sometimes concatenation, and one simple rule tells the two cases apart.
When + Means Concatenation and When It Means Addition
There are just two rules to remember:
- If at least one operand is a
String, the+operator performs string concatenation, and the other operand is automatically converted to text. - If both operands are numbers (including
char, which is an integral type), the+operator performs ordinary arithmetic addition.
This is not just a convention followed by compilers — it is defined by the official Java Language Specification, §15.18.1 «String Concatenation Operator +». The JLS states explicitly that if either operand of + is of type String, the operation is string concatenation; a char operand paired with a String is converted to its string representation (the character itself), while a char paired only with another numeric type is widened to int and added arithmetically.
| Operands | What + does | Example | Result |
|---|---|---|---|
String + String | Concatenation | "Hello " + "world" | "Hello world" |
String + any other type | Concatenation (the operand is converted to text) | "x=" + 5 | "x=5" |
| number + number | Addition | 4 + 5 | 9 |
char + char | Adds the character codes | 'A' + 'B' | 131 |
In the simplest case two strings are joined:
public class StringExample1 {
public static void main(String[] args) {
String str1 = "world";
System.out.println("Hello " + str1);
System.out.println("First line\n" + "Second line");
}
} Tip
The compound operator += works for strings too: str += " world"; is equivalent to str = str + " world";. As with a plain +, you can append a value of any type through += — it is converted to text first.
char in Concatenation: Where It Is Easy to Get It Wrong
The char type is a common trip-up. In the first System.out.println below, the console prints X Y: a char is joined with a String, so this is concatenation. In the second System.out.println, however, the output is not text but the number 177. A char is an integral type and can take part in arithmetic operations: there is no string in the expression, so the character codes are added — 88 + 89 = 177:
public class StringExample2 {
public static void main(String[] args) {
char x, y;
x = 88; // code of the character 'X'
y = 'Y';
System.out.println(x + " " + y); // prints X Y
System.out.println(x + y); // prints 177
}
} To print two characters side by side without a space, just introduce an empty string into the expression: System.out.println("" + x + y) prints XY. The same rule explains 'A' + 'B': with no string operand, the codes are added (65 + 66), giving 131.
Evaluation Order: Left to Right
An expression with several + operators is evaluated left to right, but operators with higher precedence run first. In the next example the console prints str=48: multiplication has higher precedence than addition, so 4 * 2 is computed first and gives 8. Then, going left to right, "str=" + 4 is already concatenation and yields "str=4", after which "str=4" + 8 gives "str=48":
public class StringExample3 {
public static void main(String[] args) {
System.out.println("str=" + 4 + 4 * 2);
}
} If you actually want the numbers added, change the order with parentheses: "str=" + (4 + 4 * 2) prints str=12. The reverse also holds: as long as there is no string on the left, + stays arithmetic — the expression 1 + 2 + "3" gives "33", because 1 + 2 is added first and only then is the result 3 attached to the string.
Important
Once a String shows up during left-to-right evaluation, the + operator «switches» into concatenation mode and never switches back: everything to the right is appended as text. That is exactly why "str=" + 4 + 8 gives str=48 and not str=12.
Unicode in String Literals
Inside string literals, just like in char variables, you can use Unicode escapes: \u followed by the hexadecimal code of the character:
public class StringExample4 {
public static void main(String[] args) {
// The word "Java" written with Unicode escapes
System.out.println("\u004A\u0061\u0076\u0061");
}
} The compiler decodes such sequences before it even parses the program, so the console prints the ordinary word Java.
Comparing Strings: equals(), Not ==
String is a reference type, so the comparison operator == does not compare the contents of the strings — it compares references, that is, whether both variables point to the same object in memory. Because of the string literal pool, == sometimes returns true «by accident», but for strings built at run time (including those produced by concatenating variables) it is unreliable. To compare contents, use equals() or Objects.equals() (since Java 7) — the latter is also null-safe:
import java.util.Objects;
public class StringExample5 {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hi";
System.out.println(str1.equals(str2));
System.out.println(Objects.equals(str1, str2));
}
} String Length: the length() Method
The length of a string is obtained with the length() method — it returns the number of characters:
public class StringExample6 {
public static void main(String[] args) {
String str = "Hello";
System.out.println("String length: " + str.length());
}
} Notice that concatenation is at work here as well: the number str.length() is automatically converted to text and appended to the message.
Frequently Asked Questions
What happens when you concatenate a string with null?
No exception is thrown: the expression "value: " + s when s == null returns the string "value: null" — the text «null» is substituted for the reference. A NullPointerException occurs only if you call a method on such a variable, for example s.length() or s.concat("...").
Why does "1" + 2 + 3 give "123" but 1 + 2 + "3" give "33"?
The expression is evaluated left to right. In the first case the string comes first, so both operations are concatenation: "1" + 2 gives "12", then "12" + 3 gives "123". In the second case the numbers are added first, 1 + 2 = 3, and only then is the result attached to the string: 3 + "3" gives "33".
When should you use StringBuilder instead of concatenation?
In loops and when assembling long text step by step. Strings in Java are immutable, so str += ... inside a loop creates a new string object on every iteration. StringBuilder accumulates characters in a mutable buffer via append() and produces the result with a single toString() call at the end. For a single expression made of several + operators the compiler optimizes the concatenation for you.
How is the + operator different from the concat() method?
The concat() method accepts only a String and throws a NullPointerException if called on a null variable. The + operator is more general: it accepts an operand of any type, converts it to text itself, and handles null gracefully. In practice + is used almost always; concat() is rare.
What does the official Java Language Specification say about char and the + operator?
Per the JLS §15.18.1, the + operator is string concatenation whenever at least one operand is a String — and in that case a char operand is converted to its string representation, so "x" + 'A' gives "xA". When neither operand is a String, the + operator is binary numeric addition: both operands (including any char) are widened to at least int, so 'A' + 'B' gives 131, not "AB".
Comments