ByteBuffer asShortBuffer() method in Java


A view of the ByteBuffer can be created as a ShortBuffer using the asShortBuffer() method in the class java.nio.ByteBuffer. This method requires no parameters and it returns a short buffer as required. This buffer reflects the changes made to the original buffer and vice versa.

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 = 50;
      try {
         ByteBuffer bufferB = ByteBuffer.allocate(n);
         ShortBuffer bufferS = bufferB.asShortBuffer();
         bufferS.put((short)5);
         bufferS.put((short)9);
         bufferS.put((short)2);
         bufferS.put((short)8);
         bufferS.put((short)3);
         bufferS.rewind();
         short s;
         System.out.print("The ShortBuffer is: ");
         while ((s = bufferS.get()) != 0) {
            System.out.print(s + " ");
         }
      } catch (IllegalArgumentException e) {
         System.out.println("Error!!! IllegalArgumentException");
      } catch (ReadOnlyBufferException e){
         System.out.println("Error!!! ReadOnlyBufferException");
      }
   }
}

Output

The ShortBuffer is: 5 9 2 8 3

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements