ShortBuffer put(int, short) method in Java With Examples
Last Updated :
16 Feb, 2023
The put() method of java.nio.ShortBuffer Class is used to write the given short into this buffer at the given index.
Syntax:
public abstract ShortBuffer put(int index, short s)
Parameters:
- index:This parameter specifies to the index at which the short will be written.It is optional.
- s:This parameter specifies to the short value to be written
Return Value:This method returns this buffer.
Exception:
- IndexOutOfBoundsException – If index is negative or not smaller than the buffer’s limit.
- ReadOnlyBufferException – If this buffer is read-only
Below program illustrates the put() method:
Program 1:
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 3 ;
try {
ShortBuffer sb
= ShortBuffer.allocate(capacity);
sb.put( 0 , ( short ) 400 );
sb.put( 2 , ( short ) 1000 );
sb.put( 1 , ( short ) 30 );
sb.rewind();
System.out.println("Original ShortBuffer: "
+ Arrays.toString(sb.array()));
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception throws : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println("Exception throws : " + e);
}
}
}
|
Output:
Original ShortBuffer: [400, 30, 1000]
Program 2: To demonstrate IndexOutOfBoundsException.
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 3 ;
try {
ShortBuffer sb
= ShortBuffer.allocate(capacity);
sb.put( 0 , ( short ) 31 );
sb.put( 2 , ( short ) 49 );
System.out.println("Trying to put the value"
+ " at the negative index");
sb.put(- 1 , ( short ) 27 );
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception throws : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println("Exception throws : " + e);
}
}
}
|
Output:
Trying to put the value at the negative index
Exception throws: java.lang.IndexOutOfBoundsException
Program 3: To demonstrate ReadOnlyBufferException.
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 3 ;
try {
ShortBuffer sb
= ShortBuffer.allocate(capacity);
ShortBuffer sb1 = sb.asReadOnlyBuffer();
System.out.println("Trying to put the float value"
+ " in read only buffer");
sb1.put( 0 , ( short ) 13 );
}
catch (BufferOverflowException e) {
System.out.println("Exception throws : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println("Exception throws : " + e);
}
}
}
|
Output:
Trying to put the float value in read only buffer
Exception throws: java.nio.ReadOnlyBufferException
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ShortBuffer.html#put-int-short-
Share your thoughts in the comments
Please Login to comment...