What is the CharBuffer arrayOffset() method in Java?
The java.nio.CharBuffer is a class we can use to store a buffer of characters. The arrayOffset() method of this class returns the offset of the first element of the buffer inside the buffer’s backing array.
Declaration
The CharBuffer.arrayOffset() method is declared as follows:
buff.arrayOffset()
buff: TheCharBufferwhose first element offset is required.
Return value
The CharBuffer.arrayOffest() method returns an int that is the offset of the first element of buff.
- If the buffer is not backed by an accessible array,
UnsupportedOperationExceptionis thrown.- If the buffer is backed by an array but the array is read-only,
ReadOnlyBufferExceptionis thrown.
Code
Example 1
Consider the code snippet below, which demonstrates the use of the CharBuffer.arrayOffset() method.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 5;try {CharBuffer buff1 = CharBuffer.allocate(n1);buff1.put('a');buff1.put('m');System.out.println("buff1: " + Arrays.toString(buff1.array()));int foo = buff1.arrayOffset();System.out.println("\nbuff1 array offset: " + foo);} catch (IllegalArgumentException e) {System.out.println("Error!!! IllegalArgumentException");} catch (ReadOnlyBufferException e) {System.out.println("Error!!! ReadOnlyBufferException");} catch (UnsupportedOperationException e) {System.out.println("Error!!! UnsupportedOperationException");}}}
Explanation
- An
CharBufferbuff1is declared in line 7 with capacityn1 = 5. - Two elements are added to
buff1using theput()method in lines 8-9. - The
CharBuffer.arrayOffset()method is used in line 12 to get the offset of first element ofbuff1inside its backing array.
Example 2
Consider another example of the CharBuffer.arrayOffset() method in which ReadOnlyBufferException is thrown.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 5;try {CharBuffer buff1 = CharBuffer.allocate(n1);buff1.put('a');buff1.put('m');System.out.println("buff1: " + Arrays.toString(buff1.array()));CharBuffer buff2 = buff1.asReadOnlyBuffer();int foo = buff2.arrayOffset();System.out.println("\nbuff2 array offset: " + foo);} catch (IllegalArgumentException e) {System.out.println("Error!!! IllegalArgumentException");} catch (ReadOnlyBufferException e) {System.out.println("Error!!! ReadOnlyBufferException");} catch (UnsupportedOperationException e) {System.out.println("Error!!! UnsupportedOperationException");}}}
Explanation
- An
CharBufferbuff1is declared in line 7 with capacityn1 = 5. - Two elements are added to
buff1using theput()method in lines 8-9. - An
CharBufferbuff2is declared in line 12 that is the read-only copy ofbuff1. - The
CharBuffer.arrayOffset()method is used in line 14 to get the offset of first element ofbuff2inside its backing array. TheReadOnlyBufferExceptionis thrown becausebuff2is read-only.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved