Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

CharBuffer: data ranges and shared views

CharBuffer holds char values within a range controlled by position and limit. Learn position-relative indexing and the difference between a shared read-only view and a copy of the data.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

CharBuffer b = CharBuffer.wrap(charArray);
b.position(start).limit(end);
CharBuffer view = b.slice();
CharBuffer readOnly = view.asReadOnlyBuffer();

java.nio.CharBuffer is a buffer of char values. CharBuffer.position() identifies the next position, CharBuffer.limit() is the exclusive boundary, and CharBuffer.remaining() returns limit() - position(). position(int) and limit(int) set the position and limit, respectively. remaining() has no overload that takes an argument, and there is no setter for the remaining count. The buffer satisfies 0 <= position() <= limit() <= capacity(). Lowering the limit below the position also lowers the position.

CharBuffer.charAt(i) reads element position() + i without advancing the position; it requires 0 <= i < remaining(). CharBuffer.toString() returns text from [position(), limit()), also without advancing the position.

CharBuffer.slice() shares the remaining range: position is zero; limit and capacity equal the original remaining(). CharBuffer.asReadOnlyBuffer() shares data and initially preserves the source's state. Each view's position, limit, and mark are independent. Read-only does not mean immutable data: writes through another writable view remain visible; writing through the read-only view throws ReadOnlyBufferException.

CharBuffer.rewind() zeroes the position and discards the mark, preserving the limit and data. It also works on a read-only view. In the example, changes through s are visible through ro, but repositioning ro does not change b's position.

Examples

import java.nio.CharBuffer;

public class Main {
    public static void main(String[] args) {
        CharBuffer b = CharBuffer.wrap(new char[] {'A', 'B', 'C', 'D', 'E'});
        b.position(1).limit(4);
        CharBuffer s = b.slice();
        CharBuffer ro = s.asReadOnlyBuffer();
        System.out.println(b.remaining() + ":" + b.charAt(0) + ":" + b.toString());
        s.put(0, 'X');
        ro.position(1);
        System.out.println(ro.toString());
        ro.rewind();
        System.out.println(ro.toString());
        System.out.println(b.position() + ":" + b.limit() + ":" + b.toString());
    }
}

Result

3:B:BCD
CD
XCD
1:4:XCD

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources