The ByteBuffer is the most generic and commonly used NIO buffer class.

How to create a ByteBuffer

As mentioned in our discussion of buffer layout, a buffer class is generally "wrapped" around an underlying byte array. Modifying or reading from the buffer then accesses the underlying array and vice versa. If we have a byte array, we can create a buffer object around it by calling the ByteBuffer.wrap() method:

byte[] ba = ...
ByteBuffer buff = ByteArray.wrap(ba);

A less commonly used variant of wrap() allows us to wrap around a part of an array.

If we just want to create a brand new byte array and buffer object all in one go, we can call the convenience method ByteBuffer.allocate() method, passing the required buffer and array size (in bytes):

ByteBuffer buff = ByteArray.allocate(100);

Position and limit of the buffer

Recall from our overview of the layout of a buffer that a ByteBuffer (and other types of buffer) has a current position and limit. When a new buffer is created:

In other words, a newly created buffer is set up to sequentially read or write over the entire buffer from start to finish, unless we manually change the position and/or limit.

Reading and writing data to a ByteBuffer and using a ByteBuffer to convert numbers in Java

On the next page, we'll look at the methods to read and write data to the ByteBuffer. By using the different get and put methods on a ByteBuffer, we can convert between raw bytes and different number types.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.