java.nio.DoubleBuffer
is a class that is used to store a buffer of doubles. The arrayOffset()
method of the class java.nio.DoubleBuffer
is used to return the offset of the first element of the buffer inside the buffer’s backing array.
The DoubleBuffer.arrayOffset()
method is declared as follows:
buff.arrayOffset()
buff
: The DoubleBuffer
whose first element offset is required.The DoubleBuffer.arrayOffest()
method returns an int
that is the offset of the first element of buff
.
Note:
- If the buffer is not backed by an accessible array,
UnsupportedOperationException
is thrown.- If the buffer is backed by an array but the array is read-only,
ReadOnlyBufferException
is thrown.
Consider the code snippet below, which demonstrates the use of the DoubleBuffer.arrayOffset()
method.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 5;try {DoubleBuffer buff1 = DoubleBuffer.allocate(n1);buff1.put(1.2);buff1.put(4.9);System.out.println("buff1: " + Arrays.toString(buff1.array()));int foo = buff1.arrayOffset();System.out.println("\nbuff1 array offset: " + foo);} catch (IllegalArgumentException e) {System.out.println("Error!!! IllegalArgumentException");} catch (ReadOnlyBufferException e) {System.out.println("Error!!! ReadOnlyBufferException");} catch (UnsupportedOperationException e) {System.out.println("Error!!! UnsupportedOperationException");}}}
DoubleBuffer
buff1
is declared in line 7 with the capacity n1 = 5
.buff1
using the put()
method in lines 8-9.DoubleBuffer.arrayOffset()
method is used in line 12 to get the offset of the first element of buff1
inside its backing array.Consider another example of the DoubleBuffer.arrayOffset()
method in which ReadOnlyBufferException
is thrown.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 5;try {DoubleBuffer buff1 = DoubleBuffer.allocate(n1);buff1.put(1.2);buff1.put(4.9);System.out.println("buff1: " + Arrays.toString(buff1.array()));DoubleBuffer buff2 = buff1.asReadOnlyBuffer();int foo = buff2.arrayOffset();System.out.println("\nbuff2 array offset: " + foo);} catch (IllegalArgumentException e) {System.out.println("Error!!! IllegalArgumentException");} catch (ReadOnlyBufferException e) {System.out.println("Error!!! ReadOnlyBufferException");} catch (UnsupportedOperationException e) {System.out.println("Error!!! UnsupportedOperationException");}}}
DoubleBuffer
buff1
is declared in line 7 with the capacity n1 = 5
.buff1
using the put()
method in lines 8-9.DoubleBuffer
buff2
is declared in line 12 that is the read-only copy of buff1
.DoubleBuffer.arrayOffset()
method is used in line 14 to get the offset of the first element of buff2
inside its backing array. The ReadOnlyBufferException
is thrown because buff2
is read-only.