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:
- Absolute and relative
putandgetmethods that can read and write single shorts. - Relative bulk
getmethods that assign adjacent sequences of shorts from this buffer into an array. - Methods for slicing, compacting, and duplicating a short buffer.
- Relative bulk
putmethods 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,
buff1andbuff2, are created. buff1is created with theallocatemethod, whereasbuff2is made by wrapping an already existing short array calledshortArrayinto a buffer using thewrapmethod.