CodeBlanks Logo Icon CodeBlanks

Buffer

Learn the NIO buffer with Buffer.

The Buffer concept

In NIO data is carried inside a Buffer. A buffer is like an array of primitives; it adds state such as position, limit, and capacity. This state lets a single structure manage both reading and writing.

Example: ByteBuffer b = ByteBuffer.allocate(4) allocates a four-byte buffer. b.put((byte) 5) writes one byte; b.flip() switches from write mode to read mode; b.get() reads the next byte. This flow is the basis of block-wise data processing.

allocate and wrap

There are two common ways to create a buffer. ByteBuffer.allocate(n) allocates an empty buffer; you write data into it with put. ByteBuffer.wrap(array) wraps an existing byte array so it can be read directly.

Example: ByteBuffer.wrap(new byte[]{65, 66}) turns the ready array into a buffer; get() returns 65 first, then 66. allocate requests new memory; wrap reuses what exists. Both expose the same ByteBuffer API.

Practice Write and read with ByteBuffer

Create a buffer with ByteBuffer.allocate(4). Write (byte) 10 and (byte) 20 with put. Switch to read mode with flip. Get the first byte with get and print it with System.out.println.

Starter code

Main.java
// Create a buffer with ByteBuffer
// Write two bytes with put
// Print the first byte after flip

Sample solution

Main.java
import java.nio.ByteBuffer;

public class BufferDemo {
    public static void main(String[] args) {
        ByteBuffer b = ByteBuffer.allocate(4);
        b.put((byte) 10);
        b.put((byte) 20);
        b.flip();
        System.out.println(b.get());
    }
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method switches a ByteBuffer from write mode to read mode?

  • allocate
  • flip Correct answer
  • put
  • get

Explanation: flip switches from write mode to read mode.

2 Complete the flip call

Question
b.____();
Answer
b.flip();

Explanation: flip switches to read mode.

3 Match the Buffer methods

Term Meaning
allocate Allocates a buffer
put Writes data
flip Switches mode
get Reads data

All lessons in Expert