DEV Community

Cover image for How to Concatenate Strings in Java like a Pro
Joshua Austin
Joshua Austin

Posted on

3

How to Concatenate Strings in Java like a Pro

String concatenation in Java can be initially tricky, especially if you come from other programming languages. When Java was first implemented, the decision was made to render the String class immutable. So what if you have to concatenate two or more strings? I remember being instructed to rely on the StringBuilder class like so:

StringBuilder sb = new StringBuilder();
sb.append("Gandalf");
sb.append(" ");
sb.append("The");
sb.append(" ");
sb.append("Grey");

String gandalf = sb.toString();
Enter fullscreen mode Exit fullscreen mode

Prior to Java 8, this was more efficient. However, now the compiler handles that for you by making + operations into StringBuilder operations at compile time.

However, this implementation is very naïve.

If this code

String firstName = "Frodo";
String lastName = "Baggins";
String fullName = firstName + " " + lastName;
Enter fullscreen mode Exit fullscreen mode

translates to this equivalent at compile time...

String firstName = "Frodo";
String lastName = "Baggins";
StringBuilder sb = new StringBuilder();
sb.append(firstName);
sb.append(" ");
sb.append(lastName);
String fullName = sb.toString();
Enter fullscreen mode Exit fullscreen mode

...what happens during a loop?

Unfortunately, this code

List<String> hobbits = List.of("Frodo", "Samwise", "Merry", "Pippin");
String greetAllHobbits = "";
for (String hobbit : hobbits) {
  greetAllHobbits += "Greetings, " + hobbit + "!\n";
}
Enter fullscreen mode Exit fullscreen mode

translates to roughly this equivalent at compile time

List<String> hobbits = List.of("Frodo", "Samwise", "Merry", "Pippin");
String greetAllHobbits = "";
for (String hobbit : hobbits) {
  StringBuilder sb = new StringBuilder(greetAllHobbits);
  sb.append("Greetings, ");
  sb.append(hobbit);
  sb.append("!\n");
  greetAllHobbits = sb.toString();
}
Enter fullscreen mode Exit fullscreen mode

A separate StringBuilder instance is created during each iteration, which can defeat the purpose of being efficient!

In the above case, you'll need to create a StringBuilder outside the loop so you aren't creating an unnecessary new object for each iteration.

List<String> hobbits = List.of("Frodo", "Samwise", "Merry", "Pippin");
StringBuilder sb = new StringBuilder();
for (String hobbit : hobbits) {
  sb.append("Greetings, ");
  sb.append(hobbit);
  sb.append("!\n");
}
String greetAllHobbits = sb.toString();
Enter fullscreen mode Exit fullscreen mode

In conclusion:

  • Use + when concatenating ad hoc
  • Use StringBuilder when concatenating with a loop

Top comments (1)

Collapse
 
raspberrycode profile image
RaspberryCode

Declarative approach:

StringBuilder greetAllHobbits = hobbits.stream()
                .reduce(new StringBuilder(),
                        (acc, b) -> acc.append("Greetings, %s!%n".formatted(b)),
                        StringBuilder::append);
Enter fullscreen mode Exit fullscreen mode

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay