The limit() method of java. nio. ByteBuffer Class is used to set this buffer's limit. If the position is larger than the new limit then it is set to the new limit. If the mark is defined and larger than the new limit then it is discarded.
There are several differences between a byte array and ByteBuffer class in Java, but the most important of them is that bytes from byte array always reside in Java heap space, but bytes in a ByteBuffer may potentially reside outside of the Java heap in case of direct byte buffer and memory mapped files.
After you've written to the ByteBuffer, the number of bytes you've written can be found with the position() method. If you then flip() the buffer, the number of bytes in the buffer can be found with the limit() or remaining() methods.
ByteBuffer holds a sequence of integer values to be used in an I/O operation. The ByteBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get method that read single bytes. Absolute and relative put methods that write single bytes.
Its best illustrated HERE in this article: They are mainly different depending on the mode,
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.
capacity is buffer's max size which is determined on buffer creation and never changes, limit is the actual size which can be changed. You cannot read or write beyond limit.
ByteBuffer b= ByteBuffer.allocate(10); // capacity = 10, limit = 10
b.limit(1); //set limit to 1
b.put((byte)1);
b.put((byte)1); //causes java.nio.BufferOverflowException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With