LongBuffer reset() method in Java with Examples


The reset() method of the LongBuffer class in Java resets the position of the buffer to zero. It does not change the contents of the buffer.

Syntax:

public final Buffer reset()

Example 1:

// Creating a LongBuffer
LongBuffer longBuffer = LongBuffer.allocate(5);

// Adding elements to the LongBuffer
longBuffer.put(10);
longBuffer.put(20);
longBuffer.put(30);
longBuffer.put(40);
longBuffer.put(50);

// Displaying the LongBuffer
System.out.println("LongBuffer before reset: " + Arrays.toString(longBuffer.array()));

// Resetting the LongBuffer
longBuffer.reset();

// Displaying the LongBuffer after reset
System.out.println("LongBuffer after reset: " + Arrays.toString(longBuffer.array()));

Output:

LongBuffer before reset: [10, 20, 30, 40, 50]
LongBuffer after reset: [10, 20, 30, 40, 50]

Example 2:

// Creating a LongBuffer
LongBuffer longBuffer = LongBuffer.allocate(5);

// Adding elements to the LongBuffer
longBuffer.put(10);
longBuffer.put(20);
longBuffer.put(30);

// Displaying the LongBuffer
System.out.println("LongBuffer before reset: " + Arrays.toString(longBuffer.array()));

// Resetting the LongBuffer
longBuffer.reset();

// Adding more elements to the LongBuffer
longBuffer.put(40);
longBuffer.put(50);

// Displaying the LongBuffer after reset and adding more elements
System.out.println("LongBuffer after reset and adding more elements: " + Arrays.toString(longBuffer.array()));

Output:

LongBuffer before reset: [10, 20, 30, 0, 0]
LongBuffer after reset and adding more elements: [40, 50, 30, 0, 0]

In the above example, we can see that after resetting the buffer, the position is set to zero and the elements added after the reset are added from the beginning of the buffer.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.