Careeroza
String Concatenation
Joining Strings
Example
Use +, concat(), String.join() or String.format().
public class Main {
public static void main(String[] args) {
String first = "Sneha";
String last = "Reddy";
System.out.println(first + " " + last);
System.out.println(first.concat(" ").concat(last));
System.out.println(String.join(" | ", "Java", "SQL", "Git"));
System.out.println(String.format("%s %s (%d)", first, last, 24));
System.out.println("Age: " + 20 + 4); // text + numbers
System.out.println(20 + 4 + " is the age"); // numbers first
}
}Output
Sneha Reddy Sneha Reddy Java | SQL | Git Sneha Reddy (24) Age: 204 24 is the age
Note: + works left to right: once a String appears, everything after it is joined as text. 20 + 4 + " x" gives 24 x, but "x " + 20 + 4 gives x 204.
Building Strings in a Loop
Example
Because Strings are immutable, += in a loop creates a new String every time. For many joins use StringBuilder (covered in detail in the medium level).
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i < 5) sb.append("-");
}
System.out.println(sb.toString());
}
}Output
1-2-3-4-5