What is the IntBuffer limit() method in Java?
What is IntBuffer?
IntBuffer is a class in Java that is defined inside the java.nio package. The java.nio package defines buffers, which are a chunk of readable and writeable memory that can be used to easily communicate over NIO channels. There are many buffers in the java.nio package, including IntBuffer. IntBuffer is similar to arrays of different data types with different sizes.
The class IntBuffer allows for various operations. These are:
- absolute and relative get methods that read single ints.
- absolute and relative put methods that write single ints.
- relative bulk get method that can allocate a contiguous chunk of memory from the buffer into arrays.
- relative bulk put method that can allocate contiguous memory from an int array to a buffer.
Overview
The limit method in the IntBuffer class defines the limit for the buffer. If the limit is set to be less than the mark for the integer buffer, it is discarded.
The prototype for the method is:
public final IntBuffer limit(int newLimit)
Parameters
The limit method has one compulsory parameter that defines the new limit.
Return value
The limit method returns IntBuffer with the new limit that has been set.
Example
The following example will help you understand the limit method better. As shown, we first create a buffer and use allocate to define the capacity. Then, we add elements to it and print the limit before we set it. After that, we use the limit method to set the limit and print it:
import java.nio.*;import java.util.*;public class main {public static void main(String[] args){IntBuffer buffer = IntBuffer.allocate(5);buffer.put(1);buffer.put(2);buffer.put(2);System.out.println("Pringing IntBuffer before setting limit: "+ Arrays.toString(buffer.array())+ "\nLimit: "+ buffer.limit());buffer.limit(1);System.out.println("\nPrinting buffer after setting imit: "+ Arrays.toString(buffer.array())+ "\nLimit: "+ buffer.limit());}}
Free Resources