๐Ÿ  Home โ€บ OOP and Encapsulation โ€บ StringBuilder Reference Behavior
OOP AND ENCAPSULATION

StringBuilder Reference Behavior

Java is pass-by-value for references. You get a copy of the reference, not the reference itself.

public class StringBuilderExample {
    static void modifyContent(StringBuilder sb) {
        sb.append(" modified");     // โœ… Modifies the object - caller sees this
        System.out.println("Inside method after append: " + sb);
    }
    
    static void reassignReference(StringBuilder sb) {
        sb.append(" first");        // โœ… Modifies original object
        sb = new StringBuilder("completely new");  // โŒ Only changes local copy of reference
        sb.append(" content");      // โŒ Modifies the new object, not original
        System.out.println("Inside method after reassign: " + sb);
    }
    
    public static void main(String[] args) {
        StringBuilder original = new StringBuilder("start");
        
        modifyContent(original);
        System.out.println("After modifyContent: " + original);  // "start modified"
        
        reassignReference(original);  
        System.out.println("After reassignReference: " + original);  // "start modified first"
        // Note: "completely new content" is lost!
    }
}

๐Ÿ’ก Learning Tip: You can change the objectโ€™s content through the reference, but you canโ€™t change where the original reference points.