Java String Concatenation
Concatenation is the act of joining two or more Strings into a single, longer String. Java gives you a friendly way to do this with the plus operator, plus a dedicated method when you need more control.
Joining with the + Operator
The simplest way to combine text is with the + operator. Java reads the Strings from left to right and glues them together into one result. This is handy for building messages out of separate pieces, such as a first name and a last name.
Combining names
String first = "Ada";
String last = "Lovelace";
String fullName = first + " " + last;
System.out.println(fullName); // Ada LovelaceNotice the " " in the middle. Without that space, the two words would run together as "AdaLovelace". You are responsible for adding any spaces or punctuation you want between the parts.
The concat() Method
String also offers a concat() method that appends one String to another. It behaves like the + operator for text, but it only accepts Strings, which can make your intent clearer when you know both sides are text.
Using concat()
String hello = "Hello, ";
String target = "world!";
System.out.println(hello.concat(target)); // Hello, world!Mixing Text and Numbers
When you use + with a String and a number, Java converts the number to text and joins them. This is great for output, but watch the order: if numbers appear before any String, they are added arithmetically first.
Order matters
System.out.println("Score: " + 10 + 5); // Score: 105
System.out.println("Score: " + (10 + 5)); // Score: 15