Share on Google+Share on Google+

Write a byte into byte buffer at given index.

In this tutorial you will see how to write a byte into byte buffer at given index.

Write a byte into byte buffer at given index.

 In this tutorial, we will see how to write the given byte into byte buffer at the given 

ByteBuffer API:

The java.nio.ByteBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static ByteBuffer allocate(int capacity)  The allocate(..)method allocate a new byte buffer.
abstract ByteBuffer putChar(int index, byte b) The putChar(..) method write two byte containing the given character value into associated buffer.
abstract byte get() The get() method read byte from current position and increment position.


import java.nio.*;
import java.nio.ByteBuffer;
public class PutAtIndex {
  public static final int capacity = 9;
  public static void main(String[] args) {
    try {
     ByteBuffer byteBuf = ByteBuffer.allocate(capacity);
      int i = 3;
      System.out.println("Write value at index : " + i);
      byteBuf.putChar(i, 'B');
System.out.print("\nRead value from index " + i + " : ");
      while (byteBuf.hasRemaining()) {
    catch (Exception e) {


C:\>java PutAtIndex
Write value at index  : 3
Read value from index 3 : B

Download this code



Posted on: July 27, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null