difference between bytebuffer.flip() and bytebuffer.rewind()

Rollerball picture Rollerball · May 9, 2013 · Viewed 17.1k times · Source

I am aware that flip() set the current buffer position to 0 and set the limit to the previous buffer position whereas rewind() just set the current buffer position to 0.

In the following code, either I use rewind() or flip() i get the same result.

byte b = 127;
bb.put(b);
bb.rewind();//or flip();

System.out.println(bb.get());
bb.rewind();// or flip();
System.out.println(bb.get());

Could you provide me with a real example where the difference of these 2 methods really matters? Thanks in advance.

Answer

lxy picture lxy · Jul 4, 2017

From the source code, they are very similar. You can see the follow:

public final Buffer flip() {
    limit = position;
    position = 0;
    mark = -1;
    return this;
}

public final Buffer rewind() {
    position = 0;
    mark = -1;
    return this;
}

So the difference is the flip set the limit to the position, while rewind not. Consider you have allocated a buffer with 8 bytes, you have filled the buffer with 4 bytes, then the position is set to 3, just show as follow:

    [ 1  1  1  1  0  0  0  0]
               |           |
flip           limit       |
rewind                     limit

So rewind just used limit has set appropriately.