Share on Google+Share on Google+

ShortBuffer in java, Create a read-only short buffer that shares the content of short buffer.

Advertisement
In this tutorial, you will see how to create a read-only short buffer that shares the content of short buffer.

Create a read-only short buffer that shares the content of short buffer.

In this tutorial, we will see how to create a read-only short buffer that shares the content of old short buffer.

ShortBuffer API:

The java.nio.ShortBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static ShortBuffer allocate( int capacity) The allocate(..) method allocate a short buffer of given capacity.
abstract ShortBuffer asReadOnlyBuffer() The asReadOnlyBuffer() method create a new read-only buffer that share the content of given short buffer.

Code

import java.nio.*;
import java.nio.ShortBuffer;

public class ReadOnlyBuffer{
    public static void main(String[] arg) {
    ShortBuffer shortBuff = ShortBuffer.allocate(1024);
    shortBuff.put((short75);
    shortBuff.put((short53);
    shortBuff.flip();
    System.out.println("Content in first short buffer : ");
    while (shortBuff.hasRemaining()) {
      System.out.println(shortBuff.get());
    }
    if (shortBuff.isReadOnly()) {
 System.out.println("First short buffer is read-only.");
    else {
System.out.println("first short buffer is not read-only.");
    }
    ShortBuffer shortBuff1 = shortBuff.asReadOnlyBuffer();
    shortBuff1.flip();
System.out.println("Content in read-only short buffer : ");
    while (shortBuff1.hasRemaining()) {
      System.out.println(shortBuff1.get());
    }
    if (shortBuff1.isReadOnly()) {
  System.out.println("Second short buffer is read-only.");
    else {
System.out.println("Second short buffer is not read-only.");
    }
  }
}

Output

C:\>java ReadOnlyBuffer
Content in first short buffer :
75
53
first short buffer is not read only.
Content in second short buffer :
75
53
Second short buffer is read only.

Download this code

Advertisements

Posted on: August 12, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.