Yes i have read all material on internet regarding their difference.and that difference is totally based on concatenation performance of both.My question is that in the below code which technique is better.
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("test");
System.out.println(str.toString());
str = new StringBuilder("Hi ");
System.out.println(str.toString());
}
}
here is string demo
public class StringDemo {
static String str="";
public static void main(String[] args) {
str = "test";
System.out.println(str);
str ="Hi";
System.out.println(str);
}
}
My assumptions are since strings are immutable so when we assign "Hi" to str "test " also remain in memory(two objects of string created "Hi" and "test" ).where as in case of string builder when we give value "Hi" "test" is removed.so we have one object in case of string builder. So i concluded that we should use string builder in these cases. Correct me if i am being childish here .