Java : Appendable with Examples

Appendable (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Appendable methods.


Summary

An object to which char sequences and values can be appended. The Appendable interface must be implemented by any class whose instances are intended to receive formatted output from a Formatter.

Class diagram

try (final var writer = new StringWriter()) {

    final Appendable appendable = writer;
    appendable.append("abc").append('-').append("XYZ");

    System.out.println(writer); // abc-XYZ
}
final var cb = CharBuffer.allocate(7);
final Appendable appendable = cb;

appendable.append("abc").append('-').append("XYZ");

System.out.println(Arrays.toString(cb.array())); // [a, b, c, -, X, Y, Z]

Methods

Appendable append (char c)

Appends the specified character to this Appendable.

final var cb = CharBuffer.allocate(3);
final Appendable appendable = cb;

appendable.append('a').append('b').append('c');

System.out.println(Arrays.toString(cb.array())); // [a, b, c]

Appendable append (CharSequence csq)

Appends the specified character sequence to this Appendable.

final var cb = CharBuffer.allocate(6);
final Appendable appendable = cb;

appendable.append("abc").append("XYZ");

System.out.println(Arrays.toString(cb.array())); // [a, b, c, X, Y, Z]
final var cb = CharBuffer.allocate(7);
final Appendable appendable = cb;

final var sb = new StringBuilder();

sb.append("ab");
appendable.append(sb);

sb.append(123);
appendable.append(sb);

System.out.println(Arrays.toString(cb.array())); // [a, b, a, b, 1, 2, 3]

Appendable append (CharSequence csq, int start, int end)

Appends a subsequence of the specified character sequence to this Appendable.

final var cb = CharBuffer.allocate(6);
final Appendable appendable = cb;

final var csq = "abc";

appendable.append(csq, 0, 1);
System.out.println(Arrays.toString(cb.array())); // [a,  ,  ,  ,  ,  ]

appendable.append(csq, 0, 2);
System.out.println(Arrays.toString(cb.array())); // [a, a, b,  ,  ,  ]

appendable.append(csq, 0, 3);
System.out.println(Arrays.toString(cb.array())); // [a, a, b, a, b, c]
final var cb = CharBuffer.allocate(6);
final Appendable appendable = cb;

final var csq = "abc";

appendable.append(csq, 0, 3);
System.out.println(Arrays.toString(cb.array())); // [a, b, c,  ,  ,  ]

appendable.append(csq, 1, 3);
System.out.println(Arrays.toString(cb.array())); // [a, b, c, b, c,  ]

appendable.append(csq, 2, 3);
System.out.println(Arrays.toString(cb.array())); // [a, b, c, b, c, c]

Related posts

To top of page