Java Language Basic Usage - Write Data to the Buffer


Example

Given a ByteBuffer instance one can write primitive-type data to it using relative and absolute put. The striking difference is that putting data using the relative method keeps track of the index the data is inserted at for you, while the absolute method always requires giving an index to put the data at.

Both methods allow "chaining" calls. Given a sufficiently sized buffer one can accordingly do the following:

buffer.putInt(0xCAFEBABE).putChar('c').putFloat(0.25).putLong(0xDEADBEEFCAFEBABE);

which is equivalent to:

buffer.putInt(0xCAFEBABE);
buffer.putChar('c');
buffer.putFloat(0.25);
buffer.putLong(0xDEADBEEFCAFEBABE);

Do note that the method operating on bytes is not named specially. Additionally note that it's also valid to pass both a ByteBuffer and a byte[] to put. Other than that, all primitive types have specialized put-methods.

An additional note: The index given when using absolute put* is always counted in bytes.