HOWTO · Java

Byte Buffer Class in Java

Learn how Java ByteBuffer position, limit, and capacity control byte reads and writes, how to create and use a buffer, and how two Java examples read bytes and characters with getChar().

On this page

A ByteBuffer stores bytes and tracks the next position for reading or writing. Its position, limit, and capacity determine which bytes an operation can access. This guide explains those state changes, the main creation and access methods, and two self-contained Java examples: one for byte values and one for characters.

ByteBuffer Class in Java

java.nio.ByteBuffer is a byte-oriented NIO buffer used to move binary data between Java code and I/O channels. It does not store a series of integers as its fundamental data; methods such as putInt() encode a primitive value into bytes using the buffer’s byte order.

A buffer has three key state values:

  • Capacity is the fixed size of the buffer.
  • Position is the index of the next byte a relative read or write will use.
  • Limit is the first index that cannot be read or written. It is at most the capacity.

A new buffer from allocate() has position 0, limit equal to capacity, and no data written. Relative put() advances position. Calling flip() sets the limit to the current position and resets position to 0, preparing the written bytes for reading. Relative get() advances position as it reads. clear() prepares the whole buffer for another write by restoring the limit to capacity and position to 0; it does not erase the bytes. rewind() resets position to 0 while keeping the current limit, so the same readable region can be read again.

The class hierarchy is Object → Buffer → ByteBuffer. A buffer may be direct or non-direct. allocateDirect() requests storage outside the ordinary Java heap and can be useful for some I/O patterns, but it is not automatically faster. Prefer allocate() unless direct storage fits the application’s measured I/O needs.

Operational Categories of ByteBuffer Class in Java

ByteBuffer operations fall into a few practical groups:

  • Creation: allocate(capacity) creates a heap buffer, allocateDirect(capacity) requests a direct buffer, and wrap(byteArray) exposes an existing byte array through a buffer.
  • Relative access: get() and put(byte) use the current position and advance it. Their bulk overloads transfer multiple bytes and advance by the number transferred.
  • Absolute access: get(index) and put(index, value) address a specific index without changing position. The index still must be inside the current limit.
  • Primitive values and views: getInt(), putInt(value), getChar(), and putChar(value) convert between primitive values and bytes. The order() setting determines the byte order for these multi-byte values. A view such as asIntBuffer() interprets the bytes as integers without changing the original buffer’s position.
  • State and derived buffers: position(), limit(), remaining(), slice(), duplicate(), compact(), and rewind() let code inspect or manage the readable and writable region.

The wrap() method family creates a buffer backed by an existing array: ByteBuffer.wrap(byte[]) wraps bytes, not integers. To wrap an int[], use IntBuffer.wrap(intArray); it creates an integer buffer and is a different API. A byte array can also be viewed through a ByteBuffer as a sequence of bytes, then interpreted as primitive values according to its byte order.

Methods of Byte Buffer Class in Java

The following methods cover common creation, state, and data-access tasks:

Method Purpose
allocate(int capacity) Creates a heap ByteBuffer with the requested capacity.
allocateDirect(int capacity) Creates a direct ByteBuffer; allocation can have different costs from heap storage.
wrap(byte[] array) Creates a buffer backed by the supplied byte array.
capacity() Returns the fixed capacity.
position() / position(int) Reads or sets the next relative-access index.
limit() / limit(int) Reads or sets the end of the accessible region.
remaining() Returns limit() - position().
get() / put(byte) Reads or writes one byte at the current position and advances it.
get(int) / put(int, byte) Reads or writes at an index without changing position.
getInt() / putInt(int) and getChar() / putChar(char) Reads or writes primitive values using the current byte order.
order() / order(ByteOrder) Reads or sets the byte order used for multi-byte primitive values.
hasArray() / array() Checks for and returns an accessible backing byte array. Direct and read-only buffers may not expose one.
isDirect() Reports whether the buffer is direct.
flip() / clear() / rewind() Changes position and limit for reading, writing, or rereading.
slice() / duplicate() / compact() Creates a view, copies buffer state into a related view, or moves remaining bytes to the start for further writing.
asIntBuffer() Creates an integer view over the buffer’s remaining bytes.

For full API details, consult the Java ByteBuffer documentation.

Implementation of Byte Buffer in Java

This self-contained example writes two byte values, switches the buffer to read mode with flip(), then reads the values.

This complete program allocates a four-byte buffer, writes two values, flips it for reading, and prints the values and current state.

import java.nio.ByteBuffer;

public class ByteBufferBytes {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.put((byte) 20);
        buffer.put((byte) 40);
        buffer.flip();

        byte first = buffer.get();
        byte second = buffer.get();
        System.out.println("bytes=" + first + "," + second);
        System.out.println("position=" + buffer.position()
                + ", limit=" + buffer.limit()
                + ", capacity=" + buffer.capacity());
    }
}

Expected output:

bytes=20,40
position=2, limit=2, capacity=4

After the two reads, position is 2; limit remains 2, and capacity remains 4. An absolute write such as buffer.put(0, (byte) 7) changes the byte at index 0 without advancing position. A relative write uses the current position and advances it. Setting position or limit is constrained by the buffer’s current state, so set the limit before moving position beyond it. remaining() reports how many bytes are available between position and limit.

Implement the getChar Method of Byte Buffer Class in Java

getChar() reads two bytes at the current position and advances position by two. Set the byte order explicitly when a buffer’s data format requires a particular order. The example writes four Java char values with putChar(), flips the buffer, and reads only while at least Character.BYTES remain. This uses the known byte count to stop safely; it does not depend on a zero character as a terminator.

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ByteBufferChars {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(4 * Character.BYTES)
                .order(ByteOrder.BIG_ENDIAN);
        buffer.putChar('J');
        buffer.putChar('A');
        buffer.putChar('V');
        buffer.putChar('A');
        buffer.flip();

        StringBuilder text = new StringBuilder();
        while (buffer.remaining() >= Character.BYTES) {
            text.append(buffer.getChar());
        }
        System.out.println(text);

        buffer.rewind();
        char first = buffer.getChar();
        System.out.println("first=" + first);
    }
}

Expected output:

JAVA
first=J

A Java char is a UTF-16 code unit, and getChar() does not decode an arbitrary UTF-8 byte sequence. For text stored as UTF-8, read the bytes and decode them with a Charset such as StandardCharsets.UTF_8. For this fixed-width example, the buffer size is exactly two bytes per character, and the remaining-byte check ensures each getChar() has two bytes available. rewind() then makes the same region readable again, allowing the final read to retrieve the first character.