What is the java.nio.ShortBuffer class in Java?

The java.nio class represents New IO, an alternative to the regular IO API in Java. java.nio allows you to use channels and buffers to do non-blocking IO.

A channel is like a regular stream, but unlike a stream, a single channel can be used to read and write data, whereas a stream is usually only one-way. You can write to channels asynchronously. Channels usually write to and read from buffers.

A buffer is a block of memory where data can be written and be read later on. A buffer is a finite sequence of elements of any particular primitive type.

The ShortBuffer class

The ShortBuffer class in Java is used to hold a sequence of integer values to be used in an IO operation.

This class defines four categories of operations on the short buffer:

  1. Absolute and relative put and get methods that can read and write single shorts.
  2. Relative bulk get methods that assign adjacent sequences of shorts from this buffer into an array.
  3. Methods for slicing, compacting, and duplicating a short buffer.
  4. Relative bulk put methods that assign adjacent sequences of shorts from a short array or some other short buffer into this buffer.

Methods of the ShortBuffer class

Some of the most used methods are described in the table below.

Method Description
allocate(int capacity) Allocates a new short buffer.
array() Returns the short array that backs the short buffer (optional operation).
compact() Compacts the buffer (optional operation).
asReadOnlyBuffer() Creates a new, read-only buffer that shares this buffer’s content.

The list of all the methods can be found here.

Code

import java.nio.*;
import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
int CAPACITY = 10;
short [] shortArray = {(short)100, (short)20};
ShortBuffer buff1 = ShortBuffer.allocate(CAPACITY);
ShortBuffer buff2 = ShortBuffer.wrap(shortArray);
buff1.put(1, (short)10);
System.out.println(Arrays.toString(buff1.array()));
System.out.println(Arrays.toString(buff2.array()));
}
}

Explanation

  • The code above shows an example of how to create a ShortBuffer object.
  • Two buffers, buff1 and buff2, are created.
  • buff1 is created with the allocate method, whereas buff2 is made by wrapping an already existing short array called shortArray into a buffer using the wrap method.

Free Resources