CKTIS / Java
nio.Buffer: practical reference
nio.Buffer: practical reference: Buffer is the base NIO buffer state machine, maintaining capacity, limit, position, and an optional mark.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.nio.BufferBuffer is the base NIO buffer state machine, maintaining capacity, limit, position, and an optional mark.
Use Buffer state deliberately: write until position advances, flip to make the written prefix readable, then clear or compact before the next input cycle.
clear does not erase content, and rewind does not change the limit. Changing position or limit below the mark discards the mark; buffers are not generally safe for concurrent mutation.
A relative transfer beyond the remaining elements throws BufferUnderflowException or BufferOverflowException without transferring data. Absolute access does not move position but is checked against limit.
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 {
java.nio.Buffer buffer = java.nio.ByteBuffer.allocate(4);
buffer.position(2);
buffer.flip();
System.out.println(buffer.limit() + ":" + buffer.position());
}
}
Result
2:0
The example exercises the documented element in a small deterministic program and compares exact standard output.