What is the CharBuffer limit() method in Java?

The java.nio.CharBuffer class is a class we can use to store a buffer of characters. We can use the limit() method of this class to set the limitLimit of a buffer is its first index that should not be read or written of a buffer.

Declaration

The limit() method can be declared as shown in the code snippet below:


public CharBuffer limit(int limit)

  • limit: The limit to be set of the buffer.

  • If the buffer’s position is greater than the limit, the position is set to limit.
  • If a mark is defined and is greater than the limit, the mark is discarded.

Return value

The limit() method returns the buffer after setting its limit to limit.

Code

The code snippet below demonstrates the use of the limit() method:

import java.nio.*;
import java.util.*;
public class main {
public static void main(String[] args) {
int n1 = 4;
CharBuffer buff1 = CharBuffer.allocate(n1);
buff1.put('a');
buff1.put('c');
System.out.println("buff1: " + Arrays.toString(buff1.array()));
System.out.println("limit at(before setting limit): " + buff1.limit());
System.out.println("limit(3)");
buff1.limit(3);
System.out.println("limit at(after setting limit): " + buff1.limit());
}
}

Explanation

A CharBuffer buff1 is declared in line 7. The limit of buff1 is 4. The limit() method is used in line 15 to set the limit of buff1 to 3.

Free Resources