java.nio.CharBuffer
is a class that can be used to store a buffer of characters. The put()
method of the java.nio.CharBuffer
class is used to write a character to a buffer. The CharBuffer.put()
method writes the character at the current
The CharBuffer.put()
method can be declared as:
buff1.put(x);
buff1
: The CharBuffer
in which the character x
will be written.x
: The character that will be written to buff1
.The CharBuffer.put()
method returns the CharBuffer
buff1
after writing the character x
to it.
Note:
- If the position of
buff1
is not less than theof limit The first index of the buffer that should not be read or written buff1
, theBufferOverflowException
is thrown.- If
buff1
is read-only, theReadOnlyBufferException
is thrown.
Consider the code snippet below, which demonstrates the use of the CharBuffer.put()
method.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 5;int n2 = 4;try {CharBuffer buff1 = CharBuffer.allocate(n1);buff1.put('a');buff1.put('c');System.out.println("buff1: " + Arrays.toString(buff1.array()));System.out.println("position: " + buff1.position());} catch (IllegalArgumentException e) {System.out.println("Error!!! IllegalArgumentException");} catch (ReadOnlyBufferException e) {System.out.println("Error!!! ReadOnlyBufferException");}}}
CharBuffer
buff1
is declared in line 8.buff1
using the CharBuffer.put()
method in line 9. After adding the first element, the position of buff1
is incremented from 0 to 1.buff1
using the CharBuffer.put()
method in line 10. After adding the second element, the position of buff1
is incremented from 1 to 2.As explained above, using the CharBuffer.put()
method on a read-only buffer throws the ReadOnlyBufferException
. Consider the code snippet below that demonstrates this.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 5;int n2 = 4;try {CharBuffer buff1 = CharBuffer.allocate(n1);CharBuffer buff2 = buff1.asReadOnlyBuffer();buff2.put('a');buff2.put('c');System.out.println("buff2: " + Arrays.toString(buff2.array()));System.out.println("position: " + buff2.position());} catch (IllegalArgumentException e) {System.out.println("Error!!! IllegalArgumentException");} catch (ReadOnlyBufferException e) {System.out.println("Error!!! ReadOnlyBufferException");}}}
CharBuffer
buff1
is declared in line 8.CharBuffer
buff2
is declared in line 10 that is the read-only copy of buff1
.CharBuffer.put()
method is used in line 11 to try writing a value to buff2
. ReadOnlyBufferException
is thrown because buff2
is read-only and cannot be modified.Free Resources