Last Updated on 25 August 2019   |   Print Email
In this article, I\d like to share with you some tips about using Strings in Java programming. You will understand deeper about Strings in Java, how to use String effectively and avoid beginner’s mistakes. Especially you will understand the differences between StringBuffer and StringBuilder, and when to use them properly.Let’s consider the following code snippet:
As you can see, this code constructs a SQL Insert statement by concatenating multiple Strings together.
So what is the problem with normal String concatenation?
You know, String is immutable, which means a String object cannot be changed once created. For example:
String sql = "Insert Into Users (name, email, pass, address)";
This String object cannot be modified afterward. That also means each time you concatenate Strings using the + operator, new String objects get created. For example:
sql += " values ('";
Here, two additional String objects are created: one holds the “ values (‘” literal and one holds the result of concatenation.And you know, object create always takes more time than other operations, so concatenating many Strings like the code snippet above results in many intermediate String objects created, which results in inefficient code.
So how to solve the problems with Strings concatenation?
StringBuilder comes to rescue. Java provides the StringBuilderclass that is mutable and is designed to solve the performance issue with normal String concatenation.The code snippet above can be re-written using StringBuilder like this:
So remember when you concatenate many Strings (typically in constructing SQL statements and generating HTML code), use StringBuilder to gain performance.See Javadoc for StringBuilder here.
How about using the StringBuffer class in Java?
StringBuffer acts like StringBuilder, as it has same methods except they are synchronized. That means StringBuffer should be used in multi-threading context. The above code can be re-written using StringBuffer like this:
See Javadoc for StringBuffer here.Therefore, it's a best practices in Java programming: Consider using StringBuilder to replace normal Strings concatenation. And consider using StringBuffer when thread-safety is required.Of course you have to write more code when using StringBuilder/StringBuffer, but the trade-off is you can gain more performance, and more importantly, you develop a habit of writing efficient code, not just working code.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments