In Java, sometimes you may wonder why existing StringBuilder and StringBuffer along with String, how they are different, and what are the use cases. Let's walk through this tutorial to figure out

String is immutable

String in Java is immutable. When you attempt to change its value, a new string will be created and returned

@Test
public void stringIsImmutable() {  
    String s1 = "Hello Koding";
    String s2 = s1;
    assertThat(s1 == s2).isTrue();

    s1 = s1.concat(" is awesome!");
    assertThat(s1 == s2).isFalse();
}

s1.concat(" is awesome!") internally creates and returns a new string object to fill the concatenation value. s1 now points to different object from s2

StringBuffer is mutable

StringBuffer is like a String but can be modified, designed to be used in a multi-threaded environment

@Test
public void StringBufferIsMutable() {  
    StringBuffer s1 = new StringBuffer("Hello Koding");
    StringBuffer s2 = s1;
    assertThat(s1 == s2).isTrue();

    s1 = s1.append(" is awesome!");
    assertThat(s1 == s2).isTrue();
}

s1.append(" is awesome!") does not create a new StringBuffer object, internally, it appends the " is awesome!" into a resizable array. s1 and s2 still point to the same object

StringBuilder is mutable and faster

StringBuilder is like StringBuffer but with faster performance, designed to be used in a single-threaded environment

@Test
public void StringBuilderIsMutable() {  
    StringBuilder s1 = new StringBuilder("Hello Koding");
    StringBuilder s2 = s1;
    assertThat(s1 == s2).isTrue();

    s1 = s1.append(" is awesome!");
    assertThat(s1 == s2).isTrue();
}

Conclusion

In this tutorial, we learned about the difference between String, StringBuffer, and StringBuilder. You can find below the full source code