Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

How to use the ShortBuffer limit() method in Java

Ayesha Naeem

The ShortBuffer limit() method takes a value as input and sets it as the new buffer limit.

A buffer’s limit is the first index whose value should not be read or written.

The program needs to include the following module to use the ShortBuffer limit() method:

 java.nio.ShortBuffer

Syntax

public final ShortBuffer limit(int newLimit)

Parameter and return value

The ShortBuffer limit() method accepts an integer value as the limit and returns the buffer with the new limit.

The value of the limit must be non-negative and smaller than the buffer’s capacity.

The buffer’s position is set to the new limit if it is larger than the new limit. Similarly, a mark is discarded if it is larger than the new limit.

Example

The following example demonstrates how to use the ShortBuffer limit() method in Java.

  • The program creates a short buffer of an initial limit of 4 and populates it with short values.
  • It then resets the limit to 4.
  • The program displays the buffer, position, and limit before and after and applying the limit. The limit changes to 1 and the position to 1.


import java.nio.*;
import java.util.*;

public class main {
	public static void main(String[] args)
	{
		//create a ShortBuffer
		ShortBuffer buf	= ShortBuffer.allocate(4);

		//populate using short values
		buf.put((short)50);
		buf.put((short)20);
		buf.put((short)88);

		// print the short buffer
		System.out.println(	"ShortBuffer before "+ "setting buffer's limit: "+ Arrays.toString(buf.array()));
		System.out.println( "\nPosition: "+ buf.position());
		System.out.println( "\nLimit: "	+ buf.limit());

		//set new limit
		buf.limit(1);

		// print the short buffer
		System.out.println(	"ShortBuffer before "+ "setting buffer's limit: "+ Arrays.toString(buf.array()));
		System.out.println( "\nPosition: "+ buf.position());
		System.out.println( "\nLimit: "	+ buf.limit());
	}
}

RELATED TAGS

java

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring