Eclipse: Convert String Concat to StringBuilder

Here is a simple yet effective trick for all Eclipse users. In Java we do lot of String concatenation using plain old “” + “”. It is easy but not too effective. StringBuilder is always preferred if you have too many strings to concate.

eclipse-string-concatenate-stringbuilder

In below screencast, I convert concatenated strings to StringBuilder using eclipse Ctrl + 1 option.

Move cursor on String “foo” and press Ctrl + 1. It opens a context menu. Select option Use “StringBuilder” for string concatenation

String foo = "This" + "is" + "Sparta"; System.out.println(foo);
Code language: Java (java)

Once done, the code will be converted to below:

StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("This"); stringBuilder.append("is"); stringBuilder.append("Sparta"); String foo = stringBuilder.toString(); System.out.println(foo);
Code language: Java (java)

Enjoy :)

Get our Articles via Email. Enter your email address.

You may also like...

5 Comments

  1. Neil says:

    Yay, you’re back! We missed you.

    • :) Yay. Hope will get more time to write. Thanks for following.. ^_^

  2. SubOptimal says:

    Hi Viral,

    few small comments.
    1.) The taken example isn’t well-chosen.

    String foo = "This" + "is" + "Sparta";


    will be compiled as

    String foo = "This is Sparta";

    2.) if you consider following case

    String foo = "This" + variable + "Sparta";


    this will lead in a more optimised bytecode by the compiler

    String foo = (new StringBuilder()).append("This").append(variable).append("Sparta").toString();

    3.) in case many variables needs to be concatenated I prefer to use String.format(..) (very simple example)

    String foo = String.format(“%s from %s has %s %s”, name, town, amount, gadgets);

    cheers

  3. Naga says:

    very good stuff. Thanks

  4. Sasi says:

    Excellent

Leave a Reply

Your email address will not be published. Required fields are marked *