FloatBuffer allocate() method in Java With ExamplesThe java.nio.FloatBuffer class has an allocate() function. To create a new float buffer that shares the contents of the supplied buffer, use the FloatBuffer Class. This buffer's contents will create a new buffer. The new buffer will display changes made to this buffer's content, and vice versa; the position, limit, and mark values of the two buffers will remain separate. The capacity, limit, location, and mark values of the new buffer will be the same as those of the current buffer. The new buffer will be read-only if and only if this buffer is read-only, and it will be direct if and only if this buffer is direct. Syntax: Parameter: The capacity of the new buffer is sent as a parameter to this method as a float data type. Return Value: The new float buffer is returned by this function. Exception: If the capacity is an integer that is negative, this function throws the IllegalArgumentException. Example 1:The code defines a Java class named allocateFloat, which illustrates fundamental buffer operations using the FloatBuffer class from the java.nio package. The primary method uses the FloatBuffer.allocate(cap) function to allocate memory after setting the buffer's capacity to 12. Then, it inserts a float value of 9.32F at the buffer's current location (which was initially 0) and another float value of 10.21F right at index position 3. Finally, Arrays.toString(floatbuff.array()) is used to print the contents of the FloatBuffer. This function displays the float values in the buffer by converting the backing array of the buffer to a string representation. Implementation:FileName: allocateFloat.java Output: The FloatBuffer is given by: [9.32, 0.0, 0.0, 10.21, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] Example 2:With the FloatBuffer class, the code creates a Java class named allocateFloatExample2 to show how to manage exceptions. Using a negative capacity of -12, the primary method attempts to allocate an incorrect FloatBuffer. There is an IllegalArgumentException as a result. The catch block catches the exception that is thrown during the attempt to build the FloatBuffer and publishes a message stating that an exception was thrown along with the exception details. The try block encapsulates the exception-throwing process. In terms of buffer allocation, this code demonstrates how to manage illegal arguments. Implementation:FileName: allocateFloatExample2.java Output: Creating an attempt to assign a negative integer. The Exception thrown is: java.lang.IllegalArgumentException: capacity < 0: (-12 < 0) |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India