Java NIO Buffers: Capacity, Position, Limit, flip and compact
Understand Java NIO buffers: ByteBuffer, CharBuffer and the typed buffers, capacity, position, limit and mark, the fill-flip-drain-compact cycle, absolute versus relative access, wrap, slice, duplicate and typed views, direct buffers, charset encoding, and copying between channels.
kvi5hnuCode Sprout team member10 min readOn this page
The previous article used a MappedByteBuffer spanning a whole file. Buffers are also the everyday currency of the "new I/O" (NIO) APIs: channels read into buffers and write from them, charset encoders and decoders work on them, and network code built on channels is all about buffers. Their design, with a position and a limit that you must flip at the right moment, trips up almost everyone the first time. This article explains it.
Buffer types
A buffer is a fixed-size array of values of one primitive type, with some bookkeeping. The abstract class java.nio.Buffer has subclasses ByteBuffer, CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer. In practice, you mostly use ByteBuffer, and sometimes CharBuffer. (StringBuffer is unrelated. It's the old synchronized cousin of StringBuilder.)
You get a buffer from a static factory:
ByteBuffer buffer = ByteBuffer.allocate(8192); // a new, zeroed array
ByteBuffer wrapped = ByteBuffer.wrap(bytes); // backed by an existing array
CharBuffer chars = CharBuffer.wrap("text"); // read-only view of a CharSequence
A wrapped buffer shares the array: changes through the buffer show up in the array and vice versa.
Capacity, position, limit and mark
Every buffer has:
- a capacity, the fixed size, which never changes
- a position, the index where the next value is read or written
- a limit, the index beyond which you may not read or write
- optionally a mark, a remembered position to return to
These always satisfy 0 ≤ mark ≤ position ≤ limit ≤ capacity. remaining() returns limit − position, and hasRemaining() tests whether that's positive.
The fill-and-drain cycle
A buffer is designed for alternating cycles of filling it and then draining it:
- A new or cleared buffer has position 0 and limit = capacity. You fill it with
putcalls, or by reading from a channel. Each value advances the position. - When you're ready to consume, call
flip(). It sets the limit to the current position (the end of the data) and the position to 0. - Drain it with
getcalls, or by writing to a channel, whilehasRemaining(). - To fill again, call
compact(), which moves any unread values to the front and positions you right after them with the limit at the capacity. Or callclear()if everything was consumed: it resets the position to 0 and the limit to the capacity. It doesn't erase the data, which is simply treated as free space.

Two more resets: rewind() sets the position to 0 but keeps the limit, to read the same data again. mark() remembers the position, and reset() returns to it.
Relative and absolute access
get() and put(value) are relative: they work at the position and advance it. get(index) and put(index, value) are absolute: they work at the given index and leave the position alone. Bulk versions transfer arrays: get(byte[] dst) and put(byte[] src), and since Java 13, absolute bulk versions get(int index, byte[] dst) and put(int index, byte[] src).
A relative get with nothing remaining throws BufferUnderflowException, and a put beyond the limit throws BufferOverflowException. A bulk transfer that doesn't fit transfers nothing and throws.
ByteBuffer also reads and writes binary numbers, relative or absolute: getInt, putInt, getLong, putDouble and so on, in the byte order set with order(ByteOrder) (big-endian by default).
Views: slice, duplicate and typed buffers
Several methods create a new buffer that shares the same data but has its own position, limit and mark:
duplicate()covers the same content, often used to read a buffer without disturbing its position.slice()covers the remaining part.slice(index, length)(Java 13) covers a given region. Index 0 of the slice is the start of the region.asReadOnlyBuffer()gives a view that rejects writes.asCharBuffer(),asIntBuffer(),asLongBuffer()and the others view the remaining bytes as values of another type, honoring the byte order.
Heap and direct buffers
ByteBuffer.allocate creates a heap buffer backed by a Java byte[], which array() returns (check hasArray() first). ByteBuffer.allocateDirect creates a direct buffer whose memory lives outside the Java heap. The operating system can do I/O on it without an extra copy, so channels are faster with direct buffers. They cost more to create, though, so allocate them once and reuse them. Memory-mapped buffers are direct as well. For large or long-lived off-heap memory, Java 22's MemorySegment and Arena (Part 13) offer more control.
Characters and charsets
CharBuffer connects buffers with text. A Charset encodes a CharBuffer into a ByteBuffer and decodes the other way:
ByteBuffer bytes = StandardCharsets.UTF_8.encode(CharBuffer.wrap("Grüße")); // 7 bytes
CharBuffer chars = StandardCharsets.UTF_8.decode(bytes);
For streaming conversions, where input arrives in chunks and a multi-byte character may be split across chunk boundaries, use a CharsetDecoder and call decode(in, out, endOfInput) repeatedly. It leaves incomplete sequences in the input buffer for the next round, which is exactly what compact() is for.
Channels and buffers
A ReadableByteChannel's read(buffer) fills the remaining space and returns the number of bytes read, or -1 at the end. A WritableByteChannel's write(buffer) drains as much as it can and returns the count. Neither is guaranteed to transfer everything in one call, especially for network channels. The canonical copy loop fills, flips, writes and compacts, and keeps going until the input is exhausted and the buffer is empty:
ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
while (in.read(buffer) != -1 || buffer.position() > 0) {
buffer.flip();
out.write(buffer);
buffer.compact();
}
For files, FileChannel.transferTo(position, count, target) and transferFrom need no buffer, and on many systems the data never even passes through your process. They return the number of bytes actually transferred, which may be fewer than requested, so robust code loops: for (long pos = 0, n = in.size(); pos < n; ) pos += in.transferTo(pos, n - pos, out);
A complete example
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class Solution {
static String state(Buffer b) {
return "position=" + b.position() + " limit=" + b.limit() + " capacity=" + b.capacity()
+ " remaining=" + b.remaining();
}
public static void main(String[] args) throws IOException {
// the fill, flip, consume, compact cycle
ByteBuffer buffer = ByteBuffer.allocate(8);
System.out.println("new: " + state(buffer));
buffer.put((byte) 'J').put((byte) 'a').put((byte) 'v').put((byte) 'a');
System.out.println("after put: " + state(buffer));
buffer.flip();
System.out.println("flip: " + state(buffer));
System.out.println("get two: " + (char) buffer.get() + (char) buffer.get() + " " + state(buffer));
buffer.compact();
System.out.println("compact: " + state(buffer));
buffer.put((byte) '2').put((byte) '5');
buffer.flip();
var sb = new StringBuilder();
while (buffer.hasRemaining()) sb.append((char) buffer.get());
System.out.println("drained: " + sb + " " + state(buffer));
buffer.rewind();
System.out.println("rewind: " + state(buffer));
buffer.clear();
System.out.println("clear: " + state(buffer));
// mark and reset
ByteBuffer letters = ByteBuffer.wrap("abcdef".getBytes(StandardCharsets.US_ASCII));
letters.get();
letters.mark();
letters.get();
letters.get();
letters.reset();
System.out.println("after reset, next is: " + (char) letters.get());
// absolute access doesn't move the position
letters.position(0);
System.out.println("get(4): " + (char) letters.get(4) + ", position still " + letters.position());
// overflow and underflow
try {
ByteBuffer.allocate(2).putInt(1);
} catch (BufferOverflowException e) {
System.out.println("putInt into 2 bytes: BufferOverflowException");
}
try {
ByteBuffer.allocate(4).flip().get();
} catch (BufferUnderflowException e) {
System.out.println("get from an empty buffer: BufferUnderflowException");
}
// wrap shares the array
byte[] array = { 1, 2, 3, 4 };
ByteBuffer wrapped = ByteBuffer.wrap(array);
wrapped.put(0, (byte) 99);
System.out.println("array after put through buffer: " + Arrays.toString(array));
// views: slice, duplicate, typed views
ByteBuffer numbers = ByteBuffer.allocate(16);
numbers.putInt(10).putInt(20).putInt(30).putInt(40);
IntBuffer ints = numbers.flip().asIntBuffer();
System.out.println("asIntBuffer: " + ints.get(0) + ", " + ints.get(1) + ", " + ints.get(2) + ", " + ints.get(3));
ByteBuffer slice = numbers.slice(4, 8);
System.out.println("slice(4, 8) getInt(0): " + slice.getInt(0) + ", capacity " + slice.capacity());
slice.putInt(0, 21);
System.out.println("change through slice visible: " + numbers.getInt(4));
ByteBuffer dup = numbers.duplicate();
dup.position(12);
System.out.println("duplicate has its own position: " + dup.position() + " vs " + numbers.position());
System.out.println("read-only view: " + numbers.asReadOnlyBuffer().isReadOnly());
// CharBuffer and charsets
CharBuffer chars = CharBuffer.wrap("Grüße");
ByteBuffer encoded = StandardCharsets.UTF_8.encode(chars);
System.out.println("encoded bytes: " + encoded.remaining());
System.out.println("decoded: " + StandardCharsets.UTF_8.decode(encoded));
// copying between channels with a buffer
Path src = Files.createTempFile("src", ".txt"), dst = Files.createTempFile("dst", ".txt");
Files.writeString(src, "channels move bytes through buffers\n".repeat(100));
try (FileChannel in = FileChannel.open(src); FileChannel out = FileChannel.open(dst, StandardOpenOption.WRITE)) {
ByteBuffer buf = ByteBuffer.allocate(256);
while (in.read(buf) != -1 || buf.position() > 0) {
buf.flip();
out.write(buf);
buf.compact();
}
}
System.out.println("copy identical: " + (Files.mismatch(src, dst) == -1));
// or let the channel do it
Files.writeString(dst, "");
try (FileChannel in = FileChannel.open(src); FileChannel out = FileChannel.open(dst, StandardOpenOption.WRITE)) {
long moved = in.transferTo(0, in.size(), out);
System.out.println("transferTo moved " + moved + " bytes");
}
Files.delete(src);
Files.delete(dst);
System.out.println("direct buffer: " + ByteBuffer.allocateDirect(64).isDirect()
+ ", heap buffer has array: " + ByteBuffer.allocate(64).hasArray());
}
}
new: position=0 limit=8 capacity=8 remaining=8
after put: position=4 limit=8 capacity=8 remaining=4
flip: position=0 limit=4 capacity=8 remaining=4
get two: Ja position=2 limit=4 capacity=8 remaining=2
compact: position=2 limit=8 capacity=8 remaining=6
drained: va25 position=4 limit=4 capacity=8 remaining=0
rewind: position=0 limit=4 capacity=8 remaining=4
clear: position=0 limit=8 capacity=8 remaining=8
after reset, next is: b
get(4): e, position still 0
putInt into 2 bytes: BufferOverflowException
get from an empty buffer: BufferUnderflowException
array after put through buffer: [99, 2, 3, 4]
asIntBuffer: 10, 20, 30, 40
slice(4, 8) getInt(0): 20, capacity 8
change through slice visible: 21
duplicate has its own position: 12 vs 0
read-only view: true
encoded bytes: 7
decoded: Grüße
copy identical: true
transferTo moved 3600 bytes
direct buffer: true, heap buffer has array: true
Common questions
How do I get the bytes or a String out of a ByteBuffer?
After flip(), copy the remaining bytes: byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes);. For text, decode instead: StandardCharsets.UTF_8.decode(buffer).toString(). Calling array() returns the whole backing array, ignoring position and limit, and fails for direct buffers.
What is the difference between flip() and rewind()?
flip() sets the limit to the current position and then the position to 0: "I'm done writing, now read what I wrote". rewind() sets only the position to 0 and keeps the limit: "read the same data again".
Should I always use direct buffers?
No. Direct buffers pay off for channel I/O with buffers that live long and are reused. They are slower to allocate, and their memory is outside the heap, limited by -XX:MaxDirectMemorySize. Exceeding it throws OutOfMemoryError: Direct buffer memory. For short-lived buffers and for code that mostly works with arrays, heap buffers are simpler and fast.
Is a ByteBuffer thread-safe?
No. Position, limit and mark are unsynchronized state. Give each thread its own buffer, or its own duplicate() view and use absolute get and put methods if the threads share the content.
Do I need buffers at all if I only use streams?
Not directly. Buffers matter when you use channels (files, sockets, memory mapping), charset encoders and decoders, or binary parsing with getInt and friends. Classic stream code can live without them.
API reference
java.nio.Buffer
| Method | Description |
|---|---|
int capacity(), int position(), int limit(), int remaining(), boolean hasRemaining() | the buffer's state |
Buffer position(int newPosition), Buffer limit(int newLimit) | set position or limit |
Buffer flip() | limit = position, position = 0: switch from filling to draining |
Buffer clear() | position = 0, limit = capacity: ready to fill |
Buffer rewind() | position = 0, limit unchanged: read again |
Buffer mark(), Buffer reset() | remember the position, and return to it |
boolean isDirect(), isReadOnly(), hasArray() | buffer properties |
java.nio.ByteBuffer
| Method | Description |
|---|---|
static ByteBuffer allocate(int capacity), allocateDirect(int capacity) | new heap or direct buffer |
static ByteBuffer wrap(byte[] array) | a buffer backed by array |
byte get(), get(int index), ByteBuffer put(byte b), put(int index, byte b) | relative and absolute access |
ByteBuffer get(byte[] dst), put(byte[] src), get(int index, byte[] dst) (Java 13), put(int index, byte[] src) (Java 13) | bulk transfers |
getInt(), putInt(int), getInt(int index), putInt(int index, int) and likewise for Short, Char, Long, Float, Double | binary numbers |
ByteBuffer compact() | moves unread bytes to the front and prepares to fill |
ByteBuffer slice(), slice(int index, int length) (Java 13), duplicate(), asReadOnlyBuffer() | views sharing the content |
CharBuffer asCharBuffer(), IntBuffer asIntBuffer() and other typed views | views of the remaining bytes as another type |
ByteBuffer order(ByteOrder order), ByteOrder order() | byte order for multi-byte values |
byte[] array() | the backing array of a heap buffer |
java.nio.CharBuffer
| Method | Description |
|---|---|
static CharBuffer wrap(CharSequence csq), wrap(char[] array) | a buffer over characters |
char get(), CharBuffer put(char c), put(String src) | character access |
java.nio.channels.ReadableByteChannel, WritableByteChannel and FileChannel
| Method | Description |
|---|---|
int read(ByteBuffer dst) | fills the remaining space; returns the count, or -1 at the end |
int write(ByteBuffer src) | drains as much as possible; returns the count |
long transferTo(long position, long count, WritableByteChannel target), transferFrom(...) | FileChannel: direct transfer between channels |
Summary
- Buffers are fixed-size arrays of one primitive type with a capacity, position, limit and optional mark.
- Fill with
putor channel reads,flip(), drain withgetor channel writes, thencompact()orclear()before filling again. Forgettingflipis the classic bug. - Relative access moves the position, and absolute access with an index doesn't.
wrap,slice,duplicateand the typed views share data but have their own position and limit.- Direct buffers speed up channel I/O.
Charset.encodeanddecodeconvert betweenCharBufferandByteBuffer. - Channel reads and writes may transfer partially, so loop until done;
transferTofor files needs no buffer but can also transfer partially.
Practice Questions
A buffer of capacity 10 has 6 bytes put into it. What are position and limit before and after flip()?
Before: position 6, limit 10. After flip(): position 0, limit 6, so exactly the 6 bytes written can be read.
You fill a buffer from a channel and immediately call out.write(buffer), but nothing is written. Why?
The buffer wasn't flipped. Its position is at the end of the data and its limit at the capacity, so write sends the unused space after the data, or nothing if the buffer was full. Call buffer.flip() before writing.
When should you call compact() instead of clear()?
When some data hasn't been consumed yet, for example because a channel write was partial or a multi-byte value was cut off. compact() keeps the unread bytes at the front, while clear() would discard them.
What does buffer.get(5) do to the position, compared with buffer.get()?
get(5) reads the value at index 5 and leaves the position unchanged. get() reads at the current position and advances it by one.
Why does the copy loop continue while buffer.position() > 0 even after read returns -1?
The final read may leave data in the buffer that the last write didn't fully send, which is common with non-blocking or network channels. The loop must keep flipping and writing until the buffer is empty, or that data is lost.
Previous: Java Memory-Mapped Files: FileChannel.map and Performance
Next: Java File Locking: FileLock, Shared and Exclusive Locks
Related reading
- Java Memory-Mapped Files: FileChannel.map and Performance
- Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor
- Java Files: Copying, Moving, Deleting and Reading File Attributes
- Java Files: Reading, Writing and Creating Files and Directories
- Java NIO Path: Creating, Resolving, Relativizing and Normalizing Paths

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.