Difference between String, StringBuilder and String Buffer
Storage: String uses String Pool, StringBuffer and StringBuilder uses heap
Mutability : String immutable -> String Builder and String buffer are mutable
Efficient : String builder is fastest then string buffer and then String
Thread-Safe => String is thread safe => StringBuffer is preferred for thread safety
Ques : If there are two strings and I wanted to concatenate them without initializing any extra string what is the best possible solution?
- Use StringBuilder for the concatenation , since stringbuilder and string buffer uses heap for the objects it will not create new object, we can use the append method.
public class Main
{
public static void main(String[] args) {
StringBuilder sb=new StringBuilder("hello");
sb.append("world");
System.out.println(sb.toString());
}
}