Share on Google+Share on Google+

Use of getChar method of ByteBuffer Class in java.

In this tutorial you will see the use of getChar method of ByteBuffer Class in java.

Use of getChar method of ByteBuffer Class in java.

In this tutorial, we will discuss the use of getChar() method of ByteBuffer class to fetch the character.

        In the given example, we will see how to get characters from byte buffer.
The put() method of ByteBuffer class write bytes into buffer, and the getChar() method of 
ByteBuffer class returns the character at current position and increment the position by two bytes.

About ByteBuffer API:

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

Return type Method Description
abstract CharBuffer asCharBuffer()    The asCharBuffer() method create a view of associated buffer as char buffer.
ByteBuffer put() The put() method write bytes into associated buffer.
abstract char getChar() The getChar(.) method returns character from byte buffer. 


import java.nio.*;
import java.nio.ByteBuffer;

public class GetChBuffer {
public static final int size = 1024;
public static void main(String[] argsthrows Exception{
    ByteBuffer bytebuf = ByteBuffer.allocate(size);
    bytebuf.asCharBuffer().put("Bharat Singh");
    char c;
  System.out.print("Character available in buffer : ");
    while ((c = bytebuf.getChar()) != 0) {


C:\>java GetChBuffer
Character available in buffer : Bharat Singh

Download this code



Posted on: July 26, 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.