Skip to main content

Command Palette

Search for a command to run...

Difference between String, StringBuilder and String Buffer

Updated
1 min read
S

I love learning about technology and sharing that with others

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

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)