userimage

Relation between String, StringBuffer, and StringBuilder in java

can somebody explain me the behavior of String, StringBuffer, and StringBuilder. As of my knowledge all of them looks same, then what are the difference between these or is there any relation exist in those classes?

userimage

No there is no relations exist in between mentioned classes. Its might by implementation of view looks same but there is a huge difference in between those like,

  • String is immutable. Being immutable we mean that once a String is created, we can not change its value.

             String s = "Hello";
             s = s + " World!";
             System.out.println(s);

  • StringBuffer is mutable. Once a StringBuffer object is created, we just append the content to the value of object instead of creating a new object.

            StringBuffer sb = new StringBuffer("Hello");
            sb.append(" World!");
            System.out.println(sb.toString()); //Hello World!

  • StringBuilder is similar to StringBuffer but it is not thread-safe. Methods of StingBuilder are not synchronized but in comparison to other Strings, the Stringbuilder runs fastest.

            StringBuilder sb = new StringBuilder("Hello");
            sb.append(" World!");
            System.out.println(sb.toString()); //Hello World!


Answer is