What is the FloatBuffer limit() method in Java?
FloatBuffer is a built-in class available in the java.nio.FloatBuffer package.
FloatBuffer implements a floating-point buffer and allows the user to perform various categories of operations upon buffers of datatype float.
limit() is a method defined in the FloatBuffer class. The following is the function prototype:
public final FloatBuffer limit(int newLimit)
Parameters and return value
The limit() method takes the following input parameters:
newLimit: A non-negative integer value that is set as the buffer’s new limit.
The method returns the updated FloatBuffer.
Note: Invoking the
limit()method without any input parameters returns the current limit of theFloatBuffer.
Functionality
The limit() method changes the buffer’s
If we try to access an element beyond the buffer’s limit, it results in an exception, regardless of the available capacity.
When we create a FloatBuffer, the limit is set to its capacity by default. The limit() method changes this limit to the newLimit value passed as its input argument. The newLimit value must be non-negative and no larger than the buffer’s capacity.
If a newLimit is not set.
Code
import java.nio.*;import java.util.*;class Edpresso {public static void main( String args[] ) {// Creating a FloatBufferint capacity = 5;FloatBuffer buff = FloatBuffer.allocate(capacity);System.out.println("Capacity: " + capacity);// Printing current limitSystem.out.println("Default limit is: " + buff.limit());// Populating bufferbuff.put(11.33F);buff.put(53.10F);// Setting new limitSystem.out.println("Current position is: " + buff.position());buff.limit(3);System.out.println("New limit is: " + buff.limit());// Printing bufferSystem.out.println(Arrays.toString(buff.array()));// Trying to access beyond limit by adding a 4th elementSystem.out.println("Current position is: " + buff.position());buff.put(3, 63.03F);}}
In the above example, we begin by creating a FloatBuffer with a capacity of 5. At the time of creation, we can see that the limit is set to capacity.
Next, we add two elements. The limit() method is invoked and the buffer’s limit is set to 3.
Trying to add an element beyond the limit of the buffer throws an IndexOutOfBoundsException.
Free Resources