Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

13. Concatenating strings versus StringBuilder

Check out the following plain string concatenation:

String str1 = "I love";
String str2 = "Java";
String str12 = str1 + " " + str2; 

We know that the String class is immutable (a created String cannot be modified). This means that creating str12 requires an intermediary string that represents the concatenation of str1 with white space. So after str12 is created, we know that str1 + " " is just noise or garbage, since we cannot refer to it further.

In such scenarios, the recommendation is to use a StringBuilder, since it is a mutable class and we can append strings to it. So this is how the following statement was born: In Java, don’t use the “+" operator to concatenate strings! Use StringBuilder, which is much faster.

Have you heard this statement before? I’m pretty sure you have, especially if you still run your applications on JDK 8 or even on a previous...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard