What is the java.nio.CharBuffer class in Java?

Overview

The java.nio class represents New IONIO stands for non-blocking I/O, an alternative to the regular IO API in Java. It allows you to do non-blocking IO using channels and buffers.

A channel is like a regular stream, but unlike a streamusually only one-way, a single channel can be used to read and write data. Channels can be written asynchronously.

Channels usually write to and read from buffers. A buffer is a block of memory where data can be written and be read later on.

It is a finite sequence of elements of any particular primitive type.


Even though java.nio supports non-blocking IO, it is NOT an asynchronous class because some operations are actually blocking, e.g., file IO.

Buffers have three essential properties.

  • capacity: Capacity refers to the total size of the buffer. It always remains constant.

  • limit: The limit determines how many elements you can read or write from the buffer.

  • position: The position determines the index from which to initiate reading or writing a buffer.

The CharBuffer class

This class describes four kinds of operations upon char buffers:

  • Relative and absolute get and put methods that read and write single chars.

  • Relative bulk get methods give contiguous chars sequences from this buffer into an array.

  • Relative bulk put methods give contiguous sequences of chars from a char array, a string, or another char buffer into this buffer.

  • The class gives methods for duplicating, compacting, and slicing a char buffer.

Class methods

Method name Description
allocate(int capacity) The allocate method allocates a new char buffer.
append(char c) The append method appends the specified char to the buffer.
compact() The compact method compacts the buffer.
array() The array method returns the char array that backups up the buffer.
arrayOffset() The arrayOffset method returns the offset within this buffer’s backing array of the first element of the buffer.

A complete list of class methods can be found here.

Code

The code here shows an example of how to create a CharBuffer object:

import java.nio.*;
import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
int CAPACITY = 10;
char [] charArray = {'a', 'b', 'c'};
CharBuffer buffer1 = CharBuffer.allocate(CAPACITY);
CharBuffer buffer2 = CharBuffer.wrap(charArray);
buff1.put(0, 'd');
System.out.println(Arrays.toString(buffer1.array()));
System.out.println(Arrays.toString(buffer2.array()));
}
}

Explanation

  • buffer1 is created using the allocate() method.

  • buffer2 is made by wrapping an already existing char array called charArray into a buffer using the wrap method.

  • The .array method returns the char array that backs up the buffer.