String concatenation refers to the process of joining two or more strings together.
Using the + Operator
The + operator can be used to merge strings. This is called concatenation:
Example
String carMake = "Toyota"; String carModel = "Supra"; System.out.println(carMake + " " + carModel);
Note that we included an empty string (” “) to create a space between carMake and carModel when printing.
Using the concat() Method
You can also use the concat() method to concatenate two strings:
Example
String carMake = "Toyota "; String carModel = "Supra"; System.out.println(carMake.concat(carModel));
Additional Information
String concatenation is useful in various scenarios, such as generating dynamic messages or combining user input.
You can also concatenate multiple strings in a single statement:
Example
String brand = "Toyota"; String model = "Supra"; String year = "2025"; System.out.println(brand + " " + model + " " + year);
This creates a full sentence combining all three strings with spaces in between.
Efficiency Note
While concatenation using + is simple, for larger applications or loops, StringBuilder or StringBuffer is recommended for better performance:
Example
StringBuilder carDetails = new StringBuilder();
carDetails.append("Toyota");
carDetails.append(" ");
carDetails.append("Supra");
System.out.println(carDetails.toString());

