CharBuffer get() method in Java

Java 8ProgrammingObject Oriented Programming

The value at the current position of the buffer is read and then incremented using the method get() in the class java.nio.CharBuffer. This method returns the value that is at the current buffer position. Also, the BufferUnderflowException is thrown if underflow situation occurs.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 5;
      try {
         CharBuffer buffer = CharBuffer.allocate(n);
         buffer.put('A');
         buffer.put('P');
         buffer.put('P');
         buffer.put('L');
         buffer.put('E');
         buffer.rewind();
         System.out.println("The CharBuffer is: " + Arrays.toString(buffer.array()));
         char val1 = buffer.get();
         System.out.println("\nThe value at current position of CharBuffer is: " + val1);
         char val2 = buffer.get();
         System.out.println("The value at next position of CharBuffer is: " + val2);
      } catch (IllegalArgumentException e) {
         System.out.println("Error!!! IllegalArgumentException");
      } catch (ReadOnlyBufferException e) {
         System.out.println("Error!!! ReadOnlyBufferException");
      } catch (BufferUnderflowException e) {
         System.out.println("Error!!! BufferUnderflowException");
      }
   }
}

Output

The CharBuffer is: [A, P, P, L, E]
The value at current position of CharBuffer is: A
The value at next position of CharBuffer is: P
raja
Published on 12-Mar-2019 08:21:46
Advertisements