I read about the way Java works with += operator, using StringBuilder.
Is it the same with a ("a" + "b") operation?
I read about the way Java works with += operator, using StringBuilder . Is
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Java, String instances are immutable.
So, if you do:
You are creating new Strings every time you concatenate.
On the other hand, StringBuilder is like a buffer that can grow as it needs when appending new Strings.
Rule of the thumb is (changed thanks to the comments I got):
If you are going to concatenate a lot (i.e., concatenate inside a loop, or generating a big XML formed by several string concatenated variables), do use StringBuilder. Otherwise, simple concatenation (using + operator) will be just fine.
Compiler optimizations also play a huge role when compiling this kind of code.
Here’sfurther explanation on the topic.And more StackOVerflow questions on the issue:
Is it better to reuse a StringBuilder in a loop?
What's the best way to build a string of delimited items in Java?
StringBuilder vs String concatenation in toString() in Java