Java String Concatenation: Using the + Operator and concat() Method
Learn how to concatenate strings in Java using the +
operator and the concat()
method. Discover the differences between these techniques and how to choose the best approach for your Java programs.
Java String Concatenation
In Java, strings can be concatenated using the +
operator or the concat()
method.
Using the +
Operator:
The +
operator can be used to concatenate strings together:
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // Outputs "John Doe"
Note: Adding an empty string (" "
) between variables or literals creates a space when concatenating strings.
Using the concat()
Method:
The concat()
method can also be used to concatenate strings:
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName.concat(lastName);
System.out.println(fullName); // Outputs "John Doe"
Both methods achieve the same result of combining strings together.
Choose whichever method you find more readable or suitable for your coding style.