What is the difference between limit and capacity in ByteBuffer?

Its best illustrated HERE in this article: They are mainly different depending on the mode,

  • In Write Mode, Capacity and Limit are Same.
  • But in Read mode Limit means the limit of how much data you can read from the data

enter image description here


ByteBuffer does not have a length() method. Instead it has a several length-like concepts:

mark <= position <= limit <= capacity

capacity = Inside the ByteBuffer, there is a backing byte[] or something that behaves much like one. The capacity is its size. The capacity indexes the first slot past the end of the buffer.

limit = When filling the buffer, the limit is the same as the capacity. When emptying the buffer, it is one past the last filled byte in the buffer.

position = When filling the buffer, the position points just past the last byte filled in the buffer. When emptying the buffer, the position points just past the last byte written from the buffer.

mark The mark is an optional bookmark to let you record an interesting spot in the ByteBuffer that you want to return to later. When you take a mark() it records current position, and when you call reset() it restores that position.

I hope this helps. Also an example can be seen over here: http://mindprod.com/jgloss/bytebuffer.html

Source: Oracle Java Buffer reference - See 'Invariants' section.