CharBuffer hasArray() method in Java

Last Updated : 15 Oct 2026

The hasArray() method of the Java CharBuffer class checks whether a buffer has an accessible backing character array. It returns true if the buffer has an accessible backing array and false otherwise.

In this chapter, you will learn about the hasArray() method of the CharBuffer class, its syntax, return value, and examples demonstrating its behavior with writable and read-only buffers.

What is the hasArray() Method in Java?

The hasArray() method belongs to the java.nio.CharBuffer class. It determines whether the buffer is backed by an accessible character array.

If the method returns true, the backing array can be accessed using the array() and arrayOffset() methods. If the method returns false, the buffer does not provide access to a backing array.

A read-only CharBuffer returns false from hasArray(), even if its underlying storage is backed by an array.

Syntax of the hasArray() Method

The following syntax demonstrates the declaration of the hasArray() method.

public final boolean hasArray()

Return Value

The hasArray() method returns a boolean value.

  • true: The buffer has an accessible backing array.
  • false: The buffer does not have an accessible backing array, or it is read-only.

Examples of the hasArray() Method in Java

The following examples demonstrate how the hasArray() method behaves with a writable CharBuffer and a read-only CharBuffer.

Example 1: Checking the Backing Array of a CharBuffer

In the following example, we create a CharBuffer with a capacity of 12 characters, insert characters at specific positions, and use the hasArray() method to check whether the buffer has an accessible backing array.

Output:

 
CharBuffer chabuff is backed by the array   

Example 2: Checking the Backing Array of a Read-Only CharBuffer

In the following example, we create a writable CharBuffer, insert characters, and create a read-only view using asReadOnlyBuffer(). We then call the hasArray() method to check whether the read-only buffer provides access to its backing array.

Output:

 
CharBuffer charbuff is not backed by the any array   

Important Points

  • The hasArray() method belongs to the java.nio.CharBuffer class.
  • The method returns a boolean value.
  • A writable buffer created using CharBuffer.allocate() has an accessible backing array.
  • A read-only CharBuffer returns false from hasArray().
  • The array() and arrayOffset() methods should be used only when the buffer has an accessible backing array.
  • The hasArray() method does not modify the buffer's position, limit, or contents.