What is the FloatBuffer put() method in Java?
java.nio.FloatBuffer is a class we can use to store a buffer of floating-point values. The put() method of the class java.nio.FloatBuffer writes a floating-point value to a buffer. The FloatBuffer.put() method writes the floating-point value at the current
Declaration
The FloatBuffer.put() method can be declared as follows:
buff1.put(x);
buff1: TheFloatBufferin which the floating-point valuexwill be written.x: The floating-point value that will be written tobuff1.
Return value
The FloatBuffer.put() method returns the FloatBuffer buff1 after writing the floating-point value x to it.
Note:
- If the position of
buff1is not less than theof limit The first index of the buffer that should not be read or written buff1, theBufferOverflowExceptionis thrown.- If
buff1is read-only, theReadOnlyBufferExceptionis thrown.
Code
Example 1
Consider the code snippet below, which demonstrates the use of the FloatBuffer.put() method:
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 5;int n2 = 4;try {FloatBuffer buff1 = FloatBuffer.allocate(n1);buff1.put(1.2F);buff1.put(5.9F);System.out.println("buff1: " + Arrays.toString(buff1.array()));System.out.println("position: " + buff1.position());} catch (IllegalArgumentException e) {System.out.println("Error!!! IllegalArgumentException");} catch (ReadOnlyBufferException e) {System.out.println("Error!!! ReadOnlyBufferException");}}}
Explanation
- A
FloatBufferbuff1is declared in line 8. - An element is written to
buff1using theFloatBuffer.put()method in line 9. After adding the first element, the position ofbuff1is incremented from 0 to 1. - Another element is written to
buff1using theFloatBuffer.put()method in line 10. After adding the second element, the position ofbuff1is incremented from 1 to 2.
Example 2
As explained above, using the FloatBuffer.put() method on a read-only buffer throws the ReadOnlyBufferException. Consider the code snippet below which demonstrates this:
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 5;int n2 = 4;try {FloatBuffer buff1 = FloatBuffer.allocate(n1);FloatBuffer buff2 = buff1.asReadOnlyBuffer();buff2.put(1.2F);buff2.put(5.9F);System.out.println("buff2: " + Arrays.toString(buff2.array()));System.out.println("position: " + buff2.position());} catch (IllegalArgumentException e) {System.out.println("Error!!! IllegalArgumentException");} catch (ReadOnlyBufferException e) {System.out.println("Error!!! ReadOnlyBufferException");}}}
Explanation
- A
FloatBufferbuff1is declared in line 8. - A
FloatBufferbuff2is declared in line 10 that is the read-only copy ofbuff1. - The
FloatBuffer.put()method is used in line 11 which tries writing a value tobuff2. TheReadOnlyBufferExceptionis thrown becausebuff2is read-only and cannot be modified.
Free Resources