Module java.base
Package java.nio

Class CharBuffer

java.lang.Object
java.nio.Buffer
java.nio.CharBuffer
All Implemented Interfaces:
Appendable, CharSequence, Comparable<CharBuffer>, Readable

public abstract sealed class CharBuffer extends Buffer implements Comparable<CharBuffer>, Appendable, CharSequence, Readable
A char buffer.

This class defines four categories of operations upon char buffers:

  • Absolute and relative get and put methods that read and write single chars;

  • Absolute and relative bulk get methods that transfer contiguous sequences of chars from this buffer into an array;

  • Absolute and relative bulk put methods that transfer contiguous sequences of chars from a char array, a string, or some other char buffer into this buffer;

  • A method for compacting a char buffer.

Char buffers can be created either by allocation, which allocates space for the buffer's content, by wrapping an existing char array or string into a buffer, or by creating a view of an existing byte buffer.

Like a byte buffer, a char buffer is either direct or non-direct. A char buffer created via the wrap methods of this class will be non-direct. A char buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a char buffer is direct may be determined by invoking the isDirect method.

This class implements the CharSequence interface so that character buffers may be used wherever character sequences are accepted, for example in the regular-expression package java.util.regex. The methods defined by CharSequence operate relative to the current position of the buffer when they are invoked.

Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained. The sequence of statements

    cb.put("text/");
    cb.put(subtype);
    cb.put("; charset=");
    cb.put(enc);
can, for example, be replaced by the single statement
    cb.put("text/").put(subtype).put("; charset=").put(enc);

Optional operations

Methods specified as optional operations throw a ReadOnlyBufferException when invoked on a read-only CharBuffer. The methods array and arrayOffset throw an UnsupportedOperationException if the CharBuffer is not backed by an accessible char array (irrespective of whether the CharBuffer is read-only).
Since:
1.4