Difference between String, StringBuilder and String Buffer

  1. Storage: String uses String Pool, StringBuffer and StringBuilder uses heap

  2. Mutability : String immutable -> String Builder and String buffer are mutable

  3. Efficient : String builder is fastest then string buffer and then String

  4. 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());
    }
}