Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Explain ByteBuffer position, limit, capacity and flip(). Why do people get empty results after writing data into a buffer and then reading from it?

A ByteBuffer has a fixed capacity, a position that marks the next index to read or write, and a limit that marks the end of the data we may use. After we write data in, position sits at the end of that data; flip() sets the limit to that position and moves position back to 0, so reading covers exactly what was written. If we forget flip(), reading starts at the end of the data, finds nothing between position and limit, and returns an empty result.

Why this question is asked

ByteBuffer is the basic container of Java NIO: every channel read and write goes through one, and so does a lot of networking code in libraries such as Netty. Its single-cursor design confuses almost everyone the first time, and the confusion produces a very specific bug: we write bytes into a buffer, hand it to a channel or read it back, and get nothing. Interviewers ask this to check that we can reason about the buffer's state rather than copy flip() calls by habit. In this answer, we will recap the three indexes, trace them through a write and a read, reproduce the empty result, and finish with clear(), compact() and rewind(), each with its state.

1A Quick Recap of the Three Indexes

A ByteBuffer is a fixed-size block of bytes plus a few numbers that describe which part of it is in use. capacity is the total size, set when the buffer is created, and it never changes. position is the index where the next get() reads or the next put() writes; every relative get or put moves it forward by the number of bytes handled. limit is the first index we must not touch; when we write, it is normally the capacity, and when we read, it marks the end of the valid data. The rule always holds that 0 <= position <= limit <= capacity, and remaining() is limit minus position.

The important design choice is that there is only one position, used for both reading and writing. Unlike a pair of InputStream and OutputStream, a buffer does not keep separate read and write cursors. So between filling a buffer and draining it, we have to tell it that we are switching direction. That is what flip() is for.

2Tracing a Write, a flip() and a Read

Let us follow the indexes through a small buffer of 8 bytes.

Java
ByteBuffer buf = ByteBuffer.allocate(8);
System.out.println(buf); // java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]
buf.put((byte) 'h').put((byte) 'i').put((byte) '!');
System.out.println(buf); // java.nio.HeapByteBuffer[pos=3 lim=8 cap=8]
buf.flip(); // limit = position (3), position = 0
System.out.println(buf); // java.nio.HeapByteBuffer[pos=0 lim=3 cap=8]
while (buf.hasRemaining()) System.out.print((char) buf.get()); // hi!
System.out.println(buf); // java.nio.HeapByteBuffer[pos=3 lim=3 cap=8]
Buffer state at each step (capacity 8)
AfterpositionlimitReadable or writable range
allocate(8)08write into 0..7
three put() calls38data in 0..2, can write 3..7
flip()03read 0..2
three get() calls33nothing left to read
clear()08write into 0..7 again

Notice what flip() does and why. After the three puts, position is 3, which is exactly the length of the data we wrote. flip() remembers that length by copying it into limit, then rewinds position to 0. Reading now runs from 0 up to the limit of 3, so we read the three bytes we wrote and stop, never touching the five unused bytes at the end.

3Why Forgetting flip() Gives Empty Results

Now suppose we forget the flip and go straight from writing to reading, or to handing the buffer to a channel.

Java
ByteBuffer buf = ByteBuffer.allocate(8);
buf.put("hi!".getBytes(StandardCharsets.US_ASCII)); // pos=3 lim=8
System.out.println(buf.remaining()); // 5 (the empty part, not the data)
System.out.println(buf.get()); // 0 (byte at index 3, never written)
ByteBuffer empty = ByteBuffer.allocate(8);
empty.put("hi!".getBytes(StandardCharsets.US_ASCII));
channel.write(empty); // writes the 5 zero bytes from index 3, not "hi!"
ByteBuffer in = ByteBuffer.allocate(1024);
int n = channel.read(in); // n = 200, pos=200 lim=1024
String s = StandardCharsets.UTF_8.decode(in).toString();
System.out.println(s.length()); // 824 (decoded the empty tail)

The reason is the single position. After writing, position points just past our data, so any read starts there, in the unused space. Depending on the call we get zero bytes, zeros from the unused area, or, when the buffer was exactly full, nothing at all because position equals limit. The channel examples show the same mistake from both directions: a buffer filled by our code and then written to a channel needs flip() first, and a buffer filled by channel.read() and then decoded or parsed needs flip() first too. Calling flip() between filling and draining fixes all of them.

4Clear(), compact() and rewind(): Getting Back to Writing

After reading, we usually want to fill the buffer again. clear() sets position to 0 and limit to capacity. It does not erase the bytes; it just marks the whole buffer as writable, which is right when everything has been consumed.

compact() is for the case where we read only part of the data, for example when parsing messages and the last message is incomplete. It copies the unread bytes, those between position and limit, to the start of the buffer, then sets position just after them and limit to capacity, so the next channel read appends to the leftover bytes instead of overwriting them. Using clear() here would silently drop the partial message.

rewind() sets position back to 0 and leaves limit as it is. We use it to read the same data again, for example to compute a checksum and then send the bytes.

Java
// Typical loop: read from one channel, write to another
ByteBuffer buf = ByteBuffer.allocate(8192);
while (in.read(buf) != -1 || buf.position() > 0) {
buf.flip(); // switch to draining: read what was just filled
out.write(buf); // may write only part of it
buf.compact(); // keep any unwritten bytes, switch back to filling
}

This loop is the canonical pattern and shows all three ideas together: fill, flip, drain, compact, and fill again. The extra position check makes sure bytes left over at the end of the input are still written.

5Follow-up questions

What is the difference between flip() and rewind()?

Both set position to 0, but flip() also sets limit to the old position, which is what turns a buffer we just wrote into a buffer we can read. rewind() keeps the limit, so it is for re-reading data that is already set up for reading. Calling flip() twice in a row is a bug, because the second call sets limit to 0 and the buffer looks empty.

Do absolute get(index) and put(index, b) move the position?

No. The absolute forms read or write at a given index and leave position untouched; only the relative forms move it. That makes absolute access useful for patching a length header after writing a message body, but mixing the two styles carelessly is another source of confusing buffer states.

6Conclusion

In this answer, we saw that a ByteBuffer has a fixed capacity, a single position used for both reading and writing, and a limit that bounds the usable data. flip() switches from filling to draining by setting the limit to the end of the data and the position to 0; without it, reads start after the data and find nothing. clear() prepares for writing again when everything was read, compact() keeps unread bytes, and rewind() lets us read the same data again.

What to say in the interviewAbout 90 seconds aloud

Open with

A ByteBuffer has three numbers. Capacity is the fixed size. Position is where the next relative get or put happens, and it moves forward with each one.

Then, if they want more

Limit is the first index we are not allowed to use. The key thing is there is only one position for both writing and reading. So after I put three bytes into an 8-byte buffer, position is 3 and limit is still 8.

If I read now, I start at index 3, in the empty part, and remaining is 5 bytes of nothing.

That is the classic empty result, and it happens in both directions: filling a buffer and writing it to a channel, or reading from a channel and then decoding it, without flipping in between. flip sets limit to the current position, which is the length of the data, and position back to 0, so reading covers exactly what I wrote.

After reading, clear resets position to 0 and limit to capacity for writing again; it does not erase anything. If I only consumed part of the data, like a half-received message, I use compact, which moves the unread bytes to the front and lets the next read append after them.

And rewind sets position to 0 but keeps the limit, for reading the same data again. The standard loop is fill, flip, drain, compact.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain ByteBuffer position, limit, capacity and flip(). Why do people get empty results...": https://scrivio-interview-library.netlify.app/java/io-and-nio/1c760b83b4/