Hi Ranchers,
Say i have a following class.
class Test{
public method1(){
String str = buildString();
....
....
}
public method2(){
String str = buildString();
....
....
}
public method3(){
String str = buildString();
....
....
}
private String buildString() {
StringBuffer sb = new StringBuffer();
sb.append(MyConstant.ITEM);
sb.append(" , ");
sb.append(MyConstant.CODE);
return sb.toString();
}
}
So in the above piece of code my methods make use of a particular String constant, which i obtain through the above buildString() method.
I feel there is a performance issue in the above case, and was wondering if i could optimise it, then i came up with something as such:
class Test{
private static final String str = MyConstant.ITEM + " , " + MyConstant.CODE;
public method1(){
String str = Test.str;
....
....
}
public method2(){
String str = Test.str;
....
....
}
public method3(){
String str = Test.str;
....
....
}
}
But again in the above case, the concatenation operator will cause an overhead if there are say 10 constants (or literals) to be concateneted.
Is there a better way around ??
I thought of using a static block at the class level, where i wanted my String to be a final and Static one, but i wont be able to refer to it frm methods as the scope would die outside the static block itself.
class Test {
static{
final StringBuffer sb = new StringBuffer();
sb.append(MyConstant.ITEM);
sb.append(" , ");
sb.append(MyConstant.CODE);
final String str = sb.toString();
}
method1(){
String string1 = Test.str; ----> not possible cos the scope dies outside the static block
}
method2(){
String string2 = Test.str;
}
}
Please give your valueable feedbacks.