The java.nio.ByteBuffer class provides the asCharBuffer()
method to create a char
view-buffer of the underlying byte array of the original buffer.
A view-buffer
is another buffer that is backed by the same array as the corresponding ByteBuffer
object. Any changes made to the original ByteBuffer
or the corresponding view-buffer
are visible in both places. However, the position
, limit
, and mark
of the two buffers are independent of each other.
The position
of the new buffer is zero. It defines the byte index from which the next value will be read from the buffer.
The capacity
and limit
of the new buffer are given by the number of remaining bytes divided by two. The capacity
is the index of the last byte in the buffer. The limit
is the index of the first index that should not be read from the buffer.
The mark
will be undefined. This marks the current index of the buffer so that we can return to it when the reset()
method is called.
The new buffer will only be direct if this buffer is also direct.
The new buffer is only read-only if this buffer is also read-only.
public abstract CharBuffer asCharBuffer()
asCharBuffer()
does not take any arguments.
asCharBuffer()
returns a new CharBuffer
view.
import java.nio.*;import java.util.*;class main {public static void main( String args[] ) {ByteBuffer buffer = ByteBuffer.allocate(8);CharBuffer charBuff = buffer.asCharBuffer();charBuff.put('a');charBuff.put('b');charBuff.put('c');charBuff.put('d');charBuff.rewind();System.out.print("using CharBuffer: ");for(int i = buffer.position(); i < buffer.limit()/2; i++){System.out.print(buffer.getChar() + " ");}System.out.print("\nusing ByteBuffer: ");buffer.rewind();buffer.put(5,(byte)'X');for(int i = buffer.position(); i < buffer.limit()/2; i++){System.out.print(buffer.getChar() + " ");}}}
In the code above, we create a ByteBuffer
called buffer
and allocate it with a capacity of bytes. Next, we create a view buffer using the asCharBuffer()
method and call it charBuff
. This allows us to put values of type char
in the buffer.
We use the put()
method of the CharBuffer
object to write values into the buffer as follows:
charBuff.put()
The for
loop in line prints the contents of the byte array using CharBuffer
. In this loop, we start from the index given by position()
all the way through the index at limit() / 2
. We need to divide by because the ByteBuffer
is indexed by bytes and each char
value takes two bytes of memory.
In line , we put the character X
in the buffer using the put()
method of the ByteBuffer
object instead of the CharBuffer
object. However, the changes are also visible in the buffer
object.