DoubleBuffer limit() methods in Java with Examples

The java.nio.DoubleBuffer has a limit() function. The DoubleBuffer Class is utilized to adjust the limit of this DoubleBuffer. This method sets the new limit of this buffer by using the parameter, which is the limit to be set. This new limit is not set and is discarded if the mark of this buffer is already defined and more significant than the newly provided limit.

Syntax:

Return Value: The given new limit is set as the new limit of this buffer, and this method returns this buffer after that.

Example 1:

The code shows how to control a DoubleBuffer's limit in Java. Two double values are created and added to a DoubleBuffer with a capacity of 6, before and after calling the limit() method to set the buffer's limit to 2, the contents, location, and limit are provided. The limit is set to the buffer's capacity, and the position initially represents the number of data inserted. The buffer's location remains the same when the limit is updated, but the limit is constrained to the new value, which modifies the amount of the buffer that may be read or written.

Implementation:

FileName: BufferLimitExample1.java

Output:

 
The DoubleBuffer before setting the buffer's limit: [10.5, 20.5, 0.0, 0.0, 0.0, 0.0]
 at the Position: 2
 and the Limit: 6
The DoubleBuffer before setting the buffer's limit: [10.5, 20.5, 0.0, 0.0, 0.0, 0.0]
 at the Position: 2
 and the Limit: 2   

Example 2:

The code demonstrates how to control a DoubleBuffer's limit. Three double values are created and placed into a DoubleBuffer with a capacity of five. The limit is set to the buffer's capacity, and the position initially represents the number of data inserted. The buffer's limit is limited to 2 after calling limit(2), but the position remains the same. This means that only the first two values will be accepted for read or write operations. The buffer's access is impacted by the limit modification, not its contents.

Implementation:

FileName: BufferLimitExample2.java

Output:

 
The DoubleBuffer before setting the buffer's limit: [10.5, 20.5, 30.5, 0.0, 0.0]
 at the Position: 3
 and the Limit: 5
The DoubleBuffer before setting the buffer's limit: [10.5, 20.5, 30.5, 0.0, 0.0]
 at the Position: 2
 and the Limit: 2