Java OCAJP7: StringBuilder objects modification

The behavior of the objects of the StringBuilder class is different from that of String objects as regards their modification. String objects are immutable, so each time you perform an operation that changes the, value, a new object with the new value is created, while the original doesn’t change. In the case of StringBuilder objects instead the changes are always made on the original object and, if the return value of the method is assigned to another reference, it will point to the same object with the same value.

public class StringBuilderTest {

   public static void main(final String[] args) {

        String s = "Example string";
        s.substring(0,8);        // if the return value is not assigned the substring result is lost
        System.out.println(s);   // the original value of s doesn't change

        String s2 = s.substring(0,8);   // here the return value is assigned to another reference

        System.out.println(s);          // the original value of s doesn't change
        System.out.println(s2);         // s2 is a brand new object with the new value coming from substring

		
        StringBuilder sb1 = new StringBuilder("aaa");

        sb1.append(" bbb");               // even without assigning the return value
        System.out.println("1) " + sb1);  // the modification is made on the original StringBuilder object
        sb1.insert(3, "xxx");
        System.out.println("2) " + sb1);
        sb1.reverse();
        System.out.println("3) " + sb1);

        StringBuilder sb2 = sb1.append(" yyyy");  // here the return value is assigned to another reference
        System.out.println("sb2) " + sb2);        // the modification is made on the original StringBuilder object
        System.out.println("4) " + sb1);          // sb is not a new object but refers to sb1 (so the printed value is the same)
    }

}

OUTPUT

Example string
Example string
Example 
1) aaa bbb
2) aaaxxx bbb
3) bbb xxxaaa
sb2) bbb xxxaaa yyyy
4) bbb xxxaaa yyyy
This entry was posted in $1$s. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *