The arrayOffset() method of java.nio.CharBuffer class is used to return the offset within the buffer’s backing array of the first element of the buffer. It means that if this buffer is backed by an array, then buffer position p corresponds to array index p + arrayOffset().
Inorder to check whether this buffer has a backing array, hasArray() method can be used. It ensures that this buffer has an accessible backing array.
Syntax:
public final int arrayOffset()
Return Value: This method returns the offset within this buffer’s array of the first element of the buffer.
Exception: This method throws ReadOnlyBufferException if this buffer is backed by an array but is read-only
Below program illustrates the arrayOffset() method.
Example 1:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 10 ;
try {
CharBuffer cb = CharBuffer.allocate(capacity);
cb.put( 'a' );
cb.put( 2 , 'b' );
System.out.println( "CharBuffer: "
+ Arrays.toString(cb.array()));
System.out.println( "arrayOffset: "
+ cb.arrayOffset());
}
catch (IllegalArgumentException e) {
System.out.println( "IllegalArgumentException catched" );
}
catch (ReadOnlyBufferException e) {
System.out.println( "Exception throws" + e);
}
}
}
|
Output:
CharBuffer: [a, , b, , , , , , , ]
arrayOffset: 0
Example 2: To demonstrate ReadOnlyBufferException
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 10 ;
try {
CharBuffer fb = CharBuffer.allocate(capacity);
fb.put( 'a' );
fb.put( 2 , 'b' );
fb.rewind();
CharBuffer cb1 = fb.asReadOnlyBuffer();
System.out.print( "Read only buffer : " );
while (cb1.hasRemaining())
System.out.print(cb1.get() + ", " );
System.out.println( "" );
System.out.println( "\nTry to print the array offset"
+ " of read only buffer" );
System.out.println( "arrayOffset: " + cb1.arrayOffset());
}
catch (IllegalArgumentException e) {
System.out.println( "Exception throws: " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println( "Exception throws: " + e);
}
}
}
|
Output:
Read only buffer : a, , b, , , , , , , ,
Try to print the array offset of read only buffer
Exception throws: java.nio.ReadOnlyBufferException
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Sep, 2018
Like Article
Save Article
Vote for difficulty