There are some problems in your code and in your approach to that task:
put()
methods without the explicit index will update the buffer position. After four put operations the buffer position is 4.
asCharBuffer()
reuses the contents of the original buffer, starting from the current position in the origin buffer, which is 4 and the original buffer has no actual data starting from that position.
flip()
is indeed the proper action before trying to perform get
operations after a sequence of put
operations, but:
- In Java,
char
is a two-byte value, meaning that your original 4-byte buffer will be interpreted as a 2-char buffer, for example the value of the first char will be ( char ) ( ( ( ( byte ) 'H' ) << 8 ) + ( byte ) 'e' )
.
Other that this, the ByteBuffer
behaves exactly as expected and documented in its javadoc.
An example that fixes the coding problems:
ByteBuffer byteBuffer = ByteBuffer.allocate( 100 );
byteBuffer
// explicitly converting each char into 2 bytes
.put( ( byte ) ( 'H' >>> 8 ) ).put( ( byte ) 'H' )
.put( ( byte ) ( 'e' >>> 8 ) ).put( ( byte ) 'e' )
.put( ( byte ) ( 'l' >>> 8 ) ).put( ( byte ) 'l' )
.put( ( byte ) ( 'l' >>> 8 ) ).put( ( byte ) 'l' )
.put( ( byte ) ( 'o' >>> 8 ) ).put( ( byte ) 'o' );
// flipping the buffer to be able access the current content via get operations
byteBuffer.flip();
// reinterpreting the byte sequence as a char sequence
CharBuffer charBuffer = byteBuffer.asCharBuffer();
System.out.println( charBuffer.toString() );