CKTIS / Java
ByteBuffer — binary data and buffer state
ByteBuffer stores bytes and supports reading and writing binary values. Learn buffer creation, byte order, and how flip, clear, and compact control position and limit.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
ByteBuffer b = ByteBuffer.allocate(capacity).order(ByteOrder.BIG_ENDIAN);
b.putInt(value).putShort((short) count);
b.flip();
int valueRead = b.getInt();
short countRead = b.getShort();java.nio.ByteBuffer is a fixed-capacity byte buffer also used for I/O. ByteBuffer.allocate(n) creates an array-backed buffer, while ByteBuffer.wrap(array) shares an existing array without copying. ByteBuffer.allocateDirect(n) creates a direct buffer: the JVM attempts to reduce copying during native I/O, but faster performance is not guaranteed. ByteBuffer.isDirect() identifies this buffer kind.
ByteBuffer.capacity() returns the fixed capacity in bytes. ByteBuffer.position() identifies the next byte, and ByteBuffer.limit() identifies the first inaccessible index; overloads taking an argument set these values. The invariant is 0 <= position <= limit <= capacity, and ByteBuffer.remaining() equals limit - position.
ByteBuffer.put and ByteBuffer.get write and read bytes. ByteBuffer.putInt / ByteBuffer.getInt handle 4 bytes, and ByteBuffer.putShort / ByteBuffer.getShort handle 2 bytes. Relative operations advance the position; indexed overloads do not, but still respect the limit. ByteBuffer.order() retrieves the byte order, and order(ByteOrder.LITTLE_ENDIAN) changes it; the default is BIG_ENDIAN. Insufficient space or data in a relative operation causes BufferOverflowException or BufferUnderflowException, respectively.
After writing, ByteBuffer.flip() sets the limit to the previous position and the position to zero. ByteBuffer.compact() moves unread bytes to the beginning, sets the position just after them and the limit to capacity, allowing more data to be appended. ByteBuffer.clear() sets the position to zero and the limit to capacity, but does not erase data. Concurrent access to a buffer requires synchronization.
Examples
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Main {
public static void main(String[] args) {
ByteBuffer b = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
b.putInt(16909060).putShort((short) 7).put((byte) 9);
System.out.println(b.position() + " " + b.limit() + " " + b.capacity());
b.flip();
System.out.println(b.getInt() + " " + b.getShort());
b.compact();
b.put((byte) 10);
b.flip();
System.out.println(b.remaining() + " " + b.get() + " " + b.get());
b.clear();
System.out.println(b.position() + " " + b.limit());
}
}
Result
7 8 8 16909060 7 2 9 10 0 8
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.