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.
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 :)
Yay, you’re back! We missed you.
:) Yay. Hope will get more time to write. Thanks for following.. ^_^
Hi Viral,
few small comments.
1.) The taken example isn’t well-chosen.
will be compiled as
2.) if you consider following case
this will lead in a more optimised bytecode by the compiler
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
very good stuff. Thanks
Excellent