Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

lang.StringBuffer: practical reference

lang.StringBuffer: practical reference: StringBuffer is a mutable synchronized character sequence; individual methods are synchronized but compound protocols need coordination.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.lang.StringBuffer

StringBuffer is a mutable synchronized character sequence; individual methods are synchronized but compound protocols need coordination.

Use StringBuffer when one mutable character sequence must be shared across threads and each individual operation needs synchronization.

Synchronization of individual calls does not make a read-modify-write sequence atomic. An append or insert synchronizes on the destination, not on a mutable source sequence.

append(null) writes the four characters null. compareTo compares content, but StringBuffer inherits identity-based equals, so its natural ordering is inconsistent with equals.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var text = new StringBuffer("Ja");
        text.append("va");
        System.out.println(text);
    }
}

Result

Java

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources