Java Buffer flip()

PreviousNext

The flip() method of java.nio.ByteBuffer Class flips buffer.

The limit is set to the current position.

The position is set to zero.

Syntax:

public Buffer flip()

Return Value: This method returns this buffer.

Example

The following code shows how to use flip() method:

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

public class Main {
    public static void main(String[] args) {

        // Declare and initialize the byte array
        byte[] bb = { 10, 20, 30 };

        // wrap the byte array into ByteBuffer
        // using wrap() method
        ByteBuffer byteBuffer = ByteBuffer.wrap(bb);

        // Typecast ByteBuffer to Buffer
        Buffer buffer = (Buffer) byteBuffer;

        // set position at index 1
        buffer.position(1);//   w  w  w .   d   em   o 2  s   . c   o m  

        // print the buffer
        System.out.println("Buffer before flip: " + Arrays.toString((byte[]) buffer.array()) + "\nPosition: "
                + buffer.position() + "\nLimit: " + buffer.limit());

        // Flip the Buffer
        // using flip() method
        buffer.flip();

        // print the buffer
        System.out.println("\nBuffer after flip: " + Arrays.toString((byte[]) buffer.array()) + "\nPosition: "
                + buffer.position() + "\nLimit: " + buffer.limit());
    }
}

Result

Examples 2:Java program to demonstrate flip() method

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

public class Main {
    public static void main(String[] args) {

        // defining and allocating ByteBuffer
        // using allocate() method
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);

        // put byte value in byteBuffer
        // using put() method
        byteBuffer.put((byte) 20);
        byteBuffer.put((byte) 30);

        // Typecast ByteBuffer to Buffer
        Buffer buffer = (Buffer) byteBuffer;

        // set position at index 1
        buffer.position(1);/*w  w  w  .  d    e m   o2    s  .c    o m */

        // print the buffer
        System.out.println("Buffer before flip: " + Arrays.toString((byte[]) buffer.array()) + "\nPosition: "
                + buffer.position() + "\nLimit: " + buffer.limit());

        // Flip the Buffer
        // using flip() method
        buffer.flip();

        // print the buffer
        System.out.println("\nBuffer after flip: " + Arrays.toString((byte[]) buffer.array()) + "\nPosition: "
                + buffer.position() + "\nLimit: " + buffer.limit());
    }
}

Result

PreviousNext

Related