CKTIS / Java
Direct ByteBuffer: writing, reading, and preserving unread bytes
Write six bytes into a 32-byte direct buffer and see how `flip()`, `compact()`, and `clear()` change the range available for reading or writing.
Version: Java SE 21
Syntax
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
ByteBuffer b = ByteBuffer.allocateDirect(32);
b.isDirect();
b.capacity();
b.order();
b.order(ByteOrder.LITTLE_ENDIAN);
b.position();
b.position(newPosition);
b.limit();
b.limit(newLimit);
b.putInt(intValue);
b.putInt(byteIndex, intValue);
b.putShort(shortValue);
b.putShort(byteIndex, shortValue);
b.getInt();
b.getInt(byteIndex);
b.getShort();
b.getShort(byteIndex);
b.clear();
b.flip();
b.compact();In Java SE 21, the static method java.nio.ByteBuffer.allocateDirect(n) creates a direct buffer with room for n bytes; a negative capacity throws IllegalArgumentException. isDirect() tells you whether a buffer is direct. The JVM tries to avoid intermediate copies for native I/O but does not guarantee it. The contents may live outside the Java heap. None of the operations covered here releases the buffer's storage.
capacity() returns the fixed capacity in bytes, position() is the next byte offset for relative access, and limit() is the first inaccessible offset. The initial position is 0, the limit equals the capacity, and the bytes are zeroed. position(p) requires 0 <= p <= limit; limit(l) requires 0 <= l <= capacity and lowers the position to l if needed. Invalid arguments throw IllegalArgumentException. Each setter discards the mark if it exceeds the new position or limit, respectively.
order() reports the byte order, initially ByteOrder.BIG_ENDIAN (most significant byte first). order(ByteOrder.LITTLE_ENDIAN) switches subsequent multibyte access to least significant byte first without rearranging stored bytes. Choose the order specified by the data format, not by the CPU.
putInt(value) and getInt() write or read four bytes; putShort(value) and getShort() use two. Relative operations start at position() and advance it by the width. If limit - position is too small, a read throws BufferUnderflowException, and a write to a writable buffer throws BufferOverflowException. A write to a read-only buffer can throw ReadOnlyBufferException. If a relative write targets a read-only buffer and too few bytes remain, Java SE 21 does not specify which of the two write exceptions takes precedence. The absolute overloads getInt(i), getShort(i), putInt(i, value), and putShort(i, value) leave the position unchanged. Their entire byte range must fit in [0, limit), or they throw IndexOutOfBoundsException.
flip() sets the limit to the old position and resets the position to 0 for reading. clear() sets the position to 0 and the limit to capacity for a full refill without erasing data. After a partial read, ByteBuffer.compact moves the bytes in [position, limit) to the beginning, sets the position to the number retained, and restores the limit to capacity so you can append. Call flip() before reading again. All three methods discard the mark; compact() throws ReadOnlyBufferException on a read-only buffer.
Examples
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Main {
public static void main(String[] args) {
ByteBuffer b = ByteBuffer.allocateDirect(32).order(ByteOrder.LITTLE_ENDIAN);
System.out.println("direct=" + b.isDirect() + ", capacity=" + b.capacity()
+ ", order=" + b.order());
b.putInt(0x01020304).putShort((short) 200);
state("after put", b);
b.flip();
state("after flip", b);
System.out.println("first byte=" + b.get(0));
System.out.println("int=" + b.getInt());
state("after getInt", b);
b.compact();
state("after compact", b);
b.putShort((short) 300);
b.flip();
state("after second flip", b);
short retained = b.getShort();
short appended = b.getShort();
System.out.println("shorts=" + retained + ", " + appended);
b.clear();
state("after clear", b);
}
private static void state(String label, ByteBuffer b) {
System.out.println(label + ": position=" + b.position() + ", limit=" + b.limit());
}
}Result
direct=true, capacity=32, order=LITTLE_ENDIAN after put: position=6, limit=32 after flip: position=0, limit=6 first byte=4 int=16909060 after getInt: position=4, limit=6 after compact: position=2, limit=32 after second flip: position=0, limit=4 shorts=200, 300 after clear: position=0, limit=32
The payload uses six of the 32 bytes. The absolute `get(0)` shows the least significant byte (`4`) without advancing the position. After reading the `int`, `compact()` retains the two bytes for `200`; after appending `300`, the second `flip()` makes both values readable. `clear()` restores the full write range.
Related lessons
- Java · Lesson 50 · Advanced · Version: 2