CharBuffer array() method in Java
The array() method of java.nio.CharBuffer Class is used to return the char array that backs this buffer. Any modifications done to this buffer’s content will cause the returned array’s content also to be modified, and vice versa. hasArray() method is invoked before invoking this method in order to ensure that this buffer has an accessible backing array.
Syntax:
public final char[] array()
Return Value: This method returns the array that backs this buffer.
Throws: This method throws the ReadOnlyBufferException(If this buffer is backed by an array but is read-only)
Below program illustrates the array() 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' );
cb.rewind();
char [] cbb = cb.array();
System.out.println( "CharBuffer: "
+ Arrays.toString(cbb));
}
catch (IllegalArgumentException e) {
System.out.println( "IllegalArgumentException catched" );
}
catch (ReadOnlyBufferException e) {
System.out.println( "ReadOnlyBufferException catched" );
}
}
}
|
Output:
CharBuffer: [a, , b, , , , , , , ]
Example 2:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity1 = 10 ;
int capacity2 = 5 ;
try {
CharBuffer cb = CharBuffer.allocate(capacity1);
cb.put( 'a' );
cb.put( 2 , 'b' );
cb.put( 3 , 'c' );
cb.rewind();
System.out.println( "CharBuffer cb: "
+ Arrays.toString(cb.array()));
CharBuffer cb1 = CharBuffer.allocate(capacity2);
cb1.put( 1 , 'd' );
cb1.put( 2 , 'e' );
cb1.rewind();
System.out.println( "\nCharBuffer cb1: "
+ Arrays.toString(cb1.array()));
CharBuffer readOnlycb = cb.asReadOnlyBuffer();
System.out.print( "\nReadOnlyBuffer CharBuffer: " );
while (readOnlycb.hasRemaining())
System.out.print(readOnlycb.get() + ", " );
System.out.println( "\n\nTrying to get the array"
+ " from ReadOnlycb for editing" );
char [] cbarr = readOnlycb.array();
}
catch (IllegalArgumentException e) {
System.out.println( "IllegalArgumentException catched" );
}
catch (ReadOnlyBufferException e) {
System.out.println( "Exception thrown: " + e);
}
}
}
|
Output:
CharBuffer cb: [a,, b, c,,,,,, ]
CharBuffer cb1: [, d, e,, ]
ReadOnlyBuffer CharBuffer: a,, b, c,,,,,,,
Trying to get the array from ReadOnlycb for editing
Exception thrown: java.nio.ReadOnlyBufferException
Last Updated :
19 Sep, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...